Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Imported calls on a shared brain are readable only by the owner and the people on them (GST-2904) (#9581)

Garry Tane9044af2b1ba
diff --git a/behavior-changes.d/calls_kept_to_attendees_gst2904.md b/behavior-changes.d/calls_kept_to_attendees_gst2904.md
new file mode 100644
index 0000000000..d50254d60f
--- /dev/null
+++ b/behavior-changes.d/calls_kept_to_attendees_gst2904.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+gbrain import --calls on a brain that serves two or more people (two or more enabled person members, and config access.serves is not one) now keeps each new call to the brain owner plus the teammates its Attendees or Participants line names, matched exactly by email, member id or a display name only one person holds. A teammate who was not on a call gets not_found for it. A call with no attendee list goes to the owner only, and names that match nobody are listed in the import output, never guessed. The import stays open as before, with the calls_not_scoped notice and the command to run, when no owner is named, the owner is not enabled, or any connection bound to no person still reads the brain, so the owner's own assistants never lose a call. Pass --readers source to import open as before. Calls imported earlier are not changed. A one-person brain, including one whose assistant sits in group chats, imports exactly as before.
diff --git a/behavior-changes.d/setup_ties_owner_gst2904.md b/behavior-changes.d/setup_ties_owner_gst2904.md
new file mode 100644
index 0000000000..4da7b8213e
--- /dev/null
+++ b/behavior-changes.d/setup_ties_owner_gst2904.md
@@ -0,0 +1,4 @@
+---
+kind: default
+---
+gbrain setup claude-code|codex --serves several --members <ids> --shape company (or both) now writes serve --stdio-member <owner> into the harness entry it installs when no member is named for it, so that assistant reads as the brain owner and imported calls can be kept to the people on them. The owner is the one the brain already has, else the one this run names (--owner, default your login name). Setup says so in a note and in the mcp step. It never ties an entry that already names a member, an entry a plugin serves, or one on a host where OpenClaw or Hermes is installed. With --transcripts, setup now prints one line per imported call with its readers, and the names it could not match with the command that adds a reader. Pass --no-stdio-member to leave the entry unbound as before; imported calls then stay open to the company source's readers, with the calls_not_scoped notice.
diff --git a/changelog.d/gbra592-calls-kept-to-attendees.md b/changelog.d/gbra592-calls-kept-to-attendees.md
new file mode 100644
index 0000000000..efe7400e54
--- /dev/null
+++ b/changelog.d/gbra592-calls-kept-to-attendees.md
@@ -0,0 +1,9 @@
+**Imported calls on a brain shared by two or more people are now kept to the owner and the people who were on them.**
+
+### Changed
+- `gbrain import --calls` on a brain that serves two or more people (enabled person members; group-chat audiences do not count) keeps each new call to the brain owner plus the teammates its `Attendees:` or `Participants:` header names. Names match exactly: an email by email only, else a member id, else a display name exactly one person holds (flagged `matched_by: name`). A call with no list goes to the owner only, and names that match nobody are listed (`unmatched`), never guessed. A teammate who was not on a call gets not_found for it, and links out of it stay hidden from them. Each call's readers get the label guard, so a later agent write cannot drop them. `--readers source` imports open as before. A one-person brain imports exactly as before, and calls imported earlier are not changed.
+- The import stays open, as before, and prints the `calls_not_scoped` notice with one of four reasons (`owner_unset`, `owner_inactive`, `unbound_readers`, `stdio_unbound`) and the command that fixes it, whenever a caller that could be the owner's own would lose a call. Import JSON rows carry `scoped`, `reason`, `readers`, `readers_from`, `matched_by` and `unmatched`.
+- `gbrain setup claude-code|codex --serves several --shape company` (or `both`) ties the harness entry it installs to the brain owner (`serve --stdio-member <owner>`) when no member is named for it, so the owner's own assistant reads every call. With `--transcripts` it prints one line per call with its readers, and each unmatched name with the command that adds a reader. `--no-stdio-member` leaves the entry unbound, and calls then stay open with the notice.
+
+<!-- behavior-change: calls_kept_to_attendees_gst2904 -->
+<!-- behavior-change: setup_ties_owner_gst2904 -->
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 9ba1f41484..687bfd4f6e 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -30,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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 t... (line truncated to 2000 chars)
- `src/commands/setup-brain-layout.ts` — `gbrain setup claude-code|codex --shape personal|company|both [--notes DIR] [--docs DIR] [--transcripts DIR] [--team|--solo]` (GST-2731; guide `docs/guides/brain-layout.md`). Every page is written create-only through `gbrain get` then `gbrain put` children, and only when `get` reports `page_not_found` (empty forms, `status: stub`, one "Example (delete me)" line each): `me/facts`, `me/voice`, `me/how-i-decide` in the run's source, and `COMPANY_PAGES` (`company/facts`, `company/decisions`, `company/pricing`, `company/customers`, `company/calls`, `company/playbooks`) in the `company` source. The company source is kept when it exists, else added with `gbrain sources add company --path <dir>` on a gbrain-owned folder beside the default source's content root (never the person's docs folder; a path there that is not an empty folder fails the company part with an `ask_user` `brain_layout_pages_pending` and the block is written without company lines) with no federation flag, so `sources add` federates it only on a one-person brain (#9396); when it reads back unfederated, setup returns `source_not_in_default_search` with `ask_user`. `--notes` and `--docs` import read only with one `gbrain import DIR --no-embed --json` child each (GBRAIN_SOURCE pins the source; over `IMPORT_INLINE_MAX` = 500 markdown files it returns `brain_layout_import_pending` instead), then check keyless search finds the first file's title in the top 5 (company docs through default search when federated). `--team` creates nothing for the company part and returns `brain_layout_team_next`. A `<!-- gbrain:brain-layout:begin/end -->` block (lines per part) goes into the brain-first target only when the brain-first decision is accepted; `--no-instructions` removes it, `--shape none` removes it and keeps pages and source. A brand-new brain set up without `--shape` asks inline only when `isInteractive()`, otherwise `brain_shape` joins the `first_run_decisions` bundle (defa... (line truncated to 2000 chars)
-- `src/commands/import-calls.ts` — `gbrain import <dir> --calls [--prefix <slug prefix>] [--source <id>] [--json]` (GST-2731), dispatched from `runImport` once the folder resolves (`--calls` also implies `--no-embed`; a `--prefix` value is never read as the folder). `listCallFiles` walks .txt/.md files (dot entries and symlinks skipped), and a single file argument imports that file as an import of its folder would (any other kind of file is an error); `callPageFor` names each `<prefix>/<date>-<title slug>` (date: dated file name, else first line, else modified day; title: rest of a dated file name, else first line, both read after redaction so a credential in either never reaches the title or slug), redacts the whole text with `redactSession` and the user's patterns (`loadImportRedactionPatterns`), redacts the relative path the same way (`redactCallPath`), neutralizes structure lines (`neutralizeOutsideText`) and writes frontmatter `type: meeting`, `facts_backstop: false` and `call_import: {file (redacted), root, path, hash, redactions, embedding_hold: call_import}` (root, path and hash JSON-quoted so they read back as strings), with no `readable_by`. `root` is `callRootId(dir)` (a hash of the folder path), `path` a hash of the folder and the unredacted relative path (so two names a redaction pattern makes alike stay two files, and neither name is stored), and the hash covers title and body, not the date. `call_import` is one of `ANY_SIZE_HOLD_REASONS` in `src/core/page-embedding-budget.ts`, so embed paths skip the page at any size until the owner approves it. `--prefix` is slugified per segment. Each new page goes through the `put_page` handler (trusted local context); a rerun finds the earlier page by `call_import.path` under the prefix, matching the path digest from any folder above the file that an import could have started from (`callPathIds`), or by `root` and `file` for a page stored before `path` existed, claimed by one file per run; a queued `put_page` of the same file is reported `pending`, not written again (not the computed slug, which a new modified day can move) and reports it `unchanged` (same hash) or `kept` (never overwritten); a write still in flight (`write_pending`) is reported `pending` with its `gbrain write-request` command, not as an error, and ... (line truncated to 2000 chars)
+- `src/commands/import-calls.ts` — `gbrain import <dir> --calls [--prefix <slug prefix>] [--source <id>] [--json]` (GST-2731), dispatched from `runImport` once the folder resolves (`--calls` also implies `--no-embed`; a `--prefix` value is never read as the folder). `listCallFiles` walks .txt/.md files (dot entries and symlinks skipped), and a single file argument imports that file as an import of its folder would (any other kind of file is an error); `callPageFor` names each `<prefix>/<date>-<title slug>` (date: dated file name, else first line, else modified day; title: rest of a dated file name, else first line, both read after redaction so a credential in either never reaches the title or slug), redacts the whole text with `redactSession` and the user's patterns (`loadImportRedactionPatterns`), redacts the relative path the same way (`redactCallPath`), neutralizes structure lines (`neutralizeOutsideText`) and writes frontmatter `type: meeting`, `facts_backstop: false` and `call_import: {file (redacted), root, path, hash, redactions, embedding_hold: call_import}` (root, path and hash JSON-quoted so they read back as strings), plus `readable_by` (the owner and the attendees the call's header names, matched by `src/core/meetings/attendees.ts`) when `src/core/access/call-scope.ts` finds a brain serving two or more people whose owner's connections can read scoped pages (GST-2904). `--readers attendees|source` (default attendees) chooses it; otherwise the import stays open and prints the `calls_not_scoped` notice (reasons owner_unset, owner_inactive, unbound_readers, stdio_unbound), and each row adds `scoped`, `reason`, `readers`, `readers_from`, `matched_by` and `unmatched`. `root` is `callRootId(dir)` (a hash of the folder path), `path` a hash of the folder and the unredacted relative path (so two names a redaction pattern makes alike stay two files, and neither name is stored), and the hash covers title and body, not the date. `call_import` is one of `ANY_SIZE_HOLD_REASONS` in `src/core/page-embedding-budget.ts`, so embed paths skip the page at any size until the owner approves it. `--prefix` is slugified per segment. Each new page goes through the `put_page` handler (trusted local context); a rerun finds the earlier page by `call_import.path` under the prefix, matching the path digest from any folder above the file that an import could have started from (`callPathIds`), or by `root` and `file` for a page stored before `path` existed, claimed by one file per run; a queued `put_page` of the same file is reported `pending`, not written again (not the computed slug, which a new modified day can move) and reports it `unchanged` (same hash) or `kept` (never overwritten); a write still in flight (`write_pending`) is reported `pending` with its `gbrain write-request` command, not as an error, and ... (line truncated to 2000 chars)
- `src/commands/doctor/checks/facts-pages.ts` — `facts_undated_lines` (GST-2731, brain category): each `type: facts` page with list lines carrying no YYYY-MM-DD date is a warn naming source, slug and line numbers (never the line text); the fix is `gbrain get <slug> --source <id>` with `ask_user` for the dates; segmented pages are skipped and counted. Read-only. Pinned by `test/doctor-facts-undated-lines.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 Clau... (line truncated to 2000 chars)
- `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`).
diff --git a/docs/guides/brain-layout.md b/docs/guides/brain-layout.md
index bfe837991d..5c5570ba9e 100644
--- a/docs/guides/brain-layout.md
+++ b/docs/guides/brain-layout.md
@@ -60,14 +60,17 @@ gbrain setup claude-code --shape both --notes ~/notes --docs ~/acme-example/docs
files setup prints the import command instead (`gbrain import DIR --calls --prefix
company/calls --no-embed --source company`). It needs the company part on this brain,
so it does not go with `--team`.
-- **Who reads the call pages.** They carry no readers of their own, so whoever can read
- the `company` source reads them, and no one else. Setup prints who that is, for example
- `readable by: everyone who can read source company (this brain serves one person)`, or
- on a brain that serves several people, the members the source's access rules allow
- (`gbrain access who-can-read <slug> --source company` shows the same). There, the member
- keys `gbrain setup --serves several` mints read the `company` source, so every member
- reads every call, including calls they did not attend; other keys read it only when
- their grant names it, and `company` stays out of default search. With `--labelled-only`,
+- **Who reads the call pages.** On a brain that serves one person they carry no readers
+ of their own, so whoever can read the `company` source reads them, and setup prints
+ `readable by: everyone who can read source company (this brain serves one person)`.
+ On a brain that serves several people, `gbrain import --calls` keeps each call to the
+ brain owner plus the teammates its header names (`readable_by`), so a member reads only
+ the calls they were on, and setup prints one line per call with its readers and any
+ names it could not match. When the owner's own connections can't read such pages yet,
+ the import stays open as before and prints `calls_not_scoped` with the command that
+ fixes it ([repair guide](repair.md#calls-not-scoped)); `--readers source` keeps calls
+ open on purpose. Other keys read the `company` source only when their grant names it,
+ and `company` stays out of default search. With `--labelled-only`,
setup adds one `company/` rule, so the line names that rule's readers (the owner and the
members) instead. These are not
your agent conversations: those go to `conversations/` through the
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 48dd288ac2..b56ad68a81 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2061,6 +2061,19 @@ also works on both.
Explicit-only: `gbrain repair --all`, the maintenance cycle and the doctor
remediation plan never run it.
+### Calls not scoped
+
+`gbrain import --calls` on a brain that serves two or more people keeps each new call to the brain owner plus the teammates its `Attendees:` or `Participants:` line names. When some caller that could be the owner's own would lose the call, the import stays open, exactly as before, and prints the `calls_not_scoped` notice with the reason and the one command that fixes it:
+
+| Reason | What it means | Fix |
+|---|---|---|
+| `owner_unset` | The brain names no owner, so no reader list could name one. | `gbrain access owner set <member>` |
+| `owner_inactive` | The owner member is not enabled. | `gbrain access member enable <owner>` |
+| `unbound_readers` | A token or OAuth client bound to no person still reads the brain (grace, `--reads-unscoped`, or a host that does not enforce binding). | The `gbrain auth rescope ... --member <member>` the notice names, for each one |
+| `stdio_unbound` | A local harness connection bound to nobody still reads the brain. | `gbrain setup <harness> --stdio-member <owner>` |
+
+Then import again. `--readers source` imports open on purpose and prints no notice. Calls imported before are not changed by an upgrade.
+
### Stale atoms
`gbrain repair stale-atoms` (explicit-only) retires atoms that drifted from
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index 9bd193590e..c2ca8aa9dd 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -218,6 +218,15 @@ adds the `company` source (`--shape company`), setup labels the people first and
gives their new keys `company`; `company` itself stays out of default search.
Setup leaves the stdio server unbound: stdio sessions read only pages no rule
restricts, and the harness's instructions keep the one-person scoping lines.
+The one exception is a company brain (`--shape company` or `both`): there setup
+ties the Claude Code or Codex entry it installs to the brain owner
+(`serve --stdio-member <owner>`), so your own assistant reads every page and every
+imported call, and calls can be kept to the people on them
+([calls not scoped](repair.md#calls-not-scoped)). It never ties an entry that
+already names a member, one a plugin serves, or one on a host running OpenClaw or
+Hermes; `--no-stdio-member` leaves the entry unbound. With `--transcripts`, setup
+prints one line per imported call with its readers, and each name it could not
+match with the `gbrain repair visibility` command that adds a reader.
For a Claude Code or Codex install only one person uses, bind that harness alone:
`gbrain setup claude-code --stdio-member <member>` (or `codex`) writes
`serve --stdio-member <member>` into that harness's MCP entry, so its sessions read
@@ -225,7 +234,7 @@ as that member, including pages only that member may read. Other harnesses on th
machine, and other machines that open the same brain (PGLite or Postgres), are
unchanged. The member must be enabled (or one of `--members` in the same run).
Re-runs, `gbrain post-upgrade` and doctor fixes keep the entry's member and never
-add one; `--no-stdio-member` removes it, also on a brain that serves several
+add one outside that company case; `--no-stdio-member` removes it, also on a brain that serves several
people. Setup refuses `--stdio-member` where OpenClaw or Hermes is installed,
because those harnesses serve several people, and `gbrain serve` refuses to start
with the flag there too: a bot that answers several people runs
diff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.md
index e6fad4f9da..42a7876fc7 100644
--- a/plugin/skills/setup/SKILL.md
+++ b/plugin/skills/setup/SKILL.md
@@ -40,7 +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. With no owner set it names one (`--owner <id>`, default the login name); relay its `unbound` lines, and rescope a key only on the user's word. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. On `setup_history_choice_required`, ask whether the existing pages stay private (`--labelled-only`) or every member reads them (`--open-history`); never choose for the user. When a re-run's `company/` rule readers wait for `gbrain access apply`, relay it and approve only on the user's word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |
+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. With no owner set it names one (`--owner <id>`, default the login name); relay its `unbound` lines, and rescope a key only on the user's word. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. On `setup_history_choice_required`, ask whether the existing pages stay private (`--labelled-only`) or every member reads them (`--open-history`); never choose for the user. When a re-run's `company/` rule readers wait for `gbrain access apply`, relay it and approve only on the user's word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. With `--shape company` setup ties its own entry to the owner; relay each call's readers line. [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/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv
index 3d06413ddc..3316d8e775 100644
--- a/scripts/engine-raw-sql-baseline.tsv
+++ b/scripts/engine-raw-sql-baseline.tsv
@@ -185,7 +185,7 @@ src/commands/google-setup-tail.ts execute_raw 1
src/commands/google.ts execute_raw 1
src/commands/graph-query.ts execute_raw 1
src/commands/guests.ts execute_raw 1
-src/commands/import-calls.ts execute_raw 2
+src/commands/import-calls.ts execute_raw 3 GST-2904 (open before #9641): reads the committed call page's id, frontmatter readers and whether a page_label_guards row exists, locked FOR UPDATE inside the maintenance transaction that raises the guard; no typed engine method exists yet
src/commands/import.ts execute_raw 6
src/commands/init-embedding-plane.ts execute_raw 1
src/commands/init-prefer-postgres.ts execute_raw 5
diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.md
index 7ca6da28b6..7d7439ab88 100644
--- a/skills/setup/SKILL.md
+++ b/skills/setup/SKILL.md
@@ -39,7 +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. With no owner set it names one (`--owner <id>`, default the login name); relay its `unbound` lines, and rescope a key only on the user's word. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. On `setup_history_choice_required`, ask whether the existing pages stay private (`--labelled-only`) or every member reads them (`--open-history`); never choose for the user. When a re-run's `company/` rule readers wait for `gbrain access apply`, relay it and approve only on the user's word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |
+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. With no owner set it names one (`--owner <id>`, default the login name); relay its `unbound` lines, and rescope a key only on the user's word. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. On `setup_history_choice_required`, ask whether the existing pages stay private (`--labelled-only`) or every member reads them (`--open-history`); never choose for the user. When a re-run's `company/` rule readers wait for `gbrain access apply`, relay it and approve only on the user's word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. With `--shape company` setup ties its own entry to the owner; relay each call's readers line. [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.history.json b/skills/skills.lock.history.json
index 270e0bed49..e453dc56bf 100644
--- a/skills/skills.lock.history.json
+++ b/skills/skills.lock.history.json
@@ -1102,7 +1102,8 @@
"d5250abf65d7fb822646232ed6a27a09ac4443377065b58182292023c6b3606a",
"d6b82f858e60699ff8c5ee82d61c94a98c2fbc7a852b5f74571e7ab3f0921139",
"f014513080eb81e90f0cc0203ca944698fdff250059be0267f0498c5b69c5416",
- "f65cbdee8b6153bf2557766de5e9887f2702b8d80ac32e3c875c45442eef249e"
+ "f65cbdee8b6153bf2557766de5e9887f2702b8d80ac32e3c875c45442eef249e",
+ "fbc57e68a559d2aa3bf03b0a5bd36a9e10fccb5e14653803e54d3e34ca4239aa"
],
"signal-detector/SKILL.md": [
"0ffa92ceee026f8ce1fa6fbea45dc8ebe9689a36d13683ec102c33402a50898a",
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 3cfd2e8578..7e577e1a83 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -212,7 +212,7 @@
"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489",
"schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5",
"schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",
- "setup/SKILL.md": "f65cbdee8b6153bf2557766de5e9887f2702b8d80ac32e3c875c45442eef249e",
+ "setup/SKILL.md": "fbc57e68a559d2aa3bf03b0a5bd36a9e10fccb5e14653803e54d3e34ca4239aa",
"signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60",
"skill-autobench/SKILL.md": "29f5760dcfd823c5f7d4fb50a3cf4e36601b1b8125e57d6bf83645a41f97f613",
"skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",
@@ -226,7 +226,7 @@
"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e",
"skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb",
"skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",
- "skills.lock.history.json": "3d73c9db7274e3269ddc81f5823c569488e92796f41319fb2172b19f9a7df4f8",
+ "skills.lock.history.json": "7a198740e6de691e24f50f39093d5c52b54ee4fcfc522d703f2eeb478844e5a3",
"smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5",
"soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8",
"storage-manifest/SKILL.md": "1debbefba61007a17cda1525496875d1edfde90642adf3ec031f25a71724807e",
diff --git a/src/commands/import-calls.ts b/src/commands/import-calls.ts
index cdb2a30f94..84a9f9cc2b 100644
--- a/src/commands/import-calls.ts
+++ b/src/commands/import-calls.ts
@@ -40,6 +40,18 @@ import { PENDING_WRITE_EXIT_CODE } from '../core/exit-codes.ts';
import { cliRenderContext } from '../core/agent-output.ts';
import { TERMINAL_STATES } from '../core/persistence/model.ts';
import type { WriteReceipt } from '../core/persistence/types.ts';
+import { callReadersFor, parseCallAttendees, type CallAttendee } from '../core/meetings/attendees.ts';
+import { callScopeGate, type CallScopeGate, type CallsNotScopedReason, type UnboundStdio } from '../core/access/call-scope.ts';
+import { claudeUserMcpConfigPath, codexConfigPath } from '../core/bootstrap/host-specs.ts';
+import { readCodexTomlTable } from '../core/bootstrap/codex-toml.ts';
+import { localSetupRecords } from '../core/setup/local-receipts.ts';
+import { sharedStdioHarness } from './setup-serves.ts';
+import { registeredStdioMember } from '../core/stdio-member-flag.ts';
+import { normalizeReaders } from '../core/access/principals.ts';
+import { raisePageLabelGuard } from '../core/trust/page-write.ts';
+import { maintenanceTransaction } from '../core/persistence/attribution.ts';
+import { noticeBlock, renderNotice } from '../core/agent-output.ts';
+import { opError } from '../core/ops/contract.ts';
export const CALL_FILE_RE = /\.(txt|md)$/i;
export const DEFAULT_CALL_PREFIX = 'calls';
@@ -59,6 +71,8 @@ export interface CallPage {
content: string;
redactions: number;
hash: string;
+ /** GST-2904: the attendees the call's header names (redacted), or null. */
+ attendees: CallAttendee[] | null;
}
export interface CallFileResult {
@@ -72,6 +86,41 @@ export interface CallFileResult {
/** A pending write: its request and the command that reads its receipt. */
request_id?: string;
poll?: string;
+ /** GST-2904, on a brain that serves two or more people: whether the call is kept to the owner and its attendees. */
+ scoped?: boolean;
+ /** Why it is not: --readers source, or the calls_not_scoped reason. */
+ reason?: CallsNotScopedReason | 'readers_source';
+ /** Who reads the call by its page (member ids), or null when its source's readers do. */
+ readers?: string[] | null;
+ /** computed by this import, stored on the page already, or pending in a write still being made. */
+ readers_from?: 'computed' | 'stored' | 'pending';
+ matched_by?: Record<string, 'email' | 'id' | 'name'>;
+ unmatched?: string[];
+}
+
+/**
+ * The local stdio connections on this machine bound to nobody: each claude-code or codex entry `gbrain setup` installed
+ * for this brain home without --stdio-member (a plugin-served entry counts as unbound), and a harness several people talk
+ * to (OpenClaw, Hermes), which no --stdio-member can bind. An entry that cannot be read counts as unbound.
+ */
+export function callScopeStdio(): UnboundStdio[] {
+ const out: UnboundStdio[] = [];
+ for (const record of localSetupRecords().filter(r => r.status === 'installed')) {
+ let entry: unknown;
+ try {
+ if (record.harness === 'claude-code') {
+ const cfg = JSON.parse(readFileSync(claudeUserMcpConfigPath(), 'utf8')) as { mcpServers?: Record<string, unknown>; projects?: Record<string, { mcpServers?: Record<string, unknown> }> };
+ entry = (record.scope === 'project' && record.projectDir ? cfg.projects?.[record.projectDir]?.mcpServers : cfg.mcpServers)?.[record.name];
+ } else if (record.harness === 'codex') entry = readCodexTomlTable(codexConfigPath(), ['mcp_servers', record.name]);
+ else continue;
+ } catch { entry = undefined; }
+ if (registeredStdioMember(entry) !== undefined) continue;
+ out.push({ harness: record.harness, name: record.name,
+ argv: ['gbrain', 'setup', record.harness, ...(record.name === 'gbrain' ? [] : ['--name', record.name]), ...(record.scope === 'project' ? ['--scope', 'project'] : [])] });
+ }
+ const shared = sharedStdioHarness();
+ if (shared) out.push({ harness: shared, argv: null });
+ return out;
}
/** .txt and .md files under `dir`, sorted; dot entries and symlinks are skipped. */
@@ -148,7 +197,24 @@ export function callPageFor(rel: string, text: string, mtimeMs: number, prefix:
' embedding_hold: call_import',
'---',
].join('\n');
- return { rel, file: path.file, ...(pathId ? { path: pathId } : {}), slug: `${prefix}/${date}-${slugTitle}`, title, date, date_from: fromName ? 'file_name' : fromLine ? 'first_line' : 'modified', content: `${frontmatter}\n${body}\n`, redactions: redacted.redactionCount + path.redactions, hash };
+ return { rel, file: path.file, ...(pathId ? { path: pathId } : {}), slug: `${prefix}/${date}-${slugTitle}`, title, date, date_from: fromName ? 'file_name' : fromLine ? 'first_line' : 'modified', content: `${frontmatter}\n${body}\n`, redactions: redacted.redactionCount + path.redactions, hash,
+ attendees: callAttendees(text, redacted.session.messages[0]!.text) };
+}
+
+/**
+ * GST-2904: the header's attendees, printed as redacted (a redaction pattern may cover an address) but matched by the
+ * address the file gives, which is compared and never stored. A header the redaction reshaped is read redacted only.
+ */
+function callAttendees(raw: string, redacted: string): CallAttendee[] | null {
+ const shown = parseCallAttendees(redacted);
+ const given = parseCallAttendees(raw);
+ if (!shown || !given || shown.length !== given.length) return shown;
+ return shown.map((a, i) => (given[i]!.email ? { entry: a.entry, email: given[i]!.email } : a));
+}
+
+/** GST-2904: the call page kept to `readers` (member ids, the owner first): its readable_by line rides the one put_page write. */
+export function withCallReaders(content: string, readers: readonly string[]): string {
+ return content.replace('\nfacts_backstop: false\n', `\nreadable_by: ${JSON.stringify(readers)}\nfacts_backstop: false\n`);
}
const callImportOf = (frontmatter: unknown): { file?: unknown; root?: unknown; path?: unknown; hash?: unknown } | null => {
@@ -183,9 +249,14 @@ function flagValue(args: string[], name: string): string | undefined {
}
/** Import every call file under `dir` (or the one call file `dir` names, as its folder would) once, into `sourceId` (default when unset). */
-export async function runCallImport(engine: BrainEngine, dir: string, args: string[], opts: { sourceId?: string; json: boolean }): Promise<RunImportResult> {
+export async function runCallImport(engine: BrainEngine, dir: string, args: string[], opts: { sourceId?: string; json: boolean; unboundStdio?: () => UnboundStdio[] }): Promise<RunImportResult> {
const prefix = (flagValue(args, '--prefix') ?? DEFAULT_CALL_PREFIX).split('/').map(slugifySegment).filter(Boolean).join('/') || DEFAULT_CALL_PREFIX;
const sourceId = opts.sourceId ?? 'default';
+ const readersFlag = flagValue(args, '--readers') ?? 'attendees';
+ if (readersFlag !== 'attendees' && readersFlag !== 'source') {
+ throw opError('invalid_params', `--readers must be attendees or source, not "${readersFlag}"; nothing was imported.`,
+ 'Use --readers attendees (the default: on a brain that serves several people each call is kept to the owner and its attendees) or --readers source (each call is readable by everyone who reads its source).');
+ }
const patterns = loadImportRedactionPatterns();
const { operations } = await import('../core/operations.ts');
const putPage = operations.find(op => op.name === 'put_page')!;
@@ -196,19 +267,45 @@ export async function runCallImport(engine: BrainEngine, dir: string, args: stri
const folder = single ? dirname(dir) : dir;
const files = single ? [dir] : listCallFiles(dir);
const root = callRootId(folder);
+ const gate: CallScopeGate = await callScopeGate(engine, opts.unboundStdio ?? callScopeStdio);
+ const scope = gate.applies ? (readersFlag === 'source' ? { scoped: false as const, reason: 'readers_source' as const } : gate.scoped ? { scoped: true as const } : { scoped: false as const, reason: gate.reason }) : null;
+ const scopeOf = (readers: string[] | null, from: 'computed' | 'stored' | 'pending', extra: Partial<CallFileResult> = {}): Partial<CallFileResult> =>
+ scope ? { ...scope, readers, readers_from: from, ...extra } : {};
+ const memberIds = (frontmatter: unknown): string[] | null => {
+ const normalized = normalizeReaders(frontmatter);
+ if (!normalized) return null;
+ const raw = (frontmatter as { readable_by?: unknown }).readable_by;
+ const listed = Array.isArray(raw) ? raw.map(String) : [String(raw)];
+ const ids = listed.map(r => r.trim().replace(/^member:/i, ''));
+ return JSON.stringify([...new Set(ids.map(r => normalizeReaders({ readable_by: r })?.[0]))].sort()) === JSON.stringify(normalized) ? ids : normalized;
+ };
+ /** A scoped call's readers are guarded as soon as its page row lands (its git commit may still be queued), so a later write below the operator's tier cannot drop them. */
+ const guard = async (slug: string, readers: string[] | null): Promise<void> => {
+ if (!scope?.scoped || !readers) return;
+ await maintenanceTransaction(engine, async tx => {
+ await tx.lockPageKeys([{ sourceId, slug }]);
+ const [page] = await tx.executeRaw<{ id: number; frontmatter: Record<string, unknown> | null; guarded: boolean }>(
+ 'SELECT p.id, p.frontmatter, EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = p.id) AS guarded FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL FOR UPDATE', [sourceId, slug]);
+ if (!page || page.guarded === true || JSON.stringify(normalizeReaders(page.frontmatter)) !== JSON.stringify(normalizeReaders({ readable_by: readers }))) return;
+ await raisePageLabelGuard(tx, sourceId, slug);
+ });
+ };
const prior = await engine.executeRaw<{ slug: string; root: string | null; file: string; path: string | null }>(
`SELECT slug, frontmatter->'call_import'->>'root' AS root, frontmatter->'call_import'->>'file' AS file, frontmatter->'call_import'->>'path' AS path FROM pages
WHERE source_id = $1 AND deleted_at IS NULL AND starts_with(slug, $2) AND frontmatter->'call_import'->>'file' IS NOT NULL`,
[sourceId, `${prefix}/`]);
const byPath = new Map(prior.filter(r => r.path).map(r => [r.path, r.slug]));
const byFile = new Map(prior.filter(r => !r.path && r.root === root).map(r => [r.file, r.slug]));
- const pendingByPath = new Map<string, { slug: string; request_id: string }>();
+ const pendingByPath = new Map<string, { slug: string; request_id: string; readers: string[] | null }>();
for (const row of await engine.executeRaw<{ slug: string; request_id: string; content: string | null }>(
`SELECT slug, request_id::text AS request_id, intent->>'content' AS content FROM persistence_requests
WHERE source_id = $1 AND operation = 'put_page' AND starts_with(slug, $2) AND NOT (state = ANY($3::text[])) ORDER BY sequence`,
[sourceId, `${prefix}/`, [...TERMINAL_STATES]])) {
const id = /^ {2}path: "([0-9a-f]{16})"$/m.exec(row.content ?? '')?.[1];
- if (id && !pendingByPath.has(id)) pendingByPath.set(id, { slug: row.slug, request_id: row.request_id });
+ const readersLine = /^readable_by: (\[.*\])$/m.exec(row.content ?? '')?.[1];
+ let readers: string[] | null = null;
+ try { readers = readersLine ? JSON.parse(readersLine) as string[] : null; } catch { readers = null; }
+ if (id && !pendingByPath.has(id)) pendingByPath.set(id, { slug: row.slug, request_id: row.request_id, readers });
}
const sameImport = (frontmatter: unknown, page: CallPage, ids: Set<string>): boolean => {
const ci = callImportOf(frontmatter);
@@ -240,7 +337,7 @@ export async function runCallImport(engine: BrainEngine, dir: string, args: stri
const receipt = await getWriteRequest.handler(ctx, { request_id: held.request_id }).catch(() => null) as WriteReceipt | null;
if (!receipt || !acceptPendingCovers(receipt)) uncovered++;
results.push({ file: page.file, slug: held.slug, date_from: page.date_from, redactions: page.redactions, status: 'pending', request_id: held.request_id,
- poll: pollCommand(held.request_id, undefined, cliRenderContext().routing) });
+ poll: pollCommand(held.request_id, undefined, cliRenderContext().routing), ...scopeOf(held.readers, 'pending') });
continue;
}
let slug = priorSlug ?? (used.has(page.slug) ? suffixed : page.slug);
@@ -253,16 +350,24 @@ export async function runCallImport(engine: BrainEngine, dir: string, args: stri
const base = { file: page.file, slug, date_from: page.date_from, redactions: page.redactions };
if (existing) {
if (!sameImport(existing.page.frontmatter, page, ids)) results.push({ ...base, status: 'error', error: `${slug} already holds another page; rename the file to import it` });
- else results.push({ ...base, status: callImportOf(existing.page.frontmatter)?.hash === page.hash ? 'unchanged' : 'kept' });
+ else {
+ const stored = memberIds(existing.page.frontmatter);
+ await guard(slug, stored);
+ results.push({ ...base, status: callImportOf(existing.page.frontmatter)?.hash === page.hash ? 'unchanged' : 'kept', ...scopeOf(stored, 'stored') });
+ }
continue;
}
+ const kept = scope?.scoped && gate.applies && gate.scoped ? callReadersFor(page.attendees, gate.owner, gate.members) : null;
+ const fields = kept ? scopeOf(kept.readers, 'computed', { matched_by: kept.matched_by, unmatched: kept.unmatched }) : scopeOf(null, 'computed');
try {
- const receipt = await putPage.handler(ctx, { slug, content: page.content, request_id: randomUUID() }) as { persistence?: { git_state?: string } } | null;
- results.push({ ...base, status: 'imported', ...(receipt?.persistence?.git_state ? { git_state: receipt.persistence.git_state } : {}) });
+ const receipt = await putPage.handler(ctx, { slug, content: kept ? withCallReaders(page.content, kept.readers) : page.content, request_id: randomUUID() }) as { persistence?: { git_state?: string } } | null;
+ const gitState = receipt?.persistence?.git_state;
+ if (kept) await guard(slug, kept.readers);
+ results.push({ ...base, status: 'imported', ...(gitState ? { git_state: gitState } : {}), ...fields });
} catch (e) {
const receipt = pendingReceiptOf(e);
if (receipt && !acceptPendingCovers(receipt)) uncovered++;
- if (receipt) results.push({ ...base, status: 'pending', request_id: receipt.request_id, poll: pollCommand(receipt.request_id, (e as { fix?: { argv?: readonly string[] } }).fix, cliRenderContext().routing) });
+ if (receipt) results.push({ ...base, status: 'pending', request_id: receipt.request_id, poll: pollCommand(receipt.request_id, (e as { fix?: { argv?: readonly string[] } }).fix, cliRenderContext().routing), ...(kept ? scopeOf(kept.readers, 'pending', { matched_by: kept.matched_by, unmatched: kept.unmatched }) : fields) });
else results.push({ ...base, status: 'error', error: e instanceof Error ? e.message : String(e) });
}
}
@@ -272,14 +377,27 @@ export async function runCallImport(engine: BrainEngine, dir: string, args: stri
const pending = count('pending');
const redactions = results.filter(r => r.status === 'imported').reduce((n, r) => n + (r.redactions ?? 0), 0);
const failures = results.filter(r => r.status === 'error').map(r => ({ path: r.file, error: r.error ?? 'unknown error' }));
+ const notice = gate.applies && !gate.scoped && readersFlag === 'attendees' ? gate.notice : null;
+ const placed = results.filter(r => r.status !== 'error');
+ const scopedSummary = scope ? {
+ scoped: placed.filter(r => r.scoped && (r.readers?.length ?? 0) > 1).length,
+ owner_only: placed.filter(r => r.scoped && r.readers?.length === 1).length,
+ not_scoped: placed.filter(r => !r.scoped).length,
+ } : null;
if (opts.json) {
await writeJsonDocument(JSON.stringify({
status: errors > 0 ? 'partial' : pending > 0 ? 'pending' : 'success', mode: 'calls', source_id: sourceId, prefix, total_files: files.length,
- imported, unchanged: count('unchanged'), kept: count('kept'), pending, errors, redactions, pages: results, failures,
+ imported, unchanged: count('unchanged'), kept: count('kept'), pending, errors, redactions, ...(scopedSummary ? { readers: scopedSummary } : {}), pages: results, failures,
+ ...(notice ? { notices: [renderNotice(notice, cliRenderContext())] } : {}),
}));
} else {
console.log(`Call import into source ${sourceId} under ${prefix}/: ${imported} imported, ${count('unchanged')} unchanged, ${count('kept')} kept (changed since import, not overwritten), ${pending} pending (accepted, still being written), ${errors} error(s); ${redactions} credential(s) redacted.`);
- for (const r of results) console.log(` ${r.status.padEnd(9)} ${r.slug || '-'} <- ${r.file}${r.error ? ` (${r.error})` : ''}${r.poll ? ` (still being written; check with ${r.poll} before importing again)` : ''}`);
+ if (scopedSummary) console.log(` readers ${scopedSummary.scoped} kept to the owner and their attendees, ${scopedSummary.owner_only} kept to the owner only, ${scopedSummary.not_scoped} readable by everyone who reads source ${sourceId}.`);
+ for (const r of results) {
+ const who = r.readers ? ` [readers: ${r.readers.join(', ')}${r.unmatched?.length ? `; not matched: ${r.unmatched.map(u => JSON.stringify(u)).join(', ')}` : ''}]` : '';
+ console.log(` ${r.status.padEnd(9)} ${r.slug || '-'} <- ${r.file}${who}${r.error ? ` (${r.error})` : ''}${r.poll ? ` (still being written; check with ${r.poll} before importing again)` : ''}`);
+ }
+ if (notice) process.stderr.write(noticeBlock(renderNotice(notice, cliRenderContext())) + '\n');
}
if (!errors && pending && (!acceptPendingRequested(getCliOptions().acceptPending) || uncovered > 0)) setCliExitVerdict(PENDING_WRITE_EXIT_CODE);
return { imported, skipped: results.length - imported, errors, chunksCreated: 0, failures };
diff --git a/src/commands/setup-brain-layout.ts b/src/commands/setup-brain-layout.ts
index 4706e4ccb9..dc68a0c76d 100644
--- a/src/commands/setup-brain-layout.ts
+++ b/src/commands/setup-brain-layout.ts
@@ -257,6 +257,10 @@ export interface TranscriptsOutcome extends ImportOutcome {
readers?: { members: 'every_source_reader' | string[] | null; serves: 'one' | 'several' | null; detail: string };
/** What can send call text off this machine, from doctor's auto_chronicle and extract_atoms_backlog checks. */
egress?: { leaves: boolean | null; detail: string };
+ /** GST-2904: each call the import kept to the owner and its attendees, with the names it could not match. */
+ calls?: Array<{ slug: string; readers: string[]; unmatched: string[] }>;
+ /** GST-2904: why the import kept new calls open to the source's readers (the calls_not_scoped notice), and its fix. */
+ not_scoped?: { reason: string; why: string; command: string | null };
}
export interface LayoutOutcome {
@@ -357,14 +361,19 @@ function importCalls(exec: Run, launcher: string, dir: string, dryRun: boolean):
if (count > IMPORT_INLINE_MAX) return { dir, files: count, action: 'deferred', argv, detail: `more than ${IMPORT_INLINE_MAX} call files; run the import as its own step` };
if (dryRun) return { dir, files: count, action: 'imported', argv, detail: 'would import (read only)' };
const imp = exec([launcher, ...args, '--json'], undefined, COMPANY_SOURCE);
- let doc: { imported?: number; unchanged?: number; kept?: number; errors?: number; redactions?: number; pages?: Array<{ slug: string; status: string; error?: string }> };
+ let doc: { imported?: number; unchanged?: number; kept?: number; errors?: number; redactions?: number; notices?: Array<{ code: string; why: string; fix?: { argv?: string[] } }>;
+ pages?: Array<{ slug: string; status: string; error?: string; scoped?: boolean; reason?: string; readers?: string[] | null; unmatched?: string[] }> };
try { doc = JSON.parse(imp.stdout) as typeof doc; } catch { return { dir, files: count, action: 'failed', argv, detail: lastLine(imp.stderr || imp.stdout) }; }
const landed = (doc.pages ?? []).filter(p => p.status !== 'error');
const failed = (doc.pages ?? []).find(p => p.status === 'error');
const counts = { imported: doc.imported ?? 0, unchanged: doc.unchanged ?? 0, kept: doc.kept ?? 0, redactions: doc.redactions ?? 0 };
if (!landed.length && (failed || imp.code !== 0)) return { dir, files: count, action: 'failed', argv, ...counts, detail: failed?.error ?? lastLine(imp.stderr) };
+ const calls = landed.filter(p => p.scoped && p.readers?.length).map(p => ({ slug: p.slug, readers: p.readers!, unmatched: p.unmatched ?? [] }));
+ const open = doc.notices?.find(n => n.code === 'calls_not_scoped');
+ const reason = landed.find(p => p.scoped === false && p.reason)?.reason;
return { dir, files: count, action: 'imported', argv, ...counts, ...(failed ? { detail: `${doc.errors} file(s) not imported: ${failed.error}` } : {}),
- ...(landed[0] ? { readers: readersOf(exec, launcher, landed[0].slug) } : {}) };
+ ...(calls.length ? { calls } : landed[0] ? { readers: readersOf(exec, launcher, landed[0].slug) } : {}),
+ ...(open ? { not_scoped: { reason: reason ?? 'unknown', why: open.why, command: open.fix?.argv?.length ? open.fix.argv.join(' ') : null } } : {}) };
}
type DoctorChecks = Array<{ name: string; details?: Record<string, unknown> }>;
@@ -532,6 +541,14 @@ export function describeLayout(o: LayoutOutcome, dryRun: boolean): string[] {
lines.push(t.action !== 'imported' ? ` calls ${t.action}: ${t.detail ?? ''} (${t.argv.join(' ')})`
: ` calls ${would}import ${t.files} call file(s) from ${t.dir} as ${CALLS_PREFIX}/<date>-<title> (read only, credentials redacted)`
+ (t.imported === undefined ? '' : `: ${t.imported} new, ${t.unchanged} unchanged, ${t.kept} kept, ${t.redactions} credential(s) redacted${t.detail ? `; ${t.detail}` : ''}`));
+ if (t.calls) {
+ lines.push(' each kept to the people on it (the owner reads every call):');
+ for (const c of t.calls) {
+ lines.push(` ${c.slug} ${c.readers.join(', ')}${c.readers.length === 1 && !c.unmatched.length ? ' (no other attendee matched a member)' : ''}`);
+ if (c.unmatched.length) lines.push(` not matched: ${c.unmatched.map(u => JSON.stringify(u)).join(', ')}. To add a reader: gbrain repair visibility --source ${COMPANY_SOURCE} --slug ${c.slug} --readers ${c.readers.join(',')},<member>`);
+ }
+ }
+ if (t.not_scoped) lines.push(` calls kept open, as before: ${t.not_scoped.why}${t.not_scoped.command ? ` Run: ${t.not_scoped.command}` : ''}`);
if (t.readers) lines.push(` readable by: ${t.readers.detail}`);
if (t.egress) lines.push(` what leaves this machine: ${t.egress.detail}`);
}
diff --git a/src/commands/setup-serves.ts b/src/commands/setup-serves.ts
index b00309afff..e274987cda 100644
--- a/src/commands/setup-serves.ts
+++ b/src/commands/setup-serves.ts
@@ -202,7 +202,8 @@ function runServesSeveral(launcher: string, roster: string[], flags: ServesFlags
return { mode: 'several', ...from, receipt, proof };
}
-export interface ServesPlan { roster: string[]; status: ServesStatus | null; owner?: ServesOwner }
+/** `tie`: the owner a company setup's own harness entry reads as (GST-2904), known to be an enabled member once this run's labelling lands. */
+export interface ServesPlan { roster: string[]; status: ServesStatus | null; owner?: ServesOwner; tie?: string }
/**
* Before setup writes anything: the roster (an empty one refuses), the brain's serves view (none for a brain setup is
@@ -228,7 +229,8 @@ export function servesPreflight(flags: ServesFlags, launcher: string, harness: s
const preview = run ? parsed<ServesReceipt>(run.stdout) : null;
const said = run ? `${run.stdout}\n${run.stderr}` : '';
const previewError = said.match(/"code"\s*:\s*"([a-z0-9_]+)"/)?.[1] ?? run?.stderr.trim().split('\n')[0]?.slice(0, 200);
- return historyRefusal(status, preview, flags, harness, roster, owner, previewError || undefined) ?? { roster, status, owner };
+ const tie = status?.owner ?? (!status ? owner.id : preview?.owner && preview.owner.action !== 'blocked' ? preview.owner.id : undefined);
+ return historyRefusal(status, preview, flags, harness, roster, owner, previewError || undefined) ?? { roster, status, owner, ...(tie ? { tie } : {}) };
}
if (named && !status?.enabled_members.includes(named)) {
return opError('invalid_params', `--stdio-member ${named} is not an enabled member of this brain, so the ${harness} sessions would read as nobody; nothing was written.`,
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 7f1d9fcc70..caf523d674 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -60,7 +60,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 { readServesStatus, sharedStdioHarness, servesAfterLayout, servesApply, servesLines, servesOk, servesPreflight, type EntryBinding, type ServesOutcome } from './setup-serves.ts';
+import { readServesStatus, sharedStdioHarness, servesAfterLayout, servesApply, servesLines, servesOk, servesPreflight, type EntryBinding, type ServesOutcome, type ServesPlan } from './setup-serves.ts';
import type { McpSurface } from '../mcp/surface.ts';
import {
SETUP_CAPABILITIES,
@@ -184,8 +184,10 @@ Flags:
of --members). Other harnesses on this host are unchanged. Use it for a
harness only ID uses; refused where OpenClaw or Hermes is installed
(give each person their own HTTP key there). A re-run keeps the entry's
- member; setup never adds one on its own.
- --no-stdio-member Remove --stdio-member from this harness's entry.
+ member. With --serves several and --shape company or both, an entry
+ with no member is tied to the brain owner.
+ --no-stdio-member Remove --stdio-member from this harness's entry, or leave it unbound.
+
--remove Remove exactly what setup wrote (unchanged entries only), the
brain-first instruction block included. The brain and your
notes stay. Combine with --dry-run to preview.
@@ -618,7 +620,7 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string
const again = inspectClaudeSetup(listed);
if (again.mcp.state === 'current') { plan = listed; found = again; }
}
- const binding = entryBinding(flags, found.mcp.stdioMember);
+ let binding = entryBinding(flags, found.mcp.stdioMember);
if (binding.member) { plan = { ...plan, stdioMember: binding.member }; found = inspectClaudeSetup(plan); }
if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags), out);
@@ -653,6 +655,8 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string
}
const servesPlan = servesPreflight(flags, launcher, 'claude-code', !!cfg, !!liveOwner?.ours, binding);
if (servesPlan instanceof OperationError) return refuse(servesPlan, out);
+ const tie = ownerTie(flags, servesPlan, binding, !!pluginOwner);
+ if (tie) { binding = { member: tie, previous: binding.previous }; plan = { ...plan, stdioMember: tie }; found = inspectClaudeSetup(plan); target.stdio_member = tie; say(out, `note: ${tieNote(tie)}`); }
const brainCreate = !cfg;
const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), '--json'];
@@ -819,7 +823,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
const again = inspectCodexSetup(listed);
if (again.mcp.state === 'current') { plan = listed; found = again; }
}
- const binding = entryBinding(flags, found.mcp.stdioMember);
+ let binding = entryBinding(flags, found.mcp.stdioMember);
if (binding.member) { plan = { ...plan, stdioMember: binding.member }; found = inspectCodexSetup(plan); }
if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags, 'codex'), out);
@@ -854,6 +858,8 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
}
const servesPlan = servesPreflight(flags, launcher, 'codex', !!cfg, !!liveOwner?.ours, binding);
if (servesPlan instanceof OperationError) return refuse(servesPlan, out);
+ const tie = ownerTie(flags, servesPlan, binding, !!pluginOwner);
+ if (tie) { binding = { member: tie, previous: binding.previous }; plan = { ...plan, stdioMember: tie }; found = inspectCodexSetup(plan); target.stdio_member = tie; say(out, `note: ${tieNote(tie)}`); }
const brainCreate = !cfg;
const initArgv = [launcher, 'init', '--pglite', ...(consent.providers.value === 'accepted' ? [] : ['--no-embedding']), '--json'];
@@ -976,6 +982,18 @@ function entryBinding(flags: SetupFlags, previous: string | undefined): EntryBin
return { member: flags.noStdioMember ? null : flags.stdioMember ?? previous ?? null, previous: previous ?? null };
}
+/**
+ * GST-2904 (P1): a company setup for several people with no member named for this entry ties the entry it installs to
+ * the brain owner, so the owner's local assistant reads as the owner and imported calls can be kept to their
+ * attendees. Never where a plugin serves the entry, a shared-stdio harness is installed, or --no-stdio-member is given.
+ */
+function ownerTie(flags: SetupFlags, plan: ServesPlan, entry: EntryBinding, plugin: boolean): string | null {
+ if (flags.serves !== 'several' || (flags.brain !== 'company' && flags.brain !== 'both') || flags.noStdioMember || entry.member || plugin || !plan.tie) return null;
+ return sharedStdioHarness() ? null : plan.tie;
+}
+
+const tieNote = (owner: string): string => `this connection reads as the brain owner ${owner} (serve --stdio-member ${owner}), so it reads every call; --no-stdio-member leaves it unbound`;
+
/** 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 } : {}) };
diff --git a/src/core/access/call-scope.ts b/src/core/access/call-scope.ts
new file mode 100644
index 0000000000..b1506789d1
--- /dev/null
+++ b/src/core/access/call-scope.ts
@@ -0,0 +1,100 @@
+/**
+ * GST-2904 (GBRA-592, decisions K and N): whether `gbrain import --calls` may keep a new call to its attendees.
+ *
+ * Scoping applies only on a brain that serves two or more real people: config access.serves is not `one` and at least
+ * two enabled person-kind members exist (group-chat audience members never count, so a personal brain whose assistant
+ * sits in group chats is untouched). Where it applies, a call is kept to the owner plus its attendees only when every
+ * caller that could be the owner's own still reads it afterwards (the plan's owner-read table). Otherwise the import
+ * stays open, exactly as before, and says why with the calls_not_scoped notice:
+ *
+ * - owner_unset: config access.owner_member names nobody, so no reader list could name the owner;
+ * - owner_inactive: it names a member that is not enabled now;
+ * - unbound_readers: a token or OAuth client bound to no person still reads the brain (in grace, opted to read
+ * unscoped, or on a host that does not enforce binding), and could be the owner's own assistant;
+ * - stdio_unbound: a local stdio server bound to nobody still reads (grace, or enforcement off): a harness entry
+ * `gbrain setup` wrote without --stdio-member, or a harness several people talk to (OpenClaw, Hermes), while
+ * config mcp.stdio_member is unset.
+ *
+ * A connection that is already refused reads nothing today, so it never blocks. Everything here is database state plus
+ * the harness entries setup wrote on this machine, so a repo-less brain behaves the same.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action, Notice } from '../agent-output.ts';
+import { readServesPolicy, SERVES_KEY } from '../search/private-visibility.ts';
+import { listMembers, type MemberRecord } from './members.ts';
+import { ownerView } from './owner.ts';
+import { REQUESTER_SCOPE_GRACE_DAYS, unscopedConnections } from './requester-scope.ts';
+import { stdioMemberId } from './caller.ts';
+import { stdioBindRoute } from './stdio-bind-route.ts';
+
+export const CALLS_NOT_SCOPED = 'calls_not_scoped';
+export type CallsNotScopedReason = 'owner_unset' | 'owner_inactive' | 'unbound_readers' | 'stdio_unbound';
+export const CALLS_NOT_SCOPED_REASONS: readonly CallsNotScopedReason[] = ['owner_unset', 'owner_inactive', 'unbound_readers', 'stdio_unbound'];
+
+/** A local stdio connection bound to nobody: the harness, and the setup command that binds it without its member (null for a shared harness). */
+export interface UnboundStdio { harness: string; name?: string; argv: string[] | null }
+
+export type CallScopeGate =
+ | { applies: false }
+ | { applies: true; scoped: true; owner: string; members: MemberRecord[] }
+ | { applies: true; scoped: false; reason: CallsNotScopedReason; notice: Notice };
+
+const DOCS = 'docs/guides/repair.md#calls-not-scoped';
+
+function notice(why: string, fix: Action): Notice {
+ return { code: CALLS_NOT_SCOPED, kind: 'safety', why, fix: { ...fix, docs: DOCS } };
+}
+
+const userFix = (argv: string[], why: string, verify: string[], inputs?: Action['inputs']): Action =>
+ ({ argv, consent: [], actor: 'user', why, verify: { argv: verify }, requires_exclusive: false, ...(inputs ? { inputs } : {}) });
+
+/**
+ * Whether new calls in this brain are kept to their attendees. `unboundStdio` lists the local stdio connections bound
+ * to nobody (the import reads them from this machine's harness entries; tests pass their own).
+ */
+export async function callScopeGate(engine: BrainEngine, unboundStdio: () => UnboundStdio[], nowMs = Date.now()): Promise<CallScopeGate> {
+ const serves = await readServesPolicy(engine);
+ const explicitOne = ((await engine.getConfig(SERVES_KEY)) ?? '').trim().toLowerCase() === 'one';
+ const members = await listMembers(engine);
+ const people = members.filter(m => m.status === 'enabled' && m.kind === 'person');
+ if (explicitOne || people.length < 2) return { applies: false };
+ const view = await ownerView(engine);
+ if (view.inactive) {
+ const id = view.inactive.value;
+ return { applies: true, scoped: false, reason: 'owner_inactive', notice: notice(
+ `New calls were imported open to everyone who reads their source, as before: the brain owner "${id}" is not an enabled member now (${view.inactive.reason}), so no reader list could name the owner. Enable the owner; the next import keeps new calls to their attendees.`,
+ userFix(['gbrain', 'access', 'member', 'enable', id], 'Enables the owner member, so the next call import keeps each call to the owner and its attendees.', ['gbrain', 'access', 'owner', '--json'])) };
+ }
+ if (!view.owner) {
+ const only = people.length === 1 ? people[0]!.id : null;
+ return { applies: true, scoped: false, reason: 'owner_unset', notice: notice(
+ `New calls were imported open to everyone who reads their source, as before: this brain serves several people and names no owner, so no reader list could keep a call to the owner and its attendees. Name the owner; the next import keeps new calls to their attendees.`,
+ userFix(['gbrain', 'access', 'owner', 'set', only ?? '<MEMBER>'], 'Names the brain owner, who reads every call kept to its attendees.', ['gbrain', 'access', 'owner', '--json'],
+ only ? undefined : [{ name: 'MEMBER', how: `Ask the user which member owns the brain: ${people.map(p => p.id).join(', ')}.` }])) };
+ }
+ const owner = view.owner;
+ const found = await unscopedConnections(engine, nowMs);
+ const reading = (found?.connections ?? []).filter(c => c.state !== 'refused');
+ if (reading.length) {
+ const first = reading[0]!;
+ const argv = first.argv.map(a => a === '<MEMBER>' ? owner : a);
+ const list = reading.map(c => `${c.connection} (${c.state}): ${c.argv.map(a => a === '<MEMBER>' ? owner : a).join(' ')}`).join('; ');
+ return { applies: true, scoped: false, reason: 'unbound_readers', notice: notice(
+ `New calls were imported open to everyone who reads their source, as before: ${reading.length} connection(s) bound to no person still read this brain and might be the owner's own assistant, which would lose every call kept to its attendees. Tie each one that is the owner's to ${owner}, and each other one to the person it serves: ${list}. The next import then keeps new calls to their attendees.`,
+ userFix(argv, `Ties ${first.connection} to the owner ${owner}, if it is the owner's; another person's connection is tied to that person instead.`, argv.includes('--token') ? ['gbrain', 'access', 'check', ...argv.slice(argv.indexOf('--token'), argv.indexOf('--token') + 2)] : ['gbrain', 'access', 'serves', '--json'])) };
+ }
+ const stdioReads = !serves.enforce || (serves.since !== null && Math.floor(nowMs / 1000) < serves.since + REQUESTER_SCOPE_GRACE_DAYS * 24 * 3600);
+ if (stdioReads && !(await stdioMemberId(engine))) {
+ const unbound = unboundStdio();
+ if (unbound.length) {
+ const first = unbound[0]!;
+ const argv = first.argv ? [...first.argv, '--stdio-member', owner] : stdioBindRoute(owner).argv.map(a => a === '<MEMBER>' ? owner : a === '<HARNESS>' ? first.harness : a);
+ const how = first.argv ? `Tie it to the owner ${owner} with ${argv.join(' ')}. ` : stdioBindRoute(owner).text;
+ return { applies: true, scoped: false, reason: 'stdio_unbound', notice: notice(
+ `New calls were imported open to everyone who reads their source, as before: the ${unbound.map(u => u.harness).join(', ')} stdio connection on this machine is bound to nobody and still reads this brain, and it might be the owner's own assistant. ${how}The next import then keeps new calls to their attendees.`,
+ userFix(argv, `Binds the ${first.harness} stdio connection to the owner ${owner}, so it reads every call kept to its attendees.`, ['gbrain', 'access', 'serves', '--json'])) };
+ }
+ }
+ return { applies: true, scoped: true, owner, members };
+}
+
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 015ffbeb2b..1ddfb52bb9 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -78,7 +78,7 @@ 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'],
'guests': ['--add', '--brain', '--client', '--guest-source', '--help', '--id', '--if-version', '--json', '--read-sources', '--source', '--sources', '--to', '--writer', '--yes'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--catalog', '--count', '--diff-filter', '--dir', '--enable', '--end-of-options', '--env', '--force-with-lease', '--gbrain-bin', '--get', '--harness', '--heads', '--help', '--instructions', '--instructions-only', '--is-ancestor', '--jq', '--json', '--limit', '--name-only', '--no-follow-tags', '--no-instructions', '--no-tags', '--only', '--others', '--pat-file', '--path', '--porcelain', '--print', '--pure', '--quiet', '--recurse-submodules', '--remove', '--scope', '--sdk-url', '--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', '--calls', '--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', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--prefix', '--probe', '--progress-interval', '--progress-json', '--quiet', '--room', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],
+ 'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--calls', '--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', '--log-noop', '--manifest', '--name', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--prefix', '--probe', '--progress-interval', '--progress-json', '--quiet', '--readers', '--room', '--scope', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers', '--yes'],
'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--admin-intent', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--allow-without-owner', '--anchor', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--cached', '--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', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--file', '--filter', '--first-parent', '--fix', '--force', '--force-retry', '--force-schema', '--format', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-covered', '--include-cross-entity', '--include-failures', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--label-lowerings', '--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-stdio-member', '--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', '--reason', '--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', '--safe', '--save', '--scan-secrets', '--scan-timeout', '--schedule', '--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', '--slugs-file', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--take', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--untrack', '--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', '--room', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],
@@ -125,7 +125,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--backend', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--labelled-only', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-open-pages', '--no-pull', '--no-stdio-member', '--oauth-request', '--only', '--open-history', '--operations', '--owner', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--reads-unscoped', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--to', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--calls', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--held', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--open-history', '--owner', '--owner-sender', '--path', '--pglite', '--pins-route', '--prefix', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--to', '--token', '--transcripts', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--apply', '--arg', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--calls', '--capture', '--catalog', '--command', '--credentials-file', '--docs', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--header', '--held', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--labelled-only', '--legacy-lock', '--limit', '--link', '--live-fraction', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embed', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-open-pages', '--no-providers', '--no-stdio-member', '--non-interactive', '--notes', '--oauth-client-id', '--oauth-client-secret', '--only', '--open-history', '--owner', '--owner-sender', '--path', '--pglite', '--pins-route', '--prefix', '--probe', '--providers', '--pure', '--readers', '--remove', '--root', '--runtime', '--save', '--schedule', '--scope', '--serves', '--shape', '--show-toplevel', '--skill-loading', '--skills-index-only', '--slug', '--solo', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--strict-json', '--surface', '--team', '--to', '--token', '--transcripts', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--show-toplevel', '--skill-loading', '--source', '--text', '--top-gate', '--top-k'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 6e5f8ee1c4..53d4a27df1 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -1116,6 +1116,7 @@ export const NOTICE_CODES = {
valid_time_correction: { kind: 'info', summary: "A page write changed the body and kept `valid_from`, so `as_of` reads treat it as a correction of the edition in force since that date; set `valid_from` if the change takes effect later." },
valid_time_date_only: { kind: 'ask', summary: "A page write changed only `valid_from`: a corrected date and a renewal of unchanged text look the same, so `as_of` reads around these dates carry `ambiguous_edition_dates`. Ask the user which one it was." },
ambiguous_edition_dates: { kind: 'ask', summary: "A get_page `as_of` answer is the selection rule's pick, but the versions around the date have an ambiguous shape (the same body under another `valid_from`, or a later-recorded version with an earlier one); `valid_time.competing_version_ids` names them and the fix asks which date the edition took effect." },
+ calls_not_scoped: { kind: 'safety', summary: 'gbrain import --calls on a brain that serves two or more people imported new calls open to everyone who reads their source, as before, instead of keeping each to the owner and its attendees, because some caller that could be the owner\'s own would have lost them: no owner is named (owner_unset), the owner is not enabled (owner_inactive), a token or OAuth client bound to no person still reads the brain (unbound_readers), or a local stdio connection bound to nobody still reads it (stdio_unbound). The fix is the user\'s command for that reason; the next import keeps new calls to their attendees.' },
privacy_label_ignored: { kind: 'safety', summary: 'A write (put_page, import or sync) stored a page whose `access` or `confidentiality` value is not one gbrain reads as private, with no `visibility` key: the label is ignored, so remote callers read the page like an unlabelled one and, on a source with a git repository, it is not kept out of git. The notice names the key and value (counts by value for a bulk run, never page content); the fix asks the user before adding `visibility: private`.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },
diff --git a/src/core/meetings/attendees.ts b/src/core/meetings/attendees.ts
new file mode 100644
index 0000000000..e54cf9ba27
--- /dev/null
+++ b/src/core/meetings/attendees.ts
@@ -0,0 +1,128 @@
+/**
+ * GST-2904 (GBRA-592): who was on an imported call. `gbrain import --calls` keeps a call to the brain owner plus the
+ * teammates its header names (src/commands/import-calls.ts); `gbrain repair visibility --propose` reads the same header
+ * for calls imported before that (src/commands/repair-propose.ts).
+ *
+ * Only the call's header counts: an `attendees:` key in a leading frontmatter block, or an `Attendees:` /
+ * `Participants:` line (plain or bold) within the first 15 lines and before the header ends. The header ends at the
+ * first blank line after text or at the first speaker turn (`Name: words` whose label is not a header label such as
+ * Date). A line deeper in the transcript never counts, so a speaker reading out "Attendees: ..." adds no reader.
+ *
+ * Matching is exact (skills/conventions/brain-first.md, identity rule): an entry carrying an email matches by that email
+ * only; otherwise the member id, then a display name exactly one enabled person member holds, letter case ignored.
+ * Disabled members and audience members never match. The literal `owner` is covered by the owner, who reads every
+ * scoped call. Anything else stays unmatched and is listed, never guessed.
+ */
+import { FAILSAFE_SCHEMA } from 'js-yaml';
+import { loadBoundedYaml } from '../data-frontmatter.ts';
+import type { MemberRecord } from '../access/members.ts';
+
+const HEADER_LINES = 15;
+const LIST_LINE_RE = /^(?:\*\*)?(attendees|participants)(?::\*\*|\*\*:|:)[ \t]*(.*)$/i;
+const HEADER_LABELS = new Set(['date', 'time', 'when', 'call', 'title', 'subject', 'meeting', 'topic', 'duration', 'location', 'where', 'organizer', 'organiser', 'host', 'recorded', 'recording', 'source', 'platform', 'agenda', 'attendees', 'participants']);
+const TURN_RE = /^(?:\*\*)?([^:*\n]{1,60}?)(?:\*\*)?:\s+\S/;
+const EMAIL_RE = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
+
+/** One attendee as the header gives it: the printed entry, and the email it carries when it has one. */
+export interface CallAttendee { entry: string; email?: string }
+
+function attendeeOf(raw: string): CallAttendee | null {
+ const entry = raw.trim().replace(/^[-*]\s+/, '').replace(/^\[\[|\]\]$/g, '').trim();
+ if (!entry) return null;
+ const angled = /<([^<>\s]+@[^<>\s]+)>/.exec(entry)?.[1];
+ const email = angled ?? (EMAIL_RE.test(entry) ? entry : undefined);
+ return email ? { entry, email: email.toLowerCase() } : { entry };
+}
+
+const splitList = (text: string): CallAttendee[] => text.split(/[,;]/).map(attendeeOf).filter((a): a is CallAttendee => a !== null);
+
+function inlineAttendees(value: string): CallAttendee[] {
+ let parsed: unknown;
+ try { parsed = loadBoundedYaml(value, { schema: FAILSAFE_SCHEMA }); } catch { return splitList(value.replace(/^\[|\]$/g, '').replace(/["']/g, '')); }
+ if (typeof parsed === 'string') return splitList(parsed);
+ if (!Array.isArray(parsed)) return [];
+ return (parsed.flat(Infinity) as unknown[]).flatMap(item => typeof item === 'string' ? [attendeeOf(item)] : []).filter((a): a is CallAttendee => a !== null);
+}
+
+function frontmatterAttendees(lines: string[]): { attendees: CallAttendee[] | null; end: number } {
+ if (lines[0]?.trim() !== '---') return { attendees: null, end: 0 };
+ const end = lines.findIndex((l, i) => i > 0 && l.trim() === '---');
+ if (end < 0) return { attendees: null, end: 0 };
+ for (let i = 1; i < end; i++) {
+ const m = /^attendees:[ \t]*(.*)$/i.exec(lines[i]!);
+ if (!m) continue;
+ const inline = m[1]!.trim();
+ if (inline) return { attendees: inlineAttendees(inline), end: end + 1 };
+ const items: CallAttendee[] = [];
+ for (let j = i + 1; j < end && /^\s+-\s+/.test(lines[j]!); j++) {
+ const a = attendeeOf(lines[j]!.replace(/^\s+-\s+/, '').replace(/^["']|["']$/g, ''));
+ if (a) items.push(a);
+ }
+ return { attendees: items, end: end + 1 };
+ }
+ return { attendees: null, end: end + 1 };
+}
+
+/** The attendees the call's header names, in order, or null when the header names none. */
+export function parseCallAttendees(text: string): CallAttendee[] | null {
+ const lines = text.replace(/^\uFEFF/, '').split(/\r?\n/);
+ const fm = frontmatterAttendees(lines);
+ if (fm.attendees) return fm.attendees;
+ let seenText = false;
+ for (let i = fm.end; i < Math.min(lines.length, fm.end + HEADER_LINES); i++) {
+ const line = lines[i]!.trim();
+ if (!line) { if (seenText) break; continue; }
+ const list = LIST_LINE_RE.exec(line);
+ if (list) return splitList(list[2]!);
+ const turn = TURN_RE.exec(line);
+ if (turn && !HEADER_LABELS.has(turn[1]!.trim().toLowerCase())) break;
+ seenText = true;
+ }
+ return null;
+}
+
+/** How one attendee entry resolved. */
+export type AttendeeMatch =
+ | { kind: 'member'; member: string; by: 'email' | 'id' | 'name' }
+ | { kind: 'owner' }
+ | { kind: 'unmatched' };
+
+const fold = (s: string | null | undefined): string => (s ?? '').trim().toLowerCase();
+
+/** Exact match of one attendee against the enabled person members (see the file comment). */
+export function matchAttendee(attendee: CallAttendee, members: readonly MemberRecord[]): AttendeeMatch {
+ const people = members.filter(m => m.status === 'enabled' && m.kind === 'person');
+ if (attendee.email) {
+ const hit = people.filter(m => fold(m.email) === attendee.email);
+ return hit.length === 1 ? { kind: 'member', member: hit[0]!.id, by: 'email' } : { kind: 'unmatched' };
+ }
+ const key = fold(attendee.entry);
+ if (key === 'owner') return { kind: 'owner' };
+ const byId = people.find(m => fold(m.id) === key);
+ if (byId) return { kind: 'member', member: byId.id, by: 'id' };
+ const byName = people.filter(m => fold(m.display_name) === key);
+ return byName.length === 1 ? { kind: 'member', member: byName[0]!.id, by: 'name' } : { kind: 'unmatched' };
+}
+
+/** The readers a call page gets: the owner first, then each matched teammate once, with how each matched and what did not. */
+export interface CallReaders {
+ readers: string[];
+ matched_by: Record<string, 'email' | 'id' | 'name'>;
+ unmatched: string[];
+ /** The call names no attendees, so it is kept to the owner. */
+ no_list: boolean;
+}
+
+export function callReadersFor(attendees: CallAttendee[] | null, owner: string, members: readonly MemberRecord[]): CallReaders {
+ const readers = [owner];
+ const matched_by: CallReaders['matched_by'] = {};
+ const unmatched: string[] = [];
+ for (const a of attendees ?? []) {
+ const m = matchAttendee(a, members);
+ if (m.kind === 'unmatched') { if (!unmatched.includes(a.entry)) unmatched.push(a.entry); continue; }
+ if (m.kind === 'owner' || readers.includes(m.member)) continue;
+ readers.push(m.member);
+ matched_by[m.member] = m.by;
+ }
+ return { readers, matched_by, unmatched, no_list: attendees === null || attendees.length === 0 };
+}
diff --git a/test/e2e/import-calls-attendees-postgres.test.ts b/test/e2e/import-calls-attendees-postgres.test.ts
new file mode 100644
index 0000000000..0ce777c0ee
--- /dev/null
+++ b/test/e2e/import-calls-attendees-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../import-calls-attendees.test.ts'));
diff --git a/test/import-calls-attendees.test.ts b/test/import-calls-attendees.test.ts
new file mode 100644
index 0000000000..79e88f195f
--- /dev/null
+++ b/test/import-calls-attendees.test.ts
@@ -0,0 +1,406 @@
+/**
+ * GST-2904 (GBRA-592, decisions K to O): `gbrain import --calls` keeps each call to the brain owner plus the teammates its
+ * header names, on a brain that serves two or more people, and imports open as before whenever an owner caller could
+ * lose it (calls_not_scoped).
+ *
+ * Authoring gate:
+ * 1. Protects: a teammate who was not on a call gets not_found and no search hit for it, while the attendees, the owner's
+ * local CLI and every owner caller kind (bound token, bound OAuth client, bound stdio, attested owner, owner-alone
+ * audience) read it; a one-person brain imports byte-identical pages; matching is exact and fails closed.
+ * 2. Fails on: a call readable by a non-attendee, any owner caller losing a call, a guessed or name-fallback match, a
+ * call scoped while an unbound reader could be the owner's, readers dropped by a later local write.
+ * 3. Real seams: runCallImport on a repo-less brain (PGLite, and Postgres through test/e2e), tokens and clients verified
+ * by the serve --http verifier, reads through MCP dispatch with remote: true. Placeholder names only.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCallImport } from '../src/commands/import-calls.ts';
+import { callReadersFor, parseCallAttendees } from '../src/core/meetings/attendees.ts';
+import { callScopeGate, type UnboundStdio } from '../src/core/access/call-scope.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { clearOwner, setOwner } from '../src/core/access/owner.ts';
+import { bindCredential, type MemberRecord } from '../src/core/access/members.ts';
+import { linkMember } from '../src/core/access/actor.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';
+
+const SRC = 'company';
+const OWNER = 'owner-example';
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+const temp = (prefix: string): string => { const d = realpathSync(mkdtempSync(join(tmpdir(), prefix))); roots.push(d); return d; };
+const NO_STDIO = (): UnboundStdio[] => [];
+
+/** The audit's four call shapes, plus a call with no list, in placeholder names. */
+const CALLS: Record<string, string> = {
+ '2026-11-12 hiring debrief.md': '# Hiring debrief\nDate: 2026-11-12\nAttendees: owner, carol-example\n\ncarol-example: strong on systems design.\nowner: The band is canaryhiringband 210k to 240k base.\n',
+ '2026-11-11 pricing review.txt': 'Pricing review\nDate: 2026-11-11\nAttendees: Alice Example, bob-example\n\nbob-example: canarypricing annual billing.\n',
+ '2026-11-10 weekly eng sync.md': '**Participants:** bob-example; Carol <[email protected]>\n\nbob-example: canaryengsync deploy on Tuesday.\n',
+ '2026-11-09 acme renewal.md': 'Acme renewal\nAttendees: alice-example, dave-example (acme-example procurement)\n\nalice-example: canaryrenewal renew at the same price.\n',
+ '2026-11-08 standup.txt': 'Standup\nalice-example: canarystandup shipping today.\nAttendees: bob-example\n',
+};
+const SLUG = {
+ debrief: 'company/calls/2026-11-12-hiring-debrief',
+ pricing: 'company/calls/2026-11-11-pricing-review',
+ eng: 'company/calls/2026-11-10-weekly-eng-sync',
+ renewal: 'company/calls/2026-11-09-acme-renewal',
+ standup: 'company/calls/2026-11-08-standup',
+};
+
+function writeCalls(dir: string, names = Object.keys(CALLS)): void {
+ for (const name of names) writeFileSync(join(dir, name), CALLS[name]!);
+}
+
+async function importJson(engine: BrainEngine, dir: string, extra: string[] = [], unboundStdio = NO_STDIO): Promise<any> {
+ _resetCliExitVerdictForTests();
+ const chunks: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { chunks.push(a.map(String).join(' ')); });
+ try { await runCallImport(engine, dir, ['--calls', '--prefix', 'company/calls', ...extra], { sourceId: SRC, json: true, unboundStdio }); } finally { spy.mockRestore(); }
+ __resetPrivateVisibilityCacheForTests();
+ return JSON.parse(chunks.join(''));
+}
+
+const member = (id: string, extra: Partial<MemberRecord> = {}): MemberRecord => ({ id, display_name: null, email: null, status: 'enabled', kind: 'person', labelled_only: false, groups: [], created_at: null, ...extra });
+
+describe('call header and exact matching', () => {
+ test('only the header counts: a frontmatter key, an Attendees or Participants line before the first turn or blank line', () => {
+ expect(parseCallAttendees(CALLS['2026-11-12 hiring debrief.md']!)?.map(a => a.entry)).toEqual(['owner', 'carol-example']);
+ expect(parseCallAttendees(CALLS['2026-11-10 weekly eng sync.md']!)).toEqual([{ entry: 'bob-example' }, { entry: 'Carol <[email protected]>', email: '[email protected]' }]);
+ expect(parseCallAttendees('---\nattendees: [alice-example, bob-example]\n---\nhi\n')?.map(a => a.entry)).toEqual(['alice-example', 'bob-example']);
+ expect(parseCallAttendees('---\nattendees: ["Smith, Alice", \'bob-example\']\n---\nhi\n')?.map(a => a.entry)).toEqual(['Smith, Alice', 'bob-example']);
+ expect(callReadersFor(parseCallAttendees('---\nattendees: ["Smith, Alice"]\n---\nhi\n'), OWNER, [member(OWNER), member('smith'), member('alice', { display_name: 'Alice' })]))
+ .toEqual({ readers: [OWNER], matched_by: {}, unmatched: ['Smith, Alice'], no_list: false });
+ expect(parseCallAttendees('---\nattendees:\n - alice-example\n - "[email protected]"\n---\nhi\n')).toEqual([{ entry: 'alice-example' }, { entry: '[email protected]', email: '[email protected]' }]);
+ expect(parseCallAttendees(CALLS['2026-11-08 standup.txt']!)).toBeNull();
+ expect(parseCallAttendees('Weekly\n\nalice-example: hello\nAttendees: bob-example\n')).toBeNull();
+ expect(parseCallAttendees('no header at all\n')).toBeNull();
+ });
+
+ test('an email entry matches by email only; then id, then a display name held by exactly one enabled person', () => {
+ const members = [member(OWNER), member('alice-example', { display_name: 'Alice Example', email: '[email protected]' }), member('bob-example', { display_name: 'Sam Example' }),
+ member('carol-example', { display_name: 'Sam Example', email: '[email protected]' }), member('dave-example', { status: 'disabled' }), member('room-example', { kind: 'audience', display_name: 'Room Example' })];
+ const r = callReadersFor(parseCallAttendees('Attendees: owner, ALICE EXAMPLE, bob-example, Sam Example, carol-example <[email protected]>, dave-example, Room Example, Erin <[email protected]>\n\nx: y'), OWNER, members);
+ expect(r).toEqual({ readers: [OWNER, 'alice-example', 'bob-example'], matched_by: { 'alice-example': 'name', 'bob-example': 'id' },
+ unmatched: ['Sam Example', 'carol-example <[email protected]>', 'dave-example', 'Room Example'], no_list: false });
+ expect(callReadersFor(null, OWNER, members)).toEqual({ readers: [OWNER], matched_by: {}, unmatched: [], no_list: true });
+ });
+});
+
+for (const kind of testBackends()) {
+ describe(`call import keeps calls to their attendees (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const tokens: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ let calls: string;
+
+ async function remote(who: string, op: string, params: Record<string, unknown>, extra: Record<string, unknown> = {}): Promise<string> {
+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'], ...extra });
+ return out.content.map(c => c.text).join('\n');
+ }
+ const stdio = async (op: string, params: Record<string, unknown>, stdioMember?: string) =>
+ (await dispatchToolCall(engine, op, params, { remote: true, transport: 'stdio', sourceId: SRC, ...(stdioMember ? { stdioMember } : {}) })).content.map(c => c.text).join('\n');
+ const local = async (slug: string) => (await dispatchToolCall(engine, 'get_page', { slug }, { remote: false, sourceId: SRC })).content.map(c => c.text).join('\n');
+ const reads = async (who: string, slug: string, canary: string) => (await remote(who, 'get_page', { slug })).includes(canary);
+
+ 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(); }
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ for (const [id, name, email, kindOf] of [[OWNER, 'Owner Example', null, 'person'], ['alice-example', 'Alice Example', '[email protected]', 'person'], ['bob-example', null, null, 'person'],
+ ['carol-example', 'Carol Example', '[email protected]', 'person'], ['room-example', null, null, 'audience']] as const) {
+ await engine.executeRaw('INSERT INTO access_members (id, display_name, email, kind) VALUES ($1, $2, $3, $4)', [id, name, email, kindOf]);
+ }
+ const mint = async (name: string, bind: { member?: string; mayActFor?: string[] } | 'unscoped' | null) => {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });
+ tokens[name] = minted.token;
+ if (bind === 'unscoped') await readsUnscopedOnPurpose(engine, minted.id);
+ else if (bind) await bindCredential(engine, { kind: 'token', id: minted.id }, bind);
+ return minted.id;
+ };
+ await mint('owner', { member: OWNER });
+ await mint('alice', { member: 'alice-example' });
+ await mint('bob', { member: 'bob-example' });
+ await mint('carol', { member: 'carol-example' });
+ await mint('owner-audience', { mayActFor: [`member:${OWNER}`] });
+ const client = await provider().registerClientManual('owner-client', ['client_credentials'], 'read', [], SRC);
+ await bindCredential(engine, { kind: 'client', id: client.clientId }, { member: OWNER });
+ tokens['owner-client'] = (await provider().exchangeClientCredentials(client.clientId, client.clientSecret ?? '')).access_token;
+ const qm = await provider().registerClientManual('qm-example', ['client_credentials'], 'read', [], SRC);
+ await bindCredential(engine, { kind: 'client', id: qm.clientId }, { attestActor: 'qm', attestOps: ['get_page'] });
+ tokens.qm = (await provider().exchangeClientCredentials(qm.clientId, qm.clientSecret ?? '')).access_token;
+ await linkMember(engine, OWNER, 'qm', 'U0OWNEREXAMPLE');
+ await setOwner(engine, OWNER);
+ calls = temp('gbrain-calls-attendees-');
+ writeCalls(calls);
+ }, 240_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('the four calls and a call with no list get the owner plus matched attendees, with every unmatched name listed', async () => {
+ const doc = await importJson(engine, calls);
+ expect(doc).toMatchObject({ imported: 5, errors: 0, readers: { scoped: 4, owner_only: 1, not_scoped: 0 } });
+ expect(doc.notices).toBeUndefined();
+ const bySlug = Object.fromEntries(doc.pages.map((p: any) => [p.slug, p]));
+ expect(bySlug[SLUG.debrief]).toMatchObject({ scoped: true, readers: [OWNER, 'carol-example'], readers_from: 'computed', matched_by: { 'carol-example': 'id' }, unmatched: [] });
+ expect(bySlug[SLUG.pricing]).toMatchObject({ readers: [OWNER, 'alice-example', 'bob-example'], matched_by: { 'alice-example': 'name', 'bob-example': 'id' } });
+ expect(bySlug[SLUG.eng]).toMatchObject({ readers: [OWNER, 'bob-example', 'carol-example'], matched_by: { 'carol-example': 'email' }, unmatched: [] });
+ expect(bySlug[SLUG.renewal]).toMatchObject({ readers: [OWNER, 'alice-example'], unmatched: ['dave-example (acme-example procurement)'] });
+ expect(bySlug[SLUG.standup]).toMatchObject({ scoped: true, readers: [OWNER], unmatched: [] });
+ }, 120_000);
+
+ test('a teammate who was not on the call is told it does not exist and finds nothing; the attendees and the owner read it', async () => {
+ expect(await reads('alice', SLUG.debrief, 'canaryhiringband')).toBe(false);
+ expect(await remote('alice', 'search', { query: 'canaryhiringband', match: 'keyword', limit: 20 })).not.toContain('canaryhiringband');
+ expect(await reads('bob', SLUG.debrief, 'canaryhiringband')).toBe(false);
+ expect(await reads('carol', SLUG.debrief, 'canaryhiringband')).toBe(true);
+ expect(await reads('alice', SLUG.pricing, 'canarypricing')).toBe(true);
+ expect(await reads('carol', SLUG.renewal, 'canaryrenewal')).toBe(false);
+ expect(await reads('bob', SLUG.standup, 'canarystandup')).toBe(false);
+ expect(await local(SLUG.debrief)).toContain('canaryhiringband');
+ }, 120_000);
+
+ test('every owner caller kind still reads every call: token, OAuth client, stdio, attested owner, owner-alone audience', async () => {
+ for (const [slug, canary] of [[SLUG.debrief, 'canaryhiringband'], [SLUG.standup, 'canarystandup'], [SLUG.renewal, 'canaryrenewal']] as const) {
+ expect({ slug, token: await reads('owner', slug, canary), client: await reads('owner-client', slug, canary),
+ stdio: (await stdio('get_page', { slug }, OWNER)).includes(canary),
+ attested: (await remote('qm', 'get_page', { slug }, { actor: { header: 'U0OWNEREXAMPLE' } })).includes(canary),
+ audience: (await remote('owner-audience', 'get_page', { slug }, { onBehalfOf: { header: OWNER } })).includes(canary),
+ local: (await local(slug)).includes(canary) })
+ .toEqual({ slug, token: true, client: true, stdio: true, attested: true, audience: true, local: true });
+ }
+ }, 240_000);
+
+ test('a link out of a scoped call is hidden from a teammate who was not on it, and shown to an attendee and the owner', async () => {
+ const dir = temp('gbrain-calls-links-');
+ writeFileSync(join(dir, '2026-11-07 offer review.md'), 'Offer review\nAttendees: carol-example\n\ncarol-example: canaryoffer see [[people/dave-example]] for the reference check.\n');
+ await dispatchToolCall(engine, 'put_page', { slug: 'people/dave-example', content: '---\ntype: person\ntitle: Dave Example\n---\n# Dave Example\n' }, { remote: false, sourceId: SRC });
+ const doc = await importJson(engine, dir);
+ expect(doc.pages[0]).toMatchObject({ scoped: true, readers: [OWNER, 'carol-example'] });
+ const backlinks = async (who: string) => (await remote(who, 'get_backlinks', { slug: 'people/dave-example' })).includes('company/calls/2026-11-07-offer-review');
+ const [links] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM links l JOIN pages p ON p.id = l.from_page_id WHERE p.slug = 'company/calls/2026-11-07-offer-review'");
+ expect(Number(links!.n)).toBeGreaterThan(0);
+ expect({ alice: await backlinks('alice'), carol: await backlinks('carol'), owner: await backlinks('owner') }).toEqual({ alice: false, carol: true, owner: true });
+ await engine.executeRaw("DELETE FROM pages WHERE source_id = $1 AND slug = 'company/calls/2026-11-07-offer-review'", [SRC]);
+ }, 120_000);
+
+ test('a rerun reports the stored readers and writes nothing; a later local write without readers keeps them', async () => {
+ const again = await importJson(engine, calls);
+ expect(again).toMatchObject({ imported: 0, unchanged: 5 });
+ expect(again.pages.find((p: any) => p.slug === SLUG.debrief)).toMatchObject({ status: 'unchanged', scoped: true, readers: [OWNER, 'carol-example'], readers_from: 'stored' });
+ const [guard] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_label_guards g JOIN pages p ON p.id = g.page_id WHERE p.source_id = $1 AND starts_with(p.slug, $2)', [SRC, 'company/calls/']);
+ expect(Number(guard!.n)).toBe(5);
+ const stored = JSON.parse(await local(SLUG.debrief)) as { compiled_truth: string; revision: string };
+ const body = ['---', 'title: "hiring debrief"', 'type: meeting', 'date: 2026-11-12', 'facts_backstop: false', '---', stored.compiled_truth, 'owner: one more note.', ''].join('\n');
+ const write = await dispatchToolCall(engine, 'put_page', { slug: SLUG.debrief, content: body, expected_revision: stored.revision }, { remote: false, sourceId: SRC });
+ expect({ isError: write.isError === true, text: write.isError ? write.content.map(c => c.text).join('') : '' }).toEqual({ isError: false, text: '' });
+ const [row] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; compiled_truth: string }>('SELECT frontmatter, compiled_truth FROM pages WHERE source_id = $1 AND slug = $2', [SRC, SLUG.debrief]);
+ expect(row!.frontmatter.readable_by).toEqual([OWNER, 'carol-example']);
+ __resetPrivateVisibilityCacheForTests();
+ expect(await reads('alice', SLUG.debrief, 'canaryhiringband')).toBe(false);
+ expect(await reads('carol', SLUG.debrief, 'canaryhiringband')).toBe(true);
+ expect(await reads('owner', SLUG.debrief, 'canaryhiringband')).toBe(true);
+ }, 120_000);
+ });
+
+ describe(`the owner check keeps calls open, as before (${kind}, repo-less)`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const tokens: Record<string, string> = {};
+ const ids: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ let n = 0;
+ let one: PGLiteEngine;
+ const fresh = () => { const d = temp('gbrain-calls-gate-'); writeCalls(d, ['2026-11-12 hiring debrief.md']); return d; };
+ const prefixOf = () => `company/calls`;
+ async function importOnce(extra: string[] = [], unboundStdio = NO_STDIO): Promise<any> {
+ n++;
+ await engine.executeRaw("DELETE FROM pages WHERE source_id = $1 AND starts_with(slug, 'company/calls/')", [SRC]);
+ return importJson(engine, fresh(), extra, unboundStdio);
+ }
+ async function remote(who: string, slug: string): Promise<string> {
+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ const out = await dispatchToolCall(engine, 'get_page', { slug }, { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'] });
+ return out.content.map(c => c.text).join('\n');
+ }
+ const setServesSince = (iso: string) => engine.executeRaw("INSERT INTO config (key, value) VALUES ('access.serves_since', $1) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value", [iso]);
+
+ 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(); }
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);
+ for (const id of [OWNER, 'alice-example', 'carol-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ for (const name of ['legacy-bot', 'alice']) {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });
+ tokens[name] = minted.token; ids[name] = minted.id;
+ }
+ await bindCredential(engine, { kind: 'token', id: ids.alice! }, { member: 'alice-example' });
+ await setOwner(engine, OWNER);
+ one = new PGLiteEngine();
+ await one.connect({ engine: 'pglite' } as never); await one.initSchema();
+ }, 240_000);
+ afterAll(async () => { await one?.disconnect(); await close?.(); }, 60_000);
+ beforeEach(async () => {
+ await engine.executeRaw("DELETE FROM config WHERE key IN ('access.requester_scope_enforce', 'mcp.stdio_member')");
+ await engine.executeRaw('UPDATE access_tokens SET reads_unscoped = NULL WHERE id::text = $1', [ids['legacy-bot']]);
+ await setServesSince('2000-01-01T00:00:00Z');
+ await setOwner(engine, OWNER);
+ __resetPrivateVisibilityCacheForTests();
+ });
+
+ const open = (doc: any, reason: string) => {
+ expect(doc.pages[0]).toMatchObject({ status: 'imported', scoped: false, reason, readers: null });
+ expect(doc.readers).toEqual({ scoped: 0, owner_only: 0, not_scoped: 1 });
+ expect(doc.notices?.[0]).toMatchObject({ code: 'calls_not_scoped', kind: 'safety', fix: { next: 'tell_user_to_run' } });
+ };
+
+ test('baseline: a refused unbound token reads nothing today, so it does not block scoping', async () => {
+ const doc = await importOnce();
+ expect(doc.pages[0]).toMatchObject({ scoped: true, readers: [OWNER, 'carol-example'] });
+ expect(doc.notices).toBeUndefined();
+ expect(await remote('legacy-bot', SLUG.debrief)).toContain('requester_scope_required');
+ }, 120_000);
+
+ test('an unbound token in grace keeps the import open, names its bind command, and still reads the call', async () => {
+ await setServesSince(new Date(Date.now() + 3600_000).toISOString());
+ const doc = await importOnce();
+ open(doc, 'unbound_readers');
+ expect(doc.notices[0].fix.command).toContain('gbrain auth rescope --token legacy-bot --member owner-example');
+ expect(doc.notices[0].why).toContain('token legacy-bot (grace)');
+ __resetPrivateVisibilityCacheForTests();
+ expect(await remote('legacy-bot', SLUG.debrief)).toContain('canaryhiringband');
+ }, 120_000);
+
+ test('a token that reads unscoped on purpose keeps the import open and still reads the call', async () => {
+ await readsUnscopedOnPurpose(engine, ids['legacy-bot']!);
+ open(await importOnce(), 'unbound_readers');
+ __resetPrivateVisibilityCacheForTests();
+ expect(await remote('legacy-bot', SLUG.debrief)).toContain('canaryhiringband');
+ }, 120_000);
+
+ test('a host that does not enforce binding (hosted) keeps the import open and the unbound token still reads', async () => {
+ await engine.executeRaw("INSERT INTO config (key, value) VALUES ('access.requester_scope_enforce', 'false') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value");
+ open(await importOnce(), 'unbound_readers');
+ __resetPrivateVisibilityCacheForTests();
+ expect(await remote('legacy-bot', SLUG.debrief)).toContain('canaryhiringband');
+ }, 120_000);
+
+ test('an unbound stdio connection in grace keeps the import open and still reads; bound by config it does not block', async () => {
+ await setServesSince(new Date(Date.now() - 3600_000).toISOString());
+ const unbound = (): UnboundStdio[] => [{ harness: 'claude-code', name: 'gbrain', argv: ['gbrain', 'setup', 'claude-code'] }];
+ const doc = await importOnce([], unbound);
+ open(doc, 'stdio_unbound');
+ expect(doc.notices[0].fix.command).toBe('gbrain setup claude-code --stdio-member owner-example');
+ __resetPrivateVisibilityCacheForTests();
+ expect((await dispatchToolCall(engine, 'get_page', { slug: SLUG.debrief }, { remote: true, transport: 'stdio', sourceId: SRC })).content.map(c => c.text).join('\n')).toContain('canaryhiringband');
+ await engine.executeRaw("INSERT INTO config (key, value) VALUES ('mcp.stdio_member', $1)", [OWNER]);
+ expect((await importOnce([], unbound)).pages[0]).toMatchObject({ scoped: true });
+ await setServesSince('2000-01-01T00:00:00Z');
+ await engine.executeRaw("DELETE FROM config WHERE key = 'mcp.stdio_member'");
+ expect((await importOnce([], unbound)).pages[0]).toMatchObject({ scoped: true });
+ }, 120_000);
+
+ test('no owner, or an owner who is not enabled, keeps the import open with the owner command', async () => {
+ await clearOwner(engine);
+ const unset = await importOnce();
+ open(unset, 'owner_unset');
+ expect(unset.notices[0].fix.command).toBe("gbrain access owner set '<MEMBER>'");
+ await setOwner(engine, OWNER);
+ await engine.executeRaw('UPDATE access_members SET disabled_at = now() WHERE id = $1', [OWNER]);
+ const inactive = await importOnce();
+ open(inactive, 'owner_inactive');
+ expect(inactive.notices[0].fix.command).toBe('gbrain access member enable owner-example');
+ await engine.executeRaw('UPDATE access_members SET disabled_at = NULL WHERE id = $1', [OWNER]);
+ }, 120_000);
+
+ test('--readers source imports open as today with no notice; any other value refuses', async () => {
+ const doc = await importOnce(['--readers', 'source']);
+ expect(doc.pages[0]).toMatchObject({ scoped: false, reason: 'readers_source', readers: null });
+ expect(doc.notices).toBeUndefined();
+ expect(await remote('alice', SLUG.debrief)).toContain('canaryhiringband');
+ await expect(importOnce(['--readers', 'everyone'])).rejects.toMatchObject({ code: 'invalid_params' });
+ }, 120_000);
+
+ test('a one-person brain, and an owner with group-chat audiences, import exactly as before', async () => {
+ {
+ await one.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [SRC]);
+ const before = await importJson(one, fresh());
+ await one.executeRaw("INSERT INTO access_members (id, kind) VALUES ($1, 'person'), ('room-a-example', 'audience'), ('room-b-example', 'audience')", [OWNER]);
+ await setOwner(one, OWNER);
+ expect(await callScopeGate(one, NO_STDIO)).toEqual({ applies: false });
+ await one.executeRaw("DELETE FROM pages WHERE source_id = $1", [SRC]);
+ const after = await importJson(one, fresh());
+ for (const doc of [before, after]) {
+ expect(doc.pages[0].scoped).toBeUndefined();
+ expect(doc.readers).toBeUndefined();
+ }
+ const [row] = await one.executeRaw<{ frontmatter: Record<string, unknown> }>('SELECT frontmatter FROM pages WHERE source_id = $1 AND slug = $2', [SRC, SLUG.debrief]);
+ expect(row!.frontmatter.readable_by).toBeUndefined();
+ }
+ expect(n).toBeGreaterThan(0);
+ expect(prefixOf()).toBe('company/calls');
+ }, 240_000);
+ });
+}
+
+describe('call import keeps calls to their attendees (pglite, git-backed)', () => {
+ let managed: PGLiteEngine;
+ beforeAll(async () => { managed = new PGLiteEngine(); await managed.connect({}); await managed.initSchema(); }, 120_000);
+ afterAll(async () => { await managed?.disconnect(); });
+ test('the page file carries readable_by in the committed tree, and the guard is raised by the import even while the commit is queued', async () => {
+ const fixture = temp('gbrain-calls-repo-');
+ const brain = join(fixture, 'brain');
+ const calls = join(fixture, 'calls');
+ mkdirSync(brain);
+ mkdirSync(calls);
+ for (const args of [['init', '-q', '-b', 'main'], ['config', 'user.name', 'Example'], ['config', 'user.email', '[email protected]'], ['config', 'commit.gpgsign', 'false'], ['commit', '-q', '--allow-empty', '-m', 'init']]) spawnSync('git', ['-C', brain, ...args]);
+ writeFileSync(join(calls, '2026-11-12 hiring debrief.md'), CALLS['2026-11-12 hiring debrief.md']!);
+ await managed.setConfig('sync.repo_path', brain);
+ for (const id of [OWNER, 'carol-example', 'alice-example']) await managed.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await setOwner(managed, OWNER);
+ await withEnv({ GBRAIN_HOME: join(fixture, 'home') }, async () => {
+ startPersistenceConsumer(managed, { engine: 'pglite' });
+ await new Promise(r => setTimeout(r, 50));
+ await managed.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");
+ const chunks: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { chunks.push(a.map(String).join(' ')); });
+ try { await runCallImport(managed, calls, ['--calls', '--prefix', 'company/calls'], { json: true, unboundStdio: NO_STDIO }); } finally { spy.mockRestore(); }
+ await managed.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");
+ const doc = JSON.parse(chunks.join(''));
+ expect(doc.pages[0]).toMatchObject({ status: 'imported', scoped: true, readers: [OWNER, 'carol-example'] });
+ const guardedNow = async () => Number((await managed.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_label_guards g JOIN pages p ON p.id = g.page_id WHERE p.slug = $1', [SLUG.debrief]))[0]!.n);
+ const show = () => spawnSync('git', ['-C', brain, 'show', `HEAD:${SLUG.debrief}.md`], { encoding: 'utf8' }).stdout;
+ expect(readFileSync(join(brain, `${SLUG.debrief}.md`), 'utf8')).toMatch(/\nreadable_by:\n {2}- owner-example\n {2}- carol-example\n/);
+ expect(await guardedNow()).toBe(1);
+ for (let i = 0; i < 100 && !show(); i++) {
+ await runPersistenceEffects(managed, { engine: 'pglite', embedding_disabled: true } as never, { hostId: localHostId() });
+ if (!show()) await new Promise(r => setTimeout(r, 100));
+ }
+ expect(show()).toMatch(/\nreadable_by:\n {2}- owner-example\n {2}- carol-example\n/);
+ if (doc.pages[0].git_state !== 'committed') {
+ const again: string[] = [];
+ const spy2 = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { again.push(a.map(String).join(' ')); });
+ try { await runCallImport(managed, calls, ['--calls', '--prefix', 'company/calls'], { json: true, unboundStdio: NO_STDIO }); } finally { spy2.mockRestore(); }
+ expect(JSON.parse(again.join('')).pages[0]).toMatchObject({ status: 'unchanged', readers: [OWNER, 'carol-example'], readers_from: 'stored' });
+ }
+ expect(await guardedNow()).toBe(1);
+ }).finally(async () => { await disposePersistenceConsumer(managed); });
+ }, 120_000);
+});
diff --git a/test/setup-brain-layout.test.ts b/test/setup-brain-layout.test.ts
index ec36c96de0..4775bc76bc 100644
--- a/test/setup-brain-layout.test.ts
+++ b/test/setup-brain-layout.test.ts
@@ -451,9 +451,12 @@ describe('setup --transcripts', () => {
const b = box();
expect((await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company'])).exitCode).toBe(0);
for (const m of ['alice-example', 'bob-example']) expect((await gbrain(b, ['auth', 'rescope', '--token', `member-${m}`, '--sources', 'default'])).exitCode).toBe(0);
- const r = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company', '--transcripts', callsDir(b, plantedToken())]);
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company', '--no-stdio-member', '--transcripts', callsDir(b, plantedToken())]);
expect(r.exitCode).toBe(0);
expect(r.doc.brain_layout.company).toMatchObject({ action: 'kept', federated: false });
+ expect(r.doc.brain_layout.transcripts.calls).toBeUndefined();
+ expect(r.doc.brain_layout.transcripts.not_scoped).toMatchObject({ reason: 'stdio_unbound' });
+ expect(r.doc.brain_layout.transcripts.not_scoped.command).toContain('--stdio-member');
expect(r.doc.serves.regrant).toBeUndefined();
const t = r.doc.brain_layout.transcripts;
expect(t.imported).toBe(3);
@@ -464,18 +467,28 @@ describe('setup --transcripts', () => {
expect(t.readers.detail).not.toContain('every member key gbrain setup minted');
}, 300_000);
- test('GBRA-585: setup for several people says the member keys it minted read the imported calls, and why the archive is on', async () => {
+ test('GST-2904: a company setup for several people ties its own entry to the owner and keeps each call to the owner and its attendees; the archive says why it is on', async () => {
const b = box();
- const r = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company', '--transcripts', callsDir(b, plantedToken())]);
+ const calls = callsDir(b, plantedToken());
+ writeFileSync(join(calls, '2026-03-05 hiring debrief.md'), 'Attendees: alice-example, dave-example\n\nAlice: the staff engineer range is set.\n');
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', 'alice-example,bob-example', '--shape', 'company', '--transcripts', calls]);
expect(r.exitCode).toBe(0);
expect(r.doc.brain_layout.company).toMatchObject({ action: 'created', federated: false });
expect(r.doc.serves.engine).toContain('gbrain migrate --to postgres');
const t = r.doc.brain_layout.transcripts;
- expect(t.imported).toBe(3);
- expect(t.readers.members).toBe('every_source_reader');
- expect(t.readers.serves).toBe('several');
- expect(t.readers.detail).toStartWith('every member key gbrain setup minted, and other keys only when their grant names source company or it is in default search');
- expect(t.readers.detail).toContain('this brain serves several people: alice-example, bob-example');
+ const owner = r.doc.target.stdio_member;
+ expect(owner).toBe(r.doc.serves.stdio.member);
+ expect(r.doc.serves.owner_from).toBe('login');
+ expect(r.doc.serves.brain_serves).toBe('several');
+ expect(t.imported).toBe(4);
+ expect(t.not_scoped).toBeUndefined();
+ expect(t.readers).toBeUndefined();
+ expect(t.calls).toContainEqual({ slug: 'company/calls/2026-03-05-hiring-debrief', readers: [owner, 'alice-example'], unmatched: ['dave-example'] });
+ for (const slug of CALL_SLUGS) expect(t.calls).toContainEqual({ slug, readers: [owner], unmatched: [] });
+ const reads = async (member: string, slug: string) => (await gbrain(b, ['get', slug, '--source', 'company', '--as', member])).exitCode === 0;
+ expect(await reads('alice-example', 'company/calls/2026-03-05-hiring-debrief')).toBe(true);
+ expect(await reads('bob-example', 'company/calls/2026-03-05-hiring-debrief')).toBe(false);
+ expect((await gbrain(b, ['get', 'company/calls/2026-03-05-hiring-debrief', '--source', 'company'])).exitCode).toBe(0);
expect(r.doc.serves.regrant.keys.map((k: any) => [k.member, k.adds])).toEqual([['alice-example', ['company']], ['bob-example', ['company']]]);
const archive = r.doc.brain_layout.archive;
expect(archive.state).toBe('on');
@@ -547,6 +560,17 @@ describe('transcripts units', () => {
expect(lines).toContain(' what leaves this machine: with a chat model key set, atom extraction (within cycle.extract_atoms.budget_usd) can send call text to your chat provider, within the limits you set; embedding waits for your approval');
expect(lines.find((l) => l.startsWith(' calls '))).toContain('2 new, 0 unchanged, 0 kept, 1 credential(s) redacted');
expect(lines).toContain(' archive conversation archive offered, not on: this brain may serve more than one person (gbrain transcripts archive on turns it on)');
+ const scoped = { ...o, transcripts: { ...o.transcripts, readers: undefined, calls: [
+ { slug: 'company/calls/2026-03-05-hiring-debrief', readers: ['owner-example', 'alice-example'], unmatched: ['dave-example'] },
+ { slug: 'company/calls/2026-02-01-weekly-sync', readers: ['owner-example'], unmatched: [] }] } };
+ const kept = describeLayout(scoped, false);
+ expect(kept).toContain(' each kept to the people on it (the owner reads every call):');
+ expect(kept).toContain(' company/calls/2026-03-05-hiring-debrief owner-example, alice-example');
+ expect(kept).toContain(' not matched: "dave-example". To add a reader: gbrain repair visibility --source company --slug company/calls/2026-03-05-hiring-debrief --readers owner-example,alice-example,<member>');
+ expect(kept).toContain(' company/calls/2026-02-01-weekly-sync owner-example (no other attendee matched a member)');
+ expect(kept.some((l) => l.includes('readable by'))).toBe(false);
+ const open = describeLayout({ ...o, transcripts: { ...o.transcripts, not_scoped: { reason: 'stdio_unbound', why: 'New calls were imported open.', command: 'gbrain setup claude-code --stdio-member owner-example' } } }, false);
+ expect(open).toContain(' calls kept open, as before: New calls were imported open. Run: gbrain setup claude-code --stdio-member owner-example');
});
test('at a terminal, a local company brain asks for a call-transcript folder after the docs folder', async () => {
diff --git a/test/setup-company-access.test.ts b/test/setup-company-access.test.ts
index 6650b509bc..124577d1ef 100644
--- a/test/setup-company-access.test.ts
+++ b/test/setup-company-access.test.ts
@@ -255,8 +255,9 @@ describe('A: gbrain setup --shape company --transcripts gives the members the ca
const dir = join(b.root, 'calls');
mkdirSync(dir);
writeFileSync(join(dir, '2026-03-04 acme-example renewal.txt'), 'Alice: harbor ledger notes callcanary, we agreed to move acme-example to annual billing.\n');
- const r = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--shape', 'company', '--transcripts', dir, '--json']);
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--shape', 'company', '--no-stdio-member', '--transcripts', dir, '--json']);
expect(r.exitCode).toBe(0);
+ expect(r.doc.brain_layout.transcripts.not_scoped).toMatchObject({ reason: 'stdio_unbound' });
expect(r.doc.serves.regrant.keys.map((k: any) => [k.member, k.adds])).toEqual([['alice-example', ['company']], ['bob-example', ['company']]]);
expect(r.doc.brain_layout.transcripts.readers.detail).toMatch(/^every member key gbrain setup minted, and other keys only when their grant names source company/);
expect(r.doc.brain_layout.transcripts.readers.detail).not.toContain('everyone who can read source company');
@@ -437,8 +438,9 @@ describe('C: gbrain setup --shape company --labelled-only gives labelled-only me
const dir = join(b.root, 'calls');
mkdirSync(dir);
writeFileSync(join(dir, '2026-03-04 acme-example renewal.txt'), 'Alice: harbor ledger notes callcanary, we agreed to move acme-example to annual billing.\n');
- const r = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--shape', 'company', '--transcripts', dir, '--labelled-only', '--json']);
+ const r = await setup(b, ['claude-code', '--serves', 'several', '--members', ROSTER.join(','), '--owner', 'owner-example', '--shape', 'company', '--no-stdio-member', '--transcripts', dir, '--labelled-only', '--json']);
expect(r.exitCode).toBe(0);
+ expect(r.doc.brain_layout.transcripts.not_scoped).toMatchObject({ reason: 'stdio_unbound' });
expect(r.doc.serves.regrant.company_rule).toMatchObject({ prefix: 'company/', action: 'add', readers: ['member:alice-example', 'member:bob-example', 'member:owner-example'] });
expect(r.doc.brain_layout.transcripts.readers).toMatchObject({ members: ['alice-example', 'bob-example', 'owner-example'], serves: 'several' });
expect(r.doc.brain_layout.transcripts.readers.detail).toMatch(/^alice-example, bob-example, owner-example only \(the company\/ rule on source company names them/);