Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Hold a gbrain CLI to one member's view with GBRAIN_ENFORCED_MEMBER

garrytan3244f46b433e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a112377797..7d701ec202 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**An agent that runs gbrain for one member can now be held to that member's view of the brain.** Set `GBRAIN_ENFORCED_MEMBER=<member>` in the launcher that starts the agent's gbrain calls, and every command it runs reads exactly what a remote credential bound to that member would read: pages kept to other members, private pages, folders the member is outside of and other members' personal sources leave no slug, title, body, fact or count behind. Writes still land where they land today, as trusted local writes, but the mode refuses a write to a page the member cannot read and every change to a page's readers or visibility. `remember` saves a fact only with `--entity` naming a page the member reads, and its refusal says so with the exact retry command. `gbrain write-request <id>` reads the member's own receipts, and any other id answers exactly like an unknown one. sync, `sources refresh` and `git commit-push` keep working with their output replaced by one line, `doctor` prints only check names, statuses and counts, and `hook` succeeds silently so group turns never fail. Every other command is refused with one exact line, exit 3 and the code `enforced_member_refused`, and so is everything when the value is empty, names an unknown member or names the owner. Unset, nothing changes. The mode binds only a caller whose launcher pins the variable; a process that can unset it, or read the brain's files or database directly, is outside it. Guide: [docs/guides/enforced-member.md](docs/guides/enforced-member.md).
+
+### Itemized changes
+
+- `src/cli/enforced-member.ts`, `src/cli/enforced-member-classes.ts`, `src/cli/enforced-commit-push.ts`: the gate, the allow-list (every CLI command and operation classified once) and the read, write and commit-push checks; `src/cli/main.ts` calls the gate before any dispatch.
+- `src/core/cli-force-exit.ts`: `setStdoutCapture`, so the mode also withholds what a command writes through the fd-1 chain (`--json` documents).
+- `src/mcp/dispatch.ts`: `DispatchOpts.enforcedMember` forces hidden privacy and no owner access on a dispatched read.
+- `src/commands/recall.ts`: recall reads through the member filter under the mode; `src/cli/cli-socket-client.ts`, `src/cli.ts`: the warm socket and the skill-resolver fast path are skipped under the mode.
+- `src/core/error-registry.ts`: new code `enforced_member_refused` (regenerated `docs/guides/error-codes.md`).
+- Known limits: a PGLite brain with a running `gbrain serve` refuses every enforced-mode read; a thin-client install refuses; creating a page at a slug the member cannot read refuses where a free slug would be created.
+- Tests: `test/enforced-member.serial.test.ts` (CLI subprocesses on PGLite and Postgres, repo-less and git), `test/enforced-member-classes.test.ts`.
+
## [0.60.678.0] - 2026-11-11
**Pushes from an unmanaged checkout now scan every commit they publish for secrets, not only the files they just wrote.** Four gbrain pushes from a checkout that is not a managed worktree carried earlier local commits to the remote unscanned: the access-policy commit, the durability-scaffolding commit, `gbrain sources push` (which scanned only its own staged files, then pushed the whole branch tip, even with nothing new to commit) and the first push of `gbrain bootstrap repo` after the remote branch was gone (which scanned only the current tree). A credential a script committed with plain `git commit`, including one a later commit removed or one in a commit message, went out with them. Each now runs the range scan managed publishes use over what the remote lacks (the whole history when the remote has no such branch) and refuses `publish_secret_found` or `publish_scan_unreadable`, with nothing pushed and the local commits kept. `gbrain sources push` pushes the exact commit it scanned, leased on the remote tip it read, so a remote rewound in between is scanned again. An allowlist edit that `gbrain sources push` or `gbrain bootstrap repo` commits itself, after scanning it, still publishes; one a script committed is left to the user. Remoteless checkouts, managed worktrees and repo-less brains are unchanged, and the policy command's retry hint keeps `--scan-secrets`.
diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.md
index a6f502986b..077afa8b5f 100644
--- a/docs/architecture/key-files/access.md
+++ b/docs/architecture/key-files/access.md
@@ -8,3 +8,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/access/serves.ts` + `src/commands/access-serves.ts` (GST-363 PR 1) — whether a brain serves several people (`brainServes`: config `access.serves` `one`|`several` wins, else 2+ enabled members) and `gbrain access serves [several --members a,b [--yes]]`: preview, then config, members (kept when present), one folder rule `people/<member>/` per member through `addFolderRules` (`access-rules.ts`, the `rule add` preview-then-write path; a git store commits `.gbrain/access.yml` through the commit door), and one read-write token `member-<id>` per member through `auth-mint.ts` (the `auth create` mint) written to `<configDir>/member-keys/<id>.key` (0600, dir 0700, refused inside a git work tree: `access_serves_key_dir_in_git`). Idempotent on the member id; a token whose file is gone is reported, never re-minted. `GBRAIN_SETUP_ABORT_AFTER=serves-members|serves-rules|serves-key` is the crash seam. Doctor: `checks/unlabeled-people-folders.ts` fails a `people/<x>/` folder with pages no rule covers on a several-person brain. Tests: `test/setup-serves-several.test.ts` (both engines).
- `gbrain serve --stdio-member <id>` (GST-363 PR 3) — `parseStdioMemberFlag`, `registeredStdioMember` and `withStdioMember` live in `src/core/stdio-member-flag.ts` (kept out of `mcp-registration.ts` so serve and doctor pick up no registration flags); serve passes the value to `startMcpServer`, dispatch sets `OperationContext.stdioMember` only for an unauthenticated stdio call, and `caller.ts` resolves it live ahead of config `mcp.stdio_member` (a disabled or unknown member reads as nobody, no fallback). Stored writes stamp it on `WriteAuthority.stdioMember` (jsonb, no migration); a stdio watch uses principal id `registration` so the wake drain re-checks that member. Setup writes it into one claude-code or codex entry (`ClaudeSetupPlan`/`CodexSetupPlan.stdioMember`); inspection reports an owned entry's member so setup re-runs and `refreshHookLaunchers` carry it, and `setupRerunArgv` never names it.
- `src/core/ops/qm-memory.ts` (GST-359 D) — QM's memory provider pair. `memory_recall` reads the attested person's own last-24-hour facts on their member page (`listFactsSince` with `sourceMarkdownSlug`), then `rankFactsByQuestion` over the facts they may read, renders one plain line per fact (`plainFactText` strips fence and heading markers) and cuts at a line within `max_chars` (`boundFactLines`). A call that names `source_id` or `source_ids` (full surface only) reads as that scope instead: `recallSources` resolves them through `requestSourceScope` (a source outside the credential's grant is `permission_denied`), `SCOPE_READ_ACCESS` empties identity, actor and audience, so no own facts and no member-page fact are read, restricted pages stay hidden and privacy is never relaxed; the query is ranked on its first 2,000 characters (`MEMORY_RECALL_QUERY_CHARS`). `memory_write` validates 1-20 facts, derives each request id from uuidv5(member, idempotency_key) (`memoryWriteRequestId`) and saves through `remember`'s handler with `ctx.attestedOp = 'memory_write'`, which the stored write authority keeps (`WriteAuthority.attestedOp`) so publication and receipt reads re-check that operation's attest right. `qmMemoryToolResult` (dispatch) moves the result into `structuredContent` and leaves the model text in `content`; GST-1158 F2 does the same for an attested call to a contract v3 personal tool (`QM_PERSONAL_OPS`), keeping its JSON in `content` (a list as `structuredContent.results`; context_pack's text alone, like memory_recall), and dispatch measures that frame against the result cap again; each memory_recall fact carries `arm` (`own` or `ranked`, F5) and `own_page` (GST-2407: `member-facts.ts` `ownMemberFactIds`, the one set forget_fact's ownership gate also reads); `unlinkedRecallResult` is the empty success dispatch's `actorRefusal` returns for an unlinked person. Contract fixture: `scripts/build-qm-memory-contract.ts` writes `docs/contracts/qm-memory-provider/v1.json` (frozen, byte-identical) and `v2.json` (the scope read and write; `regen:all` artifacts; `v3.json` adds the personal tools with frozen result shapes; `v4.json` adds memory_propose, each personal tool's `scope_read` marking and `own_page`). Scope writes (GST-1113): `memory_write {source_id}` saves on `memory/scope` in a scope source listed in the credential's `attest_sources` (migration v293, on `access_tokens` and `oauth_clients`); `access/attest-sources.ts` holds `perCallWriteSource` (the one exemption from the one-write-source checks in `page-mutations.ts`, `memory-mutations.ts` and `persistence/authority.ts`, keyed to that slug and re-checked at publication through `actorCoverage(..., source)`), the sticky mark `sources.config.qm_scope` (set by `applyAttestSources` under row locks; `isSourceFederated` ignores federation on it), `assertScopeSourceGrant` (in `insertClientGrant`, `persistGrant`, `writeTokenGrant` and `insertUnifiedToken`) and `withoutScopeSources` (a person recall never reads a scope source). `member-facts.ts` `assertScopePageWriter` keeps other remote writers off `memory/scope`. Tests: `test/qm-scope-writes.test.ts` (both engines), `test/qm-memory-tools.test.ts` (both engines), `test/qm-personal-tools.test.ts` (v3 tools over dispatch, both engines), `test/qm-memory-contract.test.ts` (drift), `test/e2e/serve-http-qm-memory.test.ts` (keyless `serve --http`).
+- `src/cli/enforced-member.ts` + `src/cli/enforced-member-classes.ts` + `src/cli/enforced-commit-push.ts`: enforced member mode ([guide](../../guides/enforced-member.md)). With `GBRAIN_ENFORCED_MEMBER` set, `enforcedGate` in `src/cli/main.ts` classifies the command before any dispatch (`enforcedClassOf`: read, write, allowed, silent or refused; anything unclassified is refused, exit 3, `enforced_member_refused`). An empty value, an unknown member or the owner id refuses everything. Reads go through `dispatchToolCall` with `remote: true`, `transport: 'stdio'`, `stdioMember` and `enforcedMember: true` (dispatch forces `hidePrivate`, `owner: false` and no private-readable sources), minus other members' personal sources (`hiddenPersonalSources`; an explicit `--source` naming one refuses), and `namesHiddenPage` withholds any output that still names a hidden page. Writes stay trusted local writes (`ctx.remote` false): `checkEnforcedWrite` refuses a target the member cannot read (`memberPageView`) and any label change, and `remember` needs `--entity` naming a readable page (`checkEnforcedRemember`, the one decision point). `write-request` answers only ids in the member's receipt ledger (`recordEnforcedReceipts`, `configDir()/enforced-member/<member>.receipts`); any other id is swapped for a fresh one, so it answers as unknown. sync, `sources refresh` and `git commit-push` (checked by `checkEnforcedCommitPush`: every named path readable, no label or `.gbrain/` change, refused modes) run with output replaced by one line (`withWithheldOutput`, which also captures the fd-1 chain through `setStdoutCapture`); `doctor` prints only check names, statuses and counts (`withDoctorCounts`); `hook` succeeds silently. The warm CLI socket, the persistence delegate and the skill-resolver fast path are skipped under the mode. Tests: `test/enforced-member.serial.test.ts` (CLI subprocesses, both engines, repo-less and git), `test/enforced-member-classes.test.ts` (every command and operation classified once).
diff --git a/docs/guides/enforced-member.md b/docs/guides/enforced-member.md
new file mode 100644
index 0000000000..420eff0e60
--- /dev/null
+++ b/docs/guides/enforced-member.md
@@ -0,0 +1,87 @@
+# Enforced member mode
+
+Set `GBRAIN_ENFORCED_MEMBER=<member>` in the environment of a gbrain process and
+the CLI acts as that one member instead of as the brain owner. A group-chat turn
+that runs `gbrain search` sees only what that member may read, its writes can't
+touch a page the member can't read, and anything the mode doesn't know is refused.
+
+It is meant for a launcher (a harness's wrapper or the cron wrapper in
+[cron-schedule.md](cron-schedule.md#calling-gbrain-unattended)) that pins the
+variable for every call it makes. The mode binds only a caller whose launcher
+pins it: a process that unsets the variable, or a script that opens the database
+directly, is outside it.
+
+## What each command does
+
+Every CLI command, and every subcommand of a command that mixes reads, writes
+and admin, has one class. The list is code (`src/cli/enforced-member-classes.ts`),
+and a test fails when a new command or operation has no class.
+
+| Class | What happens |
+|---|---|
+| read | The command answers exactly as a stdio MCP server bound to the member would: page readers (`readable_by`), folder rules and `visibility: private` all apply, and other members' personal sources are out of scope. Stderr gets one constant line: `gbrain: results limited to what GBRAIN_ENFORCED_MEMBER=<member> may read`. It prints the same line whether or not anything was hidden. |
+| write | A normal local write. It lands where and as visible as it would without the mode, after two checks: every target page (and its source) must be one the member reads, and the write must not change an access or privacy label (`visibility`, `readable_by`, the privacy aliases, a private fact or takes fence). |
+| allowed | `sync`, `sources refresh <id>`, `git commit-push --pull`, `doctor` and the offline `errors` and `protocol`. The first three run as usual, but their output is replaced by one constant line (and the bare error code on failure), so imported or held paths never print. `doctor` (plain or `--json`, no other flags) prints only each check's name and status and the count per status: no message, slug, path, title or source name. |
+| silent | `hook` only. Nothing on stdout, the constant stderr line, exit 0. Harness hooks run inside group turns and must not fail them; this is the one deliberate exception to "anything not listed exits non-zero". |
+| refused | Everything else: `--as`, `call`, `serve`, `config`, `auth`, `access`, `upgrade`, `autopilot`, `repair`, `delete`, `jobs`, `reindex`, `embed`, `dream`, `doctor` with any flag, `status`, `write-requests`, every status command that names held paths (`sync status`, `sources status`, `sources writer status`), raw SQL and anything that prints a credential. |
+
+Reads: `search`, `query`, `search --exact`, `list`, `find`, `get`,
+`backlinks`, `timeline`, `links`, `tags`, `history`, `stats --by` (the plain
+brain-wide counters are refused), `whoami`, `entity`, `whois`, `graph` and
+`recall` (its entity, `--since`, `--question`, `--grep` and `--query` arms).
+
+Writes: `put`, `edit_page`, `append_page`, `link`, `unlink`, `tag`, `untag`,
+`timeline-add`, `remember` and `git commit-push` with named paths. `remember`
+saves one fact only with `--entity` naming the exact slug of a page the member
+reads; nothing is inferred. Without it, the refusal's first line says so and
+that nothing was saved, and its next line is the retry shape:
+
+```
+gbrain: refused under GBRAIN_ENFORCED_MEMBER=alice-example: remember saves a fact only with --entity <slug of a page you can read>; nothing was saved [GBRAIN_ENFORCED_REFUSED]
+Retry: gbrain remember "<one fact>" --entity <exact slug of a page you can read, from gbrain find or gbrain search> --provenance "<where you learned it>"
+```
+
+`gbrain write-request <id>` reads the receipt of a write this mode accepted
+for the member (it records those request ids in `~/.gbrain/enforced-member/`
+on the machine that ran the write). Any other id answers exactly as an unknown
+one. `git commit-push` refuses a named
+file the member can't read, an access policy file (`.gbrain/`) and any label
+change against HEAD; `--pending`, `--push-only` and `--resolve` are refused.
+
+<a id="refused"></a>
+## Refused
+
+A refusal exits 3 and writes this to stderr, with no secret values:
+
+```
+gbrain: refused under GBRAIN_ENFORCED_MEMBER=alice-example: config [GBRAIN_ENFORCED_REFUSED]
+Why: This command is not on the enforced member allow-list.
+Fix: ask the brain owner to run this in a direct session (one without GBRAIN_ENFORCED_MEMBER).
+Recovery: do not retry here; nothing was changed.
+Docs: docs/guides/enforced-member.md#refused
+```
+
+With `--json`, stdout carries the `enforced_member_refused` envelope. An agent
+should stop and tell the user, not retry: the same call refuses every time. The
+variable set but empty, naming no enabled member, or naming the brain owner
+(`gbrain access owner set`) refuses every command except help, `errors` and
+`protocol`. It never falls back to the owner.
+
+## Limits
+
+- **PGLite with a running `gbrain serve`.** The mode never hands a call to a
+ live serve (the serve answers as the owner), so it opens the brain itself. A
+ PGLite brain allows one process at a time, so on a PGLite brain with a running
+ `gbrain serve`, every enforced-mode read (and write) fails closed with the
+ lock error. Postgres brains are not affected.
+- **A thin client** (a remote MCP config) reads as its own credential, so it
+ refuses every command under the mode.
+- **Create versus refuse.** A write to a page the member can't read is refused,
+ while a write to a slug no page has yet creates it, so a writer can tell those
+ two apart. The refusal never says the page exists.
+- **The warm CLI socket** is skipped under the mode.
+- **Receipts are per machine.** `write-request` answers only receipts recorded
+ on the machine that ran the write; on another machine they answer as unknown.
+- **doctor statuses are brain-wide.** A check's status counts pages the member
+ can't read, so a status can change because of one. Names, statuses and counts
+ are all it prints.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 052d6a4fda..6118b5a284 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1562,6 +1562,18 @@ More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/trouble
|---|---|---|---|---|---|---|
| The embedding model cannot produce the width of the brain's vector column; nothing was changed. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### enforced_member_refused
+
+<a id="enforced_member_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The CLI runs under GBRAIN_ENFORCED_MEMBER and refused the command before it read or changed anything: the command or its arguments are not on the enforced member allow-list, the variable names no usable member, a target page or source is outside what the member reads, or the write would change an access or privacy label. | A launcher pins GBRAIN_ENFORCED_MEMBER so a shared agent turn acts as one member: reads show only what that member reads, writes never touch a page it cannot read or change a label, and anything not classified is refused rather than run as the trusted owner. Stderr starts with gbrain: refused under GBRAIN_ENFORCED_MEMBER=<member>: <command> [GBRAIN_ENFORCED_REFUSED]. | Do not retry here; nothing was changed. Ask the brain owner to run the command in a direct session, one without GBRAIN_ENFORCED_MEMBER. | user | `repeat the read that failed` | 3 | no |
+
+Reasons: `command_not_allowed`, `member_not_usable`, `target_not_readable`, `label_change`, `thin_client`, `as_flag`, `arguments_not_allowed`, `remember_needs_entity`.
+
+More: [docs/guides/enforced-member.md#refused](../../docs/guides/enforced-member.md#refused)
+
### engine_closed
<a id="engine_closed"></a>
diff --git a/scripts/enforced-member-table.ts b/scripts/enforced-member-table.ts
new file mode 100644
index 0000000000..4c98b426de
--- /dev/null
+++ b/scripts/enforced-member-table.ts
@@ -0,0 +1,31 @@
+/**
+ * GST-2476 G2: prints the enforced member classification (every CLI command and operation-backed command, with the
+ * subcommands whose class differs) as a Markdown table. Usage: bun scripts/enforced-member-table.ts
+ */
+import { OPERATION_MANIFEST } from '../src/cli/op-manifest.ts';
+import { CLI_COMMANDS } from '../src/cli/command-table.ts';
+import { OPERATION_CLASSES, CLI_COMMAND_CLASSES, OPERATION_SUBCOMMANDS, type EnforcedClass, type EnforcedSubcommands } from '../src/cli/enforced-member-classes.ts';
+
+const rows = new Map<string, EnforcedClass | 'UNCLASSIFIED'>();
+const add = (name: string, spec: EnforcedClass | EnforcedSubcommands | undefined) => {
+ if (spec === undefined) { rows.set(name, 'UNCLASSIFIED'); return; }
+ if (typeof spec === 'string') { rows.set(name, spec); return; }
+ rows.set(name, spec.default);
+ for (const [sub, cls] of Object.entries(spec.sub)) rows.set(name + ' ' + sub, cls);
+};
+for (const c of CLI_COMMANDS) add(c.name, CLI_COMMAND_CLASSES[c.name]);
+const cliOnly = new Set(CLI_COMMANDS.map(c => c.name));
+for (const op of OPERATION_MANIFEST) {
+ if (op.cliHints?.hidden) continue;
+ const cls = OPERATION_CLASSES[op.name];
+ for (const name of [op.cliHints?.name ?? op.name, ...(op.cliHints?.aliases ?? [])]) {
+ if (cliOnly.has(name) || rows.has(name)) continue;
+ const sub = OPERATION_SUBCOMMANDS[name];
+ add(name, cls === undefined ? undefined : sub && cls !== 'refused' ? sub : cls);
+ }
+}
+const sorted = [...rows].sort(([a], [b]) => a.localeCompare(b));
+const count = (c: string) => sorted.filter(([, v]) => v === c).length;
+console.log('Commands: ' + sorted.length + ' (read ' + count('read') + ', write ' + count('write') + ', allowed ' + count('allowed') + ', silent ' + count('silent') + ', refused ' + count('refused') + ', unclassified ' + count('UNCLASSIFIED') + '; anything unclassified is refused).\n');
+console.log('| Command | Class |\n|---|---|');
+for (const [name, cls] of sorted) console.log('| ' + name + ' | ' + cls + ' |');
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 728118c9e0..78c92c23e9 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 2970 ratchet +3 GBRA-156: thin-client page-cap line on stderr in formatResult (import and two lines; +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured); re-summed at the 0.60.484.0 merge with #7598 (2959 measured); +3 GBRA-218 local --as: the access SELF_HELP_WITHOUT_ENGINE row, the --as refusal call and the preview open (logic in cli/as-preview.ts); re-summed at the GBRA-218 merge with #7593 (2962 measured); +3 #8426: serve captures the session directory the hook launcher records (import, comment, call; logic in core/session-cwd.ts); re-summed at the train R merge with v0.60.574.0: 2965 + 2; re-summed at the memory train #8481 merge with v0.60.576.0 (2970 measured); +4 GBRA-224: the startup hook resolves the release channel and prints the one-time channel notice (logic in core/release-channel-notice.ts, core/self-upgrade.ts; fits the master ceiling at the GBRA-346 merge: master 2956 + 4 = 2960)
+src/cli/main.ts 3001 ratchet +31 GST-2476 G2: enforced member gate call, socket and delegate skips, read/write dispatch seams and receipt recording (logic in cli/enforced-member.ts); +3 GBRA-156: thin-client page-cap line on stderr in formatResult (import and two lines; +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured); re-summed at the 0.60.484.0 merge with #7598 (2959 measured); +3 GBRA-218 local --as: the access SELF_HELP_WITHOUT_ENGINE row, the --as refusal call and the preview open (logic in cli/as-preview.ts); re-summed at the GBRA-218 merge with #7593 (2962 measured); +3 #8426: serve captures the session directory the hook launcher records (import, comment, call; logic in core/session-cwd.ts); re-summed at the train R merge with v0.60.574.0: 2965 + 2; re-summed at the memory train #8481 merge with v0.60.576.0 (2970 measured); +4 GBRA-224: the startup hook resolves the release channel and prints the one-time channel notice (logic in core/release-channel-notice.ts, core/self-upgrade.ts; fits the master ceiling at the GBRA-346 merge: master 2956 + 4 = 2960)
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)
src/commands/embed.ts 2306 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +2 agent operator wave D2: --json failure envelope via writeCliError
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 61b0c03d2e..c4c4a1b460 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -696,3 +696,7 @@ src/eval/brainbench/metrics/trust-reads.ts canaryPersisted sql STREAM
src/eval/chronicle/harness.ts seedChronicleEvalCorpus call:putPage SEGW
src/eval/longmemeval/call-plan.ts planPages call:prepareMarkdownChunks INLINE
src/eval/longmemeval/call-plan.ts planPages field INLINE
+src/cli/enforced-member.ts checkEnforcedWrite field INLINE the stored page comes from storedPage, which refuses a segmented page (assertInlineBody)
+src/cli/enforced-member.ts markdownLabels field NONE not a stored page body: the parsed markdown a put or a committed file submits
+src/cli/enforced-member.ts pageLabels field INLINE reads a page from storedPage (segmented refused by assertInlineBody) or parsed submitted markdown
+src/cli/enforced-member.ts storedPage sql INLINE refuses a segmented page with assertInlineBody before its body is read
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 9178715c3f..4ca1950983 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -156,6 +156,7 @@ test/e2e/segmented-rls-scope.test.ts (file-level) 5 readFileSync
test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
test/embedding-dim-check-facts.test.ts postgres-engine fact insert cast (T6, codex #20) 1 source-surface-helper
+test/enforced-member-classes.test.ts enforced member allow-list 4 readFileSync
test/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync
test/error-catalogue.test.ts error code registry (agent contract v1) 5 readFileSync
test/error-registry-6317-contract.test.ts #6317 codes are registered with a full envelope 3 readFileSync
diff --git a/src/cli.ts b/src/cli.ts
index d431130361..542b7dc5b7 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -34,7 +34,7 @@ export function cliFastPath(argv: string[], env: NodeJS.ProcessEnv = process.env
const command = rest[0];
if (!command || command === '--help' || command === '-h') return 'help';
if (command === '--version' || command === 'version') return 'version';
- if (env.GBRAIN_HOOK_LANE === 'skill-resolver' && command === 'hook' && (rest[1] === 'user-prompt' || rest[1] === 'session-start')
+ if (env.GBRAIN_HOOK_LANE === 'skill-resolver' && env.GBRAIN_ENFORCED_MEMBER === undefined && command === 'hook' && (rest[1] === 'user-prompt' || rest[1] === 'session-start')
&& !rest.some(a => a === '--help' || a === '-h')) return 'skill-resolver-lane';
return null;
}
diff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.ts
index ecd4b81b96..ee71d44c09 100644
--- a/src/cli/cli-socket-client.ts
+++ b/src/cli/cli-socket-client.ts
@@ -241,7 +241,7 @@ export async function renderOp(command: string, op: OperationMeta, params: Recor
* caller runs the normal cold path.
*/
export async function maybeServeFromCliSocket(command: string, args: string[]): Promise<boolean> {
- if (!CLI_SOCKET_COMMANDS.includes(command) || process.env.GBRAIN_CLI_SOCKET === '0') return false;
+ if (!CLI_SOCKET_COMMANDS.includes(command) || process.env.GBRAIN_CLI_SOCKET === '0' || process.env.GBRAIN_ENFORCED_MEMBER !== undefined) return false;
const config = loadConfig();
if (!config || config.engine !== 'postgres' || !config.database_url || isThinClient(config)) { debug('not a local postgres brain'); return false; }
const cliOpts = getCliOptions();
diff --git a/src/cli/enforced-commit-push.ts b/src/cli/enforced-commit-push.ts
new file mode 100644
index 0000000000..62fa8a867a
--- /dev/null
+++ b/src/cli/enforced-commit-push.ts
@@ -0,0 +1,87 @@
+/**
+ * GST-2476 G2: what gbrain git commit-push may do under GBRAIN_ENFORCED_MEMBER. Named-path commits, --dry-run and
+ * --pull run (their output withheld by the caller); every other publishing mode is refused. Each named path (a
+ * directory expands to its changed files) must map to a source the member reads, must not be an access policy file,
+ * must not be a page the member cannot read or a new page under a folder rule it does not satisfy, and its access and
+ * privacy labels must equal those at HEAD.
+ */
+import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
+import { isAbsolute, join, relative, sep } from 'node:path';
+import { execFileSync } from '../core/spawn.ts';
+import type { BrainEngine } from '../core/engine.ts';
+import { enforcedAccess, markdownLabels, memberPageView, refuseEnforced } from './enforced-member.ts';
+
+const VALUE_FLAGS = new Set(['-m', '--message', '--path', '--repo', '--base', '--branch', '--resolve', '--expect-remote']);
+const REFUSED_FLAGS = new Set(['--pending', '--push-only', '--resolve', '--expect-remote', '--allow-outside-source-root', '--keep-checkout', '--branch', '--scan-secrets', '--install', '--uninstall']);
+
+function gitOut(repo: string, args: string[]): string | null {
+ try { return execFileSync('git', ['-C', repo, ...args], { stdio: ['ignore', 'pipe', 'ignore'] }).toString(); } catch { return null; }
+}
+
+export async function checkEnforcedCommitPush(engine: BrainEngine, args: readonly string[]): Promise<void> {
+ const command = 'git commit-push';
+ const ea = await enforcedAccess(engine, command);
+ let path: string | undefined;
+ let rest = false;
+ let pull = false;
+ let dryRun = false;
+ const named: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ if (rest) { named.push(a); continue; }
+ if (a === '--') { rest = true; continue; }
+ const flag = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
+ if (REFUSED_FLAGS.has(flag)) return refuseEnforced(command, 'arguments_not_allowed', { engine });
+ if (flag === '--pull') { pull = true; continue; }
+ if (flag === '--dry-run') { dryRun = true; continue; }
+ if (VALUE_FLAGS.has(flag)) {
+ const v = a.includes('=') && a.startsWith('--') ? a.slice(a.indexOf('=') + 1) : args[++i];
+ if (flag === '--path' || flag === '--repo') path = v;
+ continue;
+ }
+ if (a.startsWith('-')) continue;
+ if (a === 'commit-push' && !named.length) continue;
+ named.push(a);
+ }
+ if (pull && !named.length) return;
+ if (!named.length) return dryRun ? undefined : refuseEnforced(command, 'arguments_not_allowed', { engine });
+ const { checkoutRoot, scopePaths } = await import('../core/git/commit-push.ts');
+ let repo: string;
+ let files: string[];
+ try {
+ repo = realpathSync(checkoutRoot(path ?? process.cwd()));
+ const cwd = path ? realpathSync(path) : process.cwd();
+ files = [];
+ for (const rel of scopePaths(repo, named, cwd)) {
+ const abs = join(repo, rel);
+ if (existsSync(abs) && statSync(abs).isDirectory()) {
+ const out = gitOut(repo, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', rel]) ?? '';
+ const parts = out.split('\0').filter(Boolean);
+ for (let i = 0; i < parts.length; i++) {
+ const entry = parts[i]!;
+ files.push(entry.slice(3));
+ if (entry[0] === 'R' || entry[0] === 'C') files.push(parts[++i]!);
+ }
+ } else files.push(rel);
+ }
+ } catch {
+ return refuseEnforced(command, 'arguments_not_allowed', { engine });
+ }
+ const sources = await engine.executeRaw<{ id: string; local_path: string | null }>('SELECT id, local_path FROM sources WHERE local_path IS NOT NULL');
+ const roots = sources.flatMap(s => {
+ try { return s.local_path && isAbsolute(s.local_path) ? [{ id: s.id, root: realpathSync(s.local_path) }] : []; } catch { return []; }
+ }).sort((a, b) => b.root.length - a.root.length);
+ const { resolveSlugForPath } = await import('../core/sync.ts');
+ for (const rel of files) {
+ const abs = join(repo, rel);
+ const owner = roots.find(r => abs === r.root || abs.startsWith(r.root + sep));
+ if (!owner) return refuseEnforced(command, 'target_not_readable', { engine });
+ const inSource = relative(owner.root, abs).split(sep).join('/');
+ if (inSource === '.gbrain' || inSource.startsWith('.gbrain/')) return refuseEnforced(command, 'label_change', { engine });
+ const slug = resolveSlugForPath(inSource);
+ if (await memberPageView(engine, ea, owner.id, slug) === 'hidden') return refuseEnforced(command, 'target_not_readable', { engine });
+ if (!/\.mdx?$/i.test(rel) || !existsSync(abs)) continue;
+ const before = gitOut(repo, ['show', 'HEAD:' + rel]);
+ if (await markdownLabels(before, slug) !== await markdownLabels(readFileSync(abs, 'utf8'), slug)) return refuseEnforced(command, 'label_change', { engine });
+ }
+}
diff --git a/src/cli/enforced-member-classes.ts b/src/cli/enforced-member-classes.ts
new file mode 100644
index 0000000000..9efdbd9557
--- /dev/null
+++ b/src/cli/enforced-member-classes.ts
@@ -0,0 +1,140 @@
+/**
+ * GST-2476 G2: the allow-list of an enforced member CLI (GBRAIN_ENFORCED_MEMBER). Every CLI command and every
+ * operation has exactly one class; anything absent is refused (test/enforced-member-classes.test.ts fails when a
+ * command or operation has none).
+ *
+ * - read: read-filtered. The operation runs as the in-process stdio MCP server bound to the member would answer it
+ * (remote: true, the member's readers and folder rules, privacy always hidden).
+ * - write: write-checked. A trusted local write (ctx.remote false, landing exactly where and as visible as it lands
+ * without the mode), after the gate refuses a target page the member cannot read and every label change.
+ * - allowed: an operation the member's launcher runs (sync, a source refresh, git commit-push --pull) with its output
+ * replaced by one constant line, doctor with only check names, statuses and counts, or an offline command (errors,
+ * protocol).
+ * - silent: hook only. Nothing on stdout, the constant stderr line, exit 0: harness hooks run in group turns and must
+ * not fail them; the one deliberate exception to "anything unlisted exits non-zero".
+ * - refused: everything else.
+ */
+export type EnforcedClass = 'read' | 'write' | 'allowed' | 'silent' | 'refused';
+
+/** A command whose subcommands differ: the first positional picks the class, default covers the rest. */
+export interface EnforcedSubcommands {
+ default: EnforcedClass;
+ sub: Readonly<Record<string, EnforcedClass>>;
+}
+
+const READ_OPS = [
+ 'search', 'query', 'search_exact', 'list_pages', 'find_pages', 'get_page', 'get_backlinks', 'get_timeline', 'get_links',
+ 'get_tags', 'get_versions', 'get_stats', 'whoami', 'entity', 'whois', 'traverse_graph',
+] as const;
+
+const WRITE_OPS = [
+ 'put_page', 'edit_page', 'append_page', 'add_link', 'remove_link', 'add_tag', 'remove_tag',
+ 'add_timeline_entry', 'remember', 'get_write_request',
+] as const;
+
+/** Operations the mode refuses: admin and local-only surfaces, label and batch writes, and reads without a leak test. */
+const REFUSED_OPS = [
+ // reads not yet covered by a no-trace test (each can move to READ_OPS with one)
+ 'assemble_evidence', 'chronicle_day', 'chronicle_last_seen', 'chronicle_on_this_day', 'chronicle_since', 'context_pack',
+ 'delta', 'entity_identity_list', 'extraction_pending', 'fetch', 'find_contradictions', 'find_trajectory',
+ 'get_active_schema_pack', 'get_brain_health', 'get_brain_identity', 'get_calibration_profile', 'get_chunks',
+ 'get_ingest_log', 'get_memory_settings', 'get_raw_data', 'get_skill', 'get_skill_asset', 'join_brain', 'leave_brain',
+ 'list_brain_skillpack', 'list_link_sources', 'list_schema_packs', 'list_skills', 'list_write_conflicts',
+ 'memory_recall', 'ontology_conflicts', 'ontology_dimensions', 'ontology_get', 'open_loops', 'questions_list',
+ 'questions_status', 'rank_entities', 'recall', 'request_tools', 'resolve_slugs', 'schema_explain_type', 'schema_graph',
+ 'schema_lint', 'schema_review_orphans', 'schema_stats', 'search_by_image', 'search_modes', 'sync_brain_skills',
+ 'synthesize', 'takes_calibration', 'takes_list', 'takes_scorecard', 'takes_search', 'volunteer_chronicle',
+ 'volunteer_context', 'wanted_pages',
+ // hidden operations: no CLI path reaches them (their CLI names are CLI-only commands or gbrain call)
+ 'advisor', 'code_blast', 'code_callees', 'code_callers', 'code_def', 'code_flow', 'code_refs', 'find_anomalies',
+ 'find_experts', 'find_orphans', 'get_recent_salience', 'sources_list', 'sources_resolve_path', 'sources_status', 'think',
+ 'capture', 'list_page_purges', 'list_watches', 'purge_fact', 'unpurge_page', 'unwatch', 'watch_job', 'connectors_status',
+ 'get_recent_transcripts', 'sources_inspect', 'sources_add', 'sources_remove', 'connector_sync',
+ 'code_traversal_cache_clear', 'migrate_embeddings', 'purge_deleted_pages', 'sync_brain',
+ // writes outside the checked set: batch, upload, label, history, fact and queue writes
+ 'abort_page_upload', 'begin_page_upload', 'commit_page_upload', 'get_page_upload', 'upload_page_part', 'put_pages',
+ 'put_raw_data', 'put_skill', 'delete_skill', 'delete_page', 'restore_page', 'revert_version', 'cancel_write_request',
+ 'list_write_requests', 'confirm_memory', 'extract_entities', 'extract_facts', 'forget',
+ 'forget_fact', 'log_ingest', 'loops_close', 'loops_mute', 'loops_unmute', 'memory_conversation_mode', 'memory_propose',
+ 'memory_write', 'mute_notice', 'ontology_propose', 'questions_pin', 'questions_refresh', 'questions_unpin', 'rate_answer',
+ 'takes_add', 'takes_resolve', 'takes_supersede', 'takes_update', 'entity_identity_link', 'entity_identity_unlink',
+ 'extraction_review', 'takes_rebuild', 'takes_remove',
+ // admin, agent and local-only
+ 'cache_stats', 'cancel_job', 'get_health', 'get_job', 'get_job_progress', 'get_job_stats', 'get_skill_policy',
+ 'get_status_snapshot', 'get_usage', 'get_write_attribution', 'list_jobs', 'pause_job', 'quarantine_list',
+ 'reload_schema_pack', 'replay_job', 'resume_job', 'retry_job', 'run_doctor', 'run_onboard', 'run_skillopt',
+ 'schema_apply_mutations', 'search_stats', 'search_tune', 'send_job_message', 'set_memory_writeback', 'set_skill_policy',
+ 'submit_job', 'wait_job', 'chronicle_backfill', 'file_list', 'file_register', 'file_upload', 'file_url', 'file_verify',
+ 'get_skill_retention', 'import_skill_proposal', 'prune_skill_revisions', 'retain_skill_revision', 'get_agent_job',
+ 'submit_agent',
+] as const;
+
+export const OPERATION_CLASSES: Readonly<Record<string, EnforcedClass>> = Object.freeze(Object.fromEntries([
+ ...READ_OPS.map(n => [n, 'read'] as const),
+ ...WRITE_OPS.map(n => [n, 'write'] as const),
+ ...REFUSED_OPS.map(n => [n, 'refused'] as const),
+]));
+
+/** Classified operations whose arguments narrow the class further (checked by the gate after parsing). */
+export const ARGUMENT_CONDITIONS: Readonly<Record<string, string>> = {
+ get_stats: 'only with --by (grouped counts under the member filter); the plain brain-wide counters are refused',
+ remember: 'only one fact with --entity naming the exact slug of a page the member reads; --items, --visibility and --share are refused',
+ get_write_request: "only the member's own receipts (writes this mode accepted for it, recorded on this machine); any other id answers exactly as an unknown id",
+};
+
+/** Arguments of classified CLI-only commands the mode refuses. */
+export const CLI_ARGUMENT_CONDITIONS: Readonly<Record<string, string>> = {
+ recall: 'the facts arms (entity, --since, --question, --grep, --query) and the page arm; --pending, --supersessions, --session and --watch are refused',
+ 'git commit-push': 'named paths (each readable by the member, no label change, no access policy file), --dry-run and --pull; --pending, --push-only, --resolve and --allow-outside-source-root are refused; output withheld',
+ sync: 'output withheld; sync status is refused (it names held paths)',
+ 'sources refresh': 'output withheld; every other sources subcommand (status and writer status name held paths) is refused',
+ doctor: 'plain doctor or doctor --json only; output replaced by each check name and status and the count per status',
+};
+
+/** Every CLI-only command (src/cli/command-table.ts) by class; a command with mixed subcommands lists them. */
+export const CLI_COMMAND_CLASSES: Readonly<Record<string, EnforcedClass | EnforcedSubcommands>> = {
+ errors: 'allowed',
+ protocol: 'allowed',
+ sync: { default: 'allowed', sub: { status: 'refused' } },
+ sources: { default: 'refused', sub: { refresh: 'allowed' } },
+ git: { default: 'refused', sub: { 'commit-push': 'write' } },
+ recall: 'read',
+ hook: 'silent',
+ doctor: 'allowed',
+ ...Object.fromEntries([
+ 'schema', 'bundled-skill', 'skill-resolver', 'notices', 'init', 'bench', 'reinit-pglite', 'embeddings', 'pglite-repair',
+ 'engine', 'db-repair', 'auth', 'google', 'creds', 'remote', 'connect', 'setup', 'bootstrap', 'backup', 'upgrade',
+ 'post-upgrade', 'check-update', 'self-upgrade', 'integrations', 'providers', 'resolvers', 'integrity', 'publish',
+ 'check-backlinks', 'frontmatter', 'lint', 'check-resolvable', 'mounts', 'cache', 'routing-eval', 'skillify', 'skillpack',
+ 'friction', 'claw-test', 'report', 'apply-migrations', 'repair-jsonb', 'skillpack-check', 'compile-context',
+ 'smoke-test', 'dream', 'decide', 'facts', 'projections', 'append', 'capture', 'forget', 'call', 'mcp', 'import', 'access',
+ 'export', 'files', 'embed', 'serve', 'sweep', 'config', 'pricing', 'migrate', 'retrieval-upgrade', 'eval', 'jobs', 'agent',
+ 'book-mirror', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query',
+ 'reconcile-links', 'repair', 'diag', 'orphans', 'maintain', 'reindex', 'salience', 'anomalies', 'feedback', 'status',
+ 'advisor', 'conversation-parser', 'edges-backfill', 'whoknows', 'brainstorm', 'lsd', 'skillopt', 'calibration',
+ 'transcripts', 'models', 'takes', 'onboard', 'founder', 'think', 'notability-eval', 'waiting', 'loops',
+ 'questions', 'edge-proposals', 'memory-proposals', 'core', 'connectors', 'wakeshift', 'pages', 'quarantine', 'beliefs',
+ 'trust', 'watch', 'storage', 'code-def', 'code-refs', 'reindex-code', 'reindex-search-vector', 'reindex-frontmatter',
+ 'backfill', 'code-callers', 'code-callees', 'repos',
+ ].map(n => [n, 'refused' as const])),
+};
+
+/** Subcommands of operation-backed commands that run something other than the operation. */
+export const OPERATION_SUBCOMMANDS: Readonly<Record<string, EnforcedSubcommands>> = {
+ search: { default: 'read', sub: { modes: 'refused', stats: 'refused', tune: 'refused', diagnose: 'refused' } },
+};
+
+function subcommandClass(spec: EnforcedClass | EnforcedSubcommands, args: readonly string[]): EnforcedClass {
+ if (typeof spec === 'string') return spec;
+ const first = args.find(a => !a.startsWith('-'));
+ return (first !== undefined ? spec.sub[first] : undefined) ?? spec.default;
+}
+
+/** The class of a dispatched command: its CLI-only record, else the operation it names (by CLI name or alias). */
+export function enforcedClassOf(command: string, args: readonly string[], opName: string | undefined): EnforcedClass {
+ const cli = CLI_COMMAND_CLASSES[command];
+ if (cli !== undefined) return subcommandClass(cli, args);
+ const opClass = opName === undefined ? 'refused' : OPERATION_CLASSES[opName] ?? 'refused';
+ const sub = OPERATION_SUBCOMMANDS[command];
+ return sub && opClass !== 'refused' ? subcommandClass(sub, args) : opClass;
+}
diff --git a/src/cli/enforced-member.ts b/src/cli/enforced-member.ts
new file mode 100644
index 0000000000..acef2164ee
--- /dev/null
+++ b/src/cli/enforced-member.ts
@@ -0,0 +1,516 @@
+/**
+ * GST-2476 G2: enforced member mode. When GBRAIN_ENFORCED_MEMBER is set, the CLI acts as that member: the gate in
+ * src/cli/main.ts classifies the command (src/cli/enforced-member-classes.ts) before any other work, reads run as the
+ * in-process stdio MCP server bound to the member would answer them (remote: true, privacy always hidden, other
+ * members' personal sources out of scope), and writes stay trusted local writes that land exactly where they land
+ * without the mode, after the checks here refuse a target the member cannot read and every label change. The mode binds
+ * only a caller whose launcher pins the variable; unsetting it or opening the database directly is out of scope.
+ * Guide: docs/guides/enforced-member.md.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import type { CallerAccess } from '../core/search/private-visibility.ts';
+import { ACCESS_ID_RE } from '../core/access/principals.ts';
+import { opError } from '../core/ops/contract.ts';
+import { writeCliError } from './cli-error.ts';
+import { CLI_COMMAND_CLASSES, OPERATION_SUBCOMMANDS, enforcedClassOf, type EnforcedClass } from './enforced-member-classes.ts';
+
+export const ENFORCED_MEMBER_ENV = 'GBRAIN_ENFORCED_MEMBER';
+export const ENFORCED_REFUSED_TAG = 'GBRAIN_ENFORCED_REFUSED';
+export const ENFORCED_DOCS = 'docs/guides/enforced-member.md#refused';
+
+export type EnforcedReason = 'command_not_allowed' | 'member_not_usable' | 'target_not_readable' | 'label_change' | 'thin_client'
+ | 'as_flag' | 'arguments_not_allowed' | 'remember_needs_entity';
+
+const REASON_TEXT: Record<EnforcedReason, string> = {
+ command_not_allowed: 'This command is not on the enforced member allow-list.',
+ member_not_usable: 'The variable is empty or names no enabled member this mode can act as.',
+ target_not_readable: 'A page or source this command would write or read is outside what this member may read.',
+ label_change: 'This write would change an access or privacy label.',
+ thin_client: 'A thin client reads as its own credential, so it cannot act as one member.',
+ as_flag: '--as is refused under this mode.',
+ arguments_not_allowed: 'These arguments are not allowed under this mode.',
+ remember_needs_entity: 'remember needs --entity naming the exact slug of a page this member reads.',
+};
+
+/** The mode's member value, or undefined when the mode is off (the variable unset). */
+export function enforcedMemberValue(env: NodeJS.ProcessEnv = process.env): string | undefined {
+ return env[ENFORCED_MEMBER_ENV];
+}
+
+export function enforcedModeOn(env: NodeJS.ProcessEnv = process.env): boolean {
+ return enforcedMemberValue(env) !== undefined;
+}
+
+/** The value as printed: a well-formed member id as is, anything else never echoed. */
+export function enforcedMemberLabel(value = enforcedMemberValue() ?? ''): string {
+ return value === '' ? '' : ACCESS_ID_RE.test(value) ? value : '<invalid>';
+}
+
+function commandLabel(command: string): string {
+ return command.split(' ').every(part => /^[a-z0-9][a-z0-9_-]{0,63}$/.test(part)) ? command : '<command>';
+}
+
+/** The one constant stderr line every read-filtered command prints, whether or not anything was hidden. */
+export function filteredNotice(): string {
+ return 'gbrain: results limited to what GBRAIN_ENFORCED_MEMBER=' + enforcedMemberLabel() + ' may read\n';
+}
+
+let noticeWritten = false;
+
+/** Writes the constant line once per process (a read may dispatch more than once). */
+export function emitFilteredNotice(): void {
+ if (noticeWritten) return;
+ noticeWritten = true;
+ try { process.stderr.write(filteredNotice()); } catch { /* stderr gone */ }
+}
+
+/** A refusal whose first line says what to do instead of naming the command (the prefix and tag stay the same). */
+const REASON_HEADLINE: Partial<Record<EnforcedReason, string>> = {
+ remember_needs_entity: 'remember saves a fact only with --entity <slug of a page you can read>; nothing was saved',
+};
+
+const REASON_NEXT: Partial<Record<EnforcedReason, { fix: string; recovery: string }>> = {
+ remember_needs_entity: { fix: 'run the Retry command with --entity set to the exact slug of a page you can read.', recovery: 'nothing was saved, so retrying with --entity is safe.' },
+};
+
+const OWNER_FIX = 'ask the brain owner to run this in a direct session (one without ' + ENFORCED_MEMBER_ENV + ').';
+const NOTHING_CHANGED = 'do not retry here; nothing was changed.';
+
+/** The refusal's stderr text: the exact first line, the retry shape, the fix, the recovery and the docs anchor; no secret values. */
+export function refusalText(command: string, reason: EnforcedReason, retry?: string): string {
+ return ['gbrain: refused under ' + ENFORCED_MEMBER_ENV + '=' + enforcedMemberLabel() + ': ' + (REASON_HEADLINE[reason] ?? commandLabel(command)) + ' [' + ENFORCED_REFUSED_TAG + ']',
+ ...(retry ? ['Retry: ' + retry] : []),
+ 'Why: ' + REASON_TEXT[reason],
+ 'Fix: ' + (REASON_NEXT[reason]?.fix ?? OWNER_FIX),
+ 'Recovery: ' + (REASON_NEXT[reason]?.recovery ?? NOTHING_CHANGED),
+ 'Docs: ' + ENFORCED_DOCS, ''].join('\n');
+}
+
+export function enforcedRefusalError(command: string, reason: EnforcedReason) {
+ const next = REASON_NEXT[reason];
+ return opError('enforced_member_refused', 'Refused under ' + ENFORCED_MEMBER_ENV + ': ' + (REASON_HEADLINE[reason] ?? commandLabel(command)) + '. ' + REASON_TEXT[reason],
+ next ? next.recovery + ' Fix: ' + next.fix : 'Do not retry here; nothing was changed. Ask the brain owner to run it in a direct session.', { reason, docs: ENFORCED_DOCS });
+}
+
+/** Refuses and exits: the exact stderr text, and under --json the envelope on stdout; exit 3. */
+export async function refuseEnforced(command: string, reason: EnforcedReason, opts: { engine?: BrainEngine | null; retry?: string } = {}): Promise<never> {
+ try { process.stderr.write(refusalText(command, reason, opts.retry)); } catch { /* stderr gone */ }
+ const code = writeCliError(enforcedRefusalError(command, reason), command, { stderr: false });
+ const { finishCliTeardown, setCliExitVerdict, flushThenExit } = await import('../core/cli-force-exit.ts');
+ if (opts.engine) await finishCliTeardown({ engine: opts.engine }).catch(() => {});
+ setCliExitVerdict(code);
+ flushThenExit(code);
+ return await new Promise<never>(() => {});
+}
+
+/** The subcommand-qualified label of a mixed command (sources refresh, git commit-push), else the command. */
+export function enforcedCommandLabel(command: string, args: readonly string[]): string {
+ const spec = CLI_COMMAND_CLASSES[command] ?? OPERATION_SUBCOMMANDS[command];
+ const first = args.find(a => !a.startsWith('-'));
+ if (!spec || typeof spec === 'string' || !first || !/^[a-z][a-z-]*$/.test(first)) return command;
+ return spec.default === 'refused' || spec.sub[first] !== undefined ? command + ' ' + first : command;
+}
+
+export interface EnforcedGateInput {
+ command: string;
+ args: readonly string[];
+ opName: string | undefined;
+ helpRequested: boolean;
+ asFlag: boolean;
+ thinClient: boolean;
+}
+
+/**
+ * The gate: undefined when the mode is off; otherwise the command's class, after refusing (and exiting) anything
+ * refused or unclassified, --as, a thin client and an empty or ill-formed value. Help always prints (it is static).
+ * hook is answered here: nothing on stdout, the constant line on stderr, exit 0 (the one deliberate success).
+ */
+export async function enforcedGate(input: EnforcedGateInput): Promise<EnforcedClass | undefined> {
+ const value = enforcedMemberValue();
+ if (value === undefined) return undefined;
+ const label = enforcedCommandLabel(input.command, input.args);
+ if (input.helpRequested) return 'allowed';
+ if (input.asFlag) return refuseEnforced(label, 'as_flag');
+ const cls = enforcedClassOf(input.command, input.args, input.opName);
+ if (cls === 'silent') {
+ const { setCliExitVerdict, flushThenExit } = await import('../core/cli-force-exit.ts');
+ try { process.stderr.write(filteredNotice()); } catch { /* stderr gone */ }
+ setCliExitVerdict(0);
+ flushThenExit(0);
+ return await new Promise<never>(() => {});
+ }
+ if (cls === 'refused') return refuseEnforced(label, 'command_not_allowed');
+ if (cls === 'allowed' && (input.command === 'errors' || input.command === 'protocol')) return cls;
+ if (input.thinClient) return refuseEnforced(label, 'thin_client');
+ if (value === '' || !ACCESS_ID_RE.test(value)) return refuseEnforced(label, 'member_not_usable');
+ return cls;
+}
+
+export interface EnforcedAccess {
+ member: string;
+ access: Partial<CallerAccess> & { identity: string[]; satisfiedRuleIds: string[] };
+ /** Other members' personal sources: outside this member's reads and writes. */
+ hiddenSources: Set<string>;
+}
+
+const ACCESS_CACHE = new WeakMap<BrainEngine, EnforcedAccess>();
+
+/**
+ * The member's live read record, refusing (and exiting) when the value names no enabled member or names the owner
+ * (config access.owner_member). Never falls back to the trusted caller.
+ */
+export async function enforcedAccess(engine: BrainEngine, command: string): Promise<EnforcedAccess> {
+ const cached = ACCESS_CACHE.get(engine);
+ if (cached) return cached;
+ const member = enforcedMemberValue() ?? '';
+ let resolved: EnforcedAccess | null = null;
+ try {
+ if (member && ACCESS_ID_RE.test(member)) {
+ const [{ memberIdentity }, { ownerMemberId }, { remoteCallerAccess }, { hiddenPersonalSources }] = await Promise.all([
+ import('../core/access/members.ts'), import('../core/access/owner.ts'), import('../core/access/caller.ts'), import('../core/access/member-sources.ts')]);
+ const { member: id } = await memberIdentity(engine, member);
+ if (id === member && await ownerMemberId(engine) !== member) {
+ const base = await remoteCallerAccess(engine, undefined, [], 'stdio', null, member);
+ const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources');
+ resolved = {
+ member,
+ access: { ...base, identity: [...base.identity ?? []], satisfiedRuleIds: [...base.satisfiedRuleIds ?? []], hidePrivate: true, owner: false, privateReadableSources: [], applyRemoteReadPolicy: false },
+ hiddenSources: await hiddenPersonalSources(engine, sources.map(s => s.id), member, false),
+ };
+ }
+ }
+ } catch { resolved = null; }
+ if (!resolved) return refuseEnforced(command, 'member_not_usable', { engine });
+ ACCESS_CACHE.set(engine, resolved);
+ return resolved;
+}
+
+/** A read-class operation's own argument checks, before it runs: the member resolves, and get_stats only with --by. */
+export async function checkEnforcedReadArgs(engine: BrainEngine, command: string, opName: string, params: Record<string, unknown>): Promise<void> {
+ await enforcedAccess(engine, command);
+ if (opName === 'get_stats' && params.by === undefined) await refuseEnforced(command, 'arguments_not_allowed', { engine });
+}
+
+/**
+ * A classified CLI-only command under the mode. recall reads through the member filter inside its own handler
+ * (commands/recall.ts); sync, sources refresh, git commit-push and doctor validate the member (and commit-push its
+ * paths) on a short probe connection, then run with their output withheld (doctor: names, statuses and counts only).
+ */
+export async function runEnforcedCliOnly(command: string, subArgs: string[], deps: {
+ handleCliOnly: (command: string, args: string[]) => Promise<void>;
+ connectEngine: () => Promise<BrainEngine>;
+}): Promise<void> {
+ const label = enforcedCommandLabel(command, subArgs);
+ if (command === 'recall') {
+ if (['--pending', '--supersessions', '--session', '--watch'].some(f => subArgs.some(a => a === f || a.startsWith(f + '=')))) await refuseEnforced(label, 'arguments_not_allowed');
+ return deps.handleCliOnly(command, subArgs);
+ }
+ if (command === 'doctor' && subArgs.some(a => a !== '--json')) await refuseEnforced(label, 'arguments_not_allowed');
+ const probe = await deps.connectEngine();
+ try {
+ await enforcedAccess(probe, label);
+ if (command === 'git') await (await import('./enforced-commit-push.ts')).checkEnforcedCommitPush(probe, subArgs);
+ } finally {
+ await probe.disconnect().catch(() => {});
+ }
+ if (command === 'doctor') return withDoctorCounts(subArgs.includes('--json'), () => deps.handleCliOnly('doctor', ['--json']));
+ await withWithheldOutput(label, () => deps.handleCliOnly(command, subArgs));
+}
+
+export interface EnforcedScope { sourceId?: string; localFederatedSourceIds?: string[]; config?: import('../core/config.ts').GBrainConfig }
+
+/**
+ * A read answered as the in-process stdio MCP server bound to the member would answer it, unpacked to the operation's
+ * result (or its error, rethrown as an OperationError). The scope is the CLI's own source resolution minus other
+ * members' personal sources; a resolved source that is one of them refuses.
+ */
+export async function enforcedRead(engine: BrainEngine, command: string, opName: string, params: Record<string, unknown>, scope: EnforcedScope): Promise<unknown> {
+ const { hiddenSources, member } = await enforcedAccess(engine, command);
+ if (scope.sourceId && hiddenSources.has(scope.sourceId)) return refuseEnforced(command, 'target_not_readable', { engine });
+ emitFilteredNotice();
+ const federated = scope.localFederatedSourceIds?.filter(s => !hiddenSources.has(s));
+ const { dispatchToolCall } = await import('../mcp/dispatch.ts');
+ const out = await dispatchToolCall(engine, opName, params, {
+ remote: true, transport: 'stdio', stdioMember: member, enforcedMember: true, admissionOrigin: 'interactive',
+ takesHoldersAllowList: ['world'],
+ ...(scope.config ? { config: scope.config } : {}),
+ ...(scope.sourceId ? { sourceId: scope.sourceId } : {}),
+ ...(federated ? { localFederatedSourceIds: federated } : {}),
+ });
+ const text = out.content?.[0]?.text ?? '';
+ let parsed: unknown;
+ try { parsed = JSON.parse(text); } catch { parsed = text; }
+ if (out.isError) {
+ const { reviveOperationError } = await import('../core/cli-socket/protocol.ts');
+ const env = (parsed && typeof parsed === 'object' ? parsed : {}) as Record<string, unknown>;
+ throw reviveOperationError({ code: env.code ?? env.error ?? 'internal_error', message: env.message ?? text, ...(typeof env.suggestion === 'string' ? { suggestion: env.suggestion } : {}),
+ ...(typeof env.docs === 'string' ? { docs: env.docs } : {}), ...(env.reason ? { reason: env.reason } : {}) });
+ }
+ return parsed;
+}
+
+type PageView = 'readable' | 'hidden' | 'missing';
+
+/** Whether the member reads a page: an existing row under the member's full read policy, a new slug under the folder rules it would sit under. */
+export async function memberPageView(engine: BrainEngine, ea: EnforcedAccess, sourceId: string, slug: string): Promise<PageView> {
+ if (ea.hiddenSources.has(sourceId)) return 'hidden';
+ const { withCallerAccess, readPolicyFragment, folderRulesAllowedSql } = await import('../core/search/private-visibility.ts');
+ const { access } = ea;
+ let view: PageView = 'missing';
+ for (const candidate of [...new Set([slug, slug.toLowerCase()])]) {
+ const policy = withCallerAccess(access, () => readPolicyFragment('p', access.identity, true, access.satisfiedRuleIds));
+ const [row] = await engine.executeRaw<{ ok: boolean }>('SELECT (' + policy + ') AS ok FROM pages p WHERE p.source_id = $1 AND p.slug = $2 LIMIT 1', [sourceId, candidate]);
+ if (row) { if (!row.ok) return 'hidden'; view = 'readable'; continue; }
+ const folder = withCallerAccess(access, () => folderRulesAllowedSql('p', access.satisfiedRuleIds));
+ const [rule] = await engine.executeRaw<{ ok: boolean }>('SELECT (' + folder + ') AS ok FROM (SELECT $1::text AS source_id, $2::text AS slug, gbrain_access_folder_rules($1, $2) AS folder_rule_ids) p', [sourceId, candidate]);
+ if (!rule?.ok) return 'hidden';
+ }
+ return view;
+}
+
+const LABEL_KEYS = ['visibility', 'readable_by', 'access', 'confidentiality', 'pinned_question', 'derived_from'] as const;
+const LABEL_TEXT_RE = /readable_by|visibility|confidentiality|pinned_question|derived_from|\bprivate\b|^\s*(access|type)\s*:|<!--\s*gbrain:|^\s*---\s*$/im;
+
+/** The protected-fence text a remote reader never sees (private fact rows and takes), which the member cannot change. */
+async function hiddenResidue(body: string | null | undefined): Promise<string> {
+ if (!body) return '';
+ const [{ PROTECTED_PAIRS, renderFactsRegion }, { protectedRegions }, { sanitizeText }] = await Promise.all([
+ import('../core/remote-body.ts'), import('../core/fence-scan.ts'), import('../core/batch-rows.ts')]);
+ const text = sanitizeText(body);
+ const { regions, truncatedAt } = protectedRegions(text, PROTECTED_PAIRS);
+ const out = regions.filter(r => r.pair !== 0 || renderFactsRegion(text.slice(r.start, r.end), true) !== text.slice(r.start, r.end)).map(r => text.slice(r.start, r.end));
+ if (truncatedAt !== -1) out.push(text.slice(truncatedAt));
+ return out.join('\u0000');
+}
+
+/** Every access and privacy label of a page: label keys, normalised readers, derived privacy, and its hidden fence text. */
+async function pageLabels(page: { type?: string | null; frontmatter?: unknown; compiled_truth?: string | null; timeline?: string | null } | null): Promise<string> {
+ const { isPrivacyPrivatePage } = await import('../core/search/private-visibility.ts');
+ const { hasReaders, normalizeReaders } = await import('../core/access/principals.ts');
+ const fm = (page?.frontmatter && typeof page.frontmatter === 'object' ? page.frontmatter : {}) as Record<string, unknown>;
+ return JSON.stringify({
+ private: page ? isPrivacyPrivatePage({ type: page.type ?? null, frontmatter: fm }) : false,
+ readers: hasReaders(fm) ? normalizeReaders(fm) ?? '!invalid' : null,
+ keys: LABEL_KEYS.map(k => fm[k] ?? null),
+ residue: [await hiddenResidue(page?.compiled_truth), await hiddenResidue(page?.timeline)],
+ });
+}
+
+/** The labels of markdown content (a put, or a file in a commit), or of no page at all for null. */
+export async function markdownLabels(content: string | null, slug: string): Promise<string> {
+ if (content === null) return pageLabels(null);
+ const { parseMarkdown } = await import('../core/markdown.ts');
+ const parsed = parseMarkdown(content, slug + '.md');
+ return pageLabels({ type: parsed.type, frontmatter: parsed.frontmatter, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline });
+}
+
+/** The stored page a label check compares against; a segmented page (no body string) refuses, so the check never reads an empty body as no labels. */
+async function storedPage(engine: BrainEngine, sourceId: string, slug: string) {
+ const [row] = await engine.executeRaw<{ type: string | null; frontmatter: unknown; compiled_truth: string | null; timeline: string | null; body_storage: 'inline' | 'segmented' | null; body_bytes: number | null }>(
+ 'SELECT type, frontmatter, compiled_truth, timeline, body_storage, body_bytes FROM pages WHERE source_id = $1 AND slug = $2 LIMIT 1', [sourceId, slug.toLowerCase()]);
+ if (row) (await import('../core/page-body/page-shape.ts')).assertInlineBody({ ...row, slug, source_id: sourceId }, 'enforced_member_label_check');
+ return row ? { ...row, frontmatter: typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter } : null;
+}
+
+/** The page targets of each write-checked operation. */
+function writeTargets(opName: string, p: Record<string, unknown>): string[] {
+ const s = (v: unknown) => (typeof v === 'string' ? [v] : []);
+ return opName === 'add_link' || opName === 'remove_link' ? [...s(p.from), ...s(p.to)] : s(p.slug);
+}
+
+/**
+ * The checks a write-checked operation passes before it runs as a trusted local write: its source and every target page
+ * readable by the member, and no label change. remember: one fact on --entity, the exact slug of a page the member reads,
+ * nothing inferred and no visibility or share label (params.infer_entity is set to false).
+ */
+export async function checkEnforcedWrite(engine: BrainEngine, command: string, opName: string, params: Record<string, unknown>, sourceId: string | undefined): Promise<void> {
+ const ea = await enforcedAccess(engine, command);
+ const source = typeof params.source_id === 'string' && params.source_id ? params.source_id : sourceId ?? 'default';
+ if (ea.hiddenSources.has(source)) return refuseEnforced(command, 'target_not_readable', { engine });
+ if (opName === 'remember') return checkEnforcedRemember(engine, command, ea, source, params);
+ if (opName === 'get_write_request') {
+ if (!await ownEnforcedReceipt(params.request_id)) params.request_id = (await import('node:crypto')).randomUUID();
+ return;
+ }
+ for (const slug of writeTargets(opName, params)) {
+ if (await memberPageView(engine, ea, source, slug) === 'hidden') return refuseEnforced(command, 'target_not_readable', { engine });
+ }
+ const slug = String(params.slug ?? '');
+ if (opName === 'put_page') {
+ const content = typeof params.content === 'string' ? params.content : '';
+ if (await pageLabels(await storedPage(engine, source, slug)) !== await markdownLabels(content, slug)) return refuseEnforced(command, 'label_change', { engine });
+ }
+ if (opName === 'edit_page' || opName === 'append_page') {
+ const texts = opName === 'append_page' ? [params.text] : (Array.isArray(params.edits) ? params.edits as Record<string, unknown>[] : []).flatMap(e => [e?.old_text, e?.new_text]);
+ const stored = await storedPage(engine, source, slug);
+ const hidden = stored ? await hiddenResidue(stored.compiled_truth) + await hiddenResidue(stored.timeline) : '';
+ if (hidden !== '' || texts.some(t => typeof t === 'string' && LABEL_TEXT_RE.test(t))) return refuseEnforced(command, 'label_change', { engine });
+ }
+}
+
+export const REMEMBER_RETRY = 'gbrain remember "<one fact>" --entity <exact slug of a page you can read, from gbrain find or gbrain search> --provenance "<where you learned it>"';
+
+/**
+ * Where a remember may save under the mode, decided here and nowhere else: one fact on --entity, the exact slug of a
+ * page the member reads, nothing inferred (params.infer_entity is set to false) and no visibility or share label.
+ * Anything else refuses with the retry shape. A later no-entity form would be one branch here.
+ */
+async function checkEnforcedRemember(engine: BrainEngine, command: string, ea: EnforcedAccess, source: string, params: Record<string, unknown>): Promise<void> {
+ if (params.items !== undefined || params.visibility !== undefined || params.share !== undefined) return refuseEnforced(command, 'arguments_not_allowed', { engine });
+ const entity = typeof params.entity === 'string' ? params.entity.trim() : '';
+ if (!entity || entity !== entity.toLowerCase() || /\s/.test(entity) || await memberPageView(engine, ea, source, entity) !== 'readable') {
+ return refuseEnforced(command, 'remember_needs_entity', { engine, retry: REMEMBER_RETRY });
+ }
+ params.infer_entity = false;
+}
+
+const RECEIPT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const RECEIPT_LEDGER_MAX = 2000;
+
+/** The member's receipt ledger: the request ids of writes this mode accepted for it, one per line, on this machine. */
+async function receiptLedgerPath(): Promise<string> {
+ const [{ join }, { configDir }] = await Promise.all([import('node:path'), import('../core/config.ts')]);
+ return join(configDir(), 'enforced-member', enforcedMemberLabel() + '.receipts');
+}
+
+/**
+ * Records the request ids an accepted write under the mode returned (its result, or the pending receipt on its error),
+ * so gbrain write-request can answer the member's own receipts and nothing else. A failed record only makes the
+ * receipt answer as unknown.
+ */
+export async function recordEnforcedReceipts(opName: string, value: unknown, params: Record<string, unknown>): Promise<void> {
+ if (opName === 'get_write_request') return;
+ const ids = new Set<string>();
+ const add = (v: unknown) => { if (typeof v === 'string' && RECEIPT_ID_RE.test(v.trim().toLowerCase())) ids.add(v.trim().toLowerCase()); };
+ const obj = (v: unknown) => (v && typeof v === 'object' ? v as Record<string, unknown> : {});
+ add(obj(value).request_id); add(obj(obj(value).write_request).request_id); add(obj(obj(value).writeRequest).request_id);
+ if (ids.size) add(params.request_id);
+ if (!ids.size) return;
+ try {
+ const fs = await import('node:fs');
+ const path = await receiptLedgerPath();
+ fs.mkdirSync((await import('node:path')).dirname(path), { recursive: true, mode: 0o700 });
+ const kept = fs.existsSync(path) ? fs.readFileSync(path, 'utf8').split('\n').filter(Boolean).slice(-(RECEIPT_LEDGER_MAX - ids.size)) : [];
+ fs.writeFileSync(path, [...kept, ...ids].join('\n') + '\n', { mode: 0o600 });
+ } catch { /* unrecorded: the receipt answers as unknown */ }
+}
+
+async function ownEnforcedReceipt(id: unknown): Promise<boolean> {
+ if (typeof id !== 'string' || !RECEIPT_ID_RE.test(id.trim().toLowerCase())) return false;
+ try {
+ const text = (await import('node:fs')).readFileSync(await receiptLedgerPath(), 'utf8');
+ return text.split('\n').includes(id.trim().toLowerCase());
+ } catch { return false; }
+}
+
+/**
+ * Output guard (defense in depth): true when any whole string in result is the slug of a page the member cannot read
+ * and no page it reads carries the same slug. The caller then withholds the whole output.
+ */
+export async function namesHiddenPage(engine: BrainEngine, command: string, result: unknown): Promise<boolean> {
+ const strings = new Set<string>();
+ const walk = (v: unknown, depth: number): void => {
+ if (depth > 12 || strings.size > 5000) return;
+ if (typeof v === 'string') { if (v.length > 0 && v.length <= 255 && !/\s/.test(v)) strings.add(v.toLowerCase()); return; }
+ if (Array.isArray(v)) { for (const x of v) walk(x, depth + 1); return; }
+ if (v && typeof v === 'object') for (const x of Object.values(v as Record<string, unknown>)) walk(x, depth + 1);
+ };
+ walk(result, 0);
+ if (!strings.size) return false;
+ const ea = await enforcedAccess(engine, command);
+ const { withCallerAccess, readPolicyFragment } = await import('../core/search/private-visibility.ts');
+ const policy = withCallerAccess(ea.access, () => readPolicyFragment('p', ea.access.identity, true, ea.access.satisfiedRuleIds));
+ const hidden = ea.hiddenSources.size ? '(NOT (' + policy + ') OR p.source_id = ANY($2::text[]))' : 'NOT (' + policy + ')';
+ const rows = await engine.executeRaw<{ slug: string; hidden: boolean }>('SELECT p.slug, ' + hidden + ' AS hidden FROM pages p WHERE p.slug = ANY($1::text[])',
+ ea.hiddenSources.size ? [[...strings], [...ea.hiddenSources]] : [[...strings]]);
+ const visible = new Set(rows.filter(r => !r.hidden).map(r => r.slug));
+ return rows.some(r => r.hidden && !visible.has(r.slug));
+}
+
+export const WITHHELD_LINE = (command: string) => 'gbrain: ' + commandLabel(command) + ' finished; its output is withheld under ' + ENFORCED_MEMBER_ENV + '\n';
+
+/**
+ * Runs an allowed operation (sync, sources refresh, git commit-push) with stdout and stderr withheld: it prints one
+ * constant line, plus the bare error code (never a path or slug) on failure, and keeps the exit code.
+ */
+async function captureOutput(run: () => Promise<void>): Promise<{ stdout: string; all: string; exit: number }> {
+ const { currentExitCode, setCliExitVerdict, setStdoutCapture } = await import('../core/cli-force-exit.ts');
+ const all: string[] = [];
+ const stdout: string[] = [];
+ const stdoutWrite = process.stdout.write;
+ const stderrWrite = process.stderr.write;
+ const consoleFns = { log: console.log, info: console.info, warn: console.warn, error: console.error, debug: console.debug };
+ const swallow = (toStdout: boolean) => ((chunk: unknown, ...rest: unknown[]) => {
+ const text = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
+ all.push(text);
+ if (toStdout) stdout.push(text);
+ const cb = rest.find(r => typeof r === 'function') as (() => void) | undefined;
+ if (cb) cb();
+ return true;
+ }) as typeof process.stdout.write;
+ const swallowConsole = (toStdout: boolean) => (...args: unknown[]) => {
+ const text = args.map(String).join(' ') + '\n';
+ all.push(text);
+ if (toStdout) stdout.push(text);
+ };
+ setStdoutCapture(text => { all.push(text); stdout.push(text); });
+ process.stdout.write = swallow(true);
+ process.stderr.write = swallow(false);
+ console.log = console.info = swallowConsole(true);
+ console.warn = console.error = console.debug = swallowConsole(false);
+ let failed = false;
+ try {
+ await run();
+ } catch (e) {
+ failed = true;
+ const code = (e as { code?: unknown })?.code;
+ if (typeof code === 'string') all.push('Error [' + code + ']');
+ } finally {
+ setStdoutCapture(null);
+ process.stdout.write = stdoutWrite;
+ process.stderr.write = stderrWrite;
+ Object.assign(console, consoleFns);
+ }
+ const exit = failed && currentExitCode() === 0 ? 1 : currentExitCode();
+ if (failed) setCliExitVerdict(exit);
+ return { stdout: stdout.join(''), all: all.join(''), exit };
+}
+
+function withheldFailureLine(command: string, text: string, exit: number): string {
+ const code = /Error \[([a-z0-9_]+)\]/.exec(text)?.[1] ?? /"code"\s*:\s*"([a-z0-9_]+)"/.exec(text)?.[1];
+ return 'gbrain: ' + commandLabel(command) + ' failed' + (code ? ' [' + code + ']' : '') + ' (exit ' + exit + '); its output is withheld under ' + ENFORCED_MEMBER_ENV + '\n';
+}
+
+export async function withWithheldOutput(command: string, run: () => Promise<void>): Promise<void> {
+ const out = await captureOutput(run);
+ process.stderr.write(out.exit === 0 ? WITHHELD_LINE(command) : withheldFailureLine(command, out.all, out.exit));
+}
+
+export const DOCTOR_COUNTS_LINE = 'gbrain: doctor shows check names, statuses and counts only under ' + ENFORCED_MEMBER_ENV + '\n';
+
+/**
+ * doctor under the mode: runs doctor --json with its output captured and prints only each check's name and status and
+ * the count per status (no message, detail, fix, slug, path, title or source name). A name or status outside
+ * [a-z0-9_] prints as "other". Keeps doctor's exit code.
+ */
+export async function withDoctorCounts(json: boolean, run: () => Promise<void>): Promise<void> {
+ const out = await captureOutput(run);
+ let report: Record<string, unknown> = {};
+ try { report = JSON.parse(out.stdout.slice(out.stdout.indexOf('{'), out.stdout.lastIndexOf('}') + 1)) as Record<string, unknown>; } catch { /* no report */ }
+ const checks = Array.isArray(report.checks) ? report.checks as Record<string, unknown>[] : [];
+ if (!checks.length) {
+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');
+ const exit = out.exit === 0 ? 1 : out.exit;
+ setCliExitVerdict(exit);
+ process.stderr.write(withheldFailureLine('doctor', out.all, exit));
+ return;
+ }
+ const safe = (v: unknown) => (typeof v === 'string' && /^[a-z0-9_]{1,64}$/.test(v) ? v : 'other');
+ const rows = checks.map(c => ({ name: safe(c.name), status: safe(c.status) }));
+ const counts: Record<string, number> = {};
+ for (const r of rows) counts[r.status] = (counts[r.status] ?? 0) + 1;
+ const summary = { status: safe(report.status), checks: rows, counts };
+ await (await import('../core/cli-force-exit.ts')).writeStdoutFinal(json ? JSON.stringify(summary, null, 2) + '\n'
+ : rows.map(r => r.status + ' ' + r.name).join('\n') + '\n' + Object.entries(counts).map(([k, v]) => k + ': ' + v).join(', ') + '\n');
+ process.stderr.write(DOCTOR_COUNTS_LINE);
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index fb62cdde70..46eea47ceb 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -337,6 +337,16 @@ async function main() {
return;
}
+ // GST-2476 G2: enforced member mode decides first; nothing below runs for a refused command (cli/enforced-member.ts).
+ if (process.env.GBRAIN_ENFORCED_MEMBER !== undefined) {
+ const routedForGate = routeCommand(command === 'ask' ? 'query' : command, args.slice(1));
+ const gateMeta = CLI_ONLY.has(routedForGate.command) ? undefined : cliOps.get(routedForGate.command) ?? cliAliases.get(routedForGate.command);
+ enforcedClass = await (await import('./enforced-member.ts')).enforcedGate({
+ command: routedForGate.command, args: routedForGate.subArgs, opName: gateMeta?.name,
+ helpRequested: cliHelpRequested(command, args.slice(1)), asFlag: cliOpts.as !== undefined, thinClient: isThinClient(loadConfig()),
+ });
+ }
+
if (command === '--tools-json') {
const { printToolsJson } = await import('../commands/tools-json.ts');
await printToolsJson();
@@ -529,8 +539,12 @@ async function main() {
return;
}
- if (cliOpts.as === undefined && ['search', 'query', 'get', 'recall'].includes(command) && await (await import('./cli-socket-client.ts')).maybeServeFromCliSocket(command, subArgs)) return; // warm serve socket (opt-in)
+ if (cliOpts.as === undefined && !enforcedClass && ['search', 'query', 'get', 'recall'].includes(command) && await (await import('./cli-socket-client.ts')).maybeServeFromCliSocket(command, subArgs)) return; // warm serve socket (opt-in)
// CLI-only commands
+ if (CLI_ONLY.has(command) && enforcedClass && !helpRequested && command !== 'errors' && command !== 'protocol') {
+ await (await import('./enforced-member.ts')).runEnforcedCliOnly(command, subArgs, { handleCliOnly, connectEngine });
+ return;
+ }
if (CLI_ONLY.has(command)) {
const endRead = (await import('./slow-read.ts')).beginCommandRead(command, subArgs); try { await handleCliOnly(command, subArgs); } finally { endRead(); }
return;
@@ -539,6 +553,9 @@ async function main() {
await runSharedOperation(command, subArgs, cliOpts);
}
+/** GST-2476 G2: the gate's class for this invocation; undefined when GBRAIN_ENFORCED_MEMBER is unset. */
+let enforcedClass: import('./enforced-member-classes.ts').EnforcedClass | undefined;
+
/**
* Shared-operation dispatch (every non-CLI_ONLY command and alias): parse the
* op's args, route thin clients over MCP, delegate to a live PGLite owner, or
@@ -637,7 +654,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// The live PGLite owner exposes canonical operations over a dedicated
// local socket. Delegate before opening a competing engine connection.
- if (cliOpts.as === undefined) { // GBRA-218: a --as preview runs in this process (the owner socket carries no member identity)
+ if (cliOpts.as === undefined && !enforcedClass) { // GBRA-218: a --as preview runs in this process (the owner socket carries no member identity); G2: so does an enforced member
const { runDelegatedCliOperation } = await import('../commands/persistence-delegate.ts');
if (await runDelegatedCliOperation(op.name, params, cfgPre, {
brain: cliOpts.brain, timeoutMs: cliOpts.timeoutMs ?? undefined,
@@ -668,6 +685,9 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
const READ_OP_TIMEOUT_MS = 180_000;
const configSnapshot = op.scope === 'read' ? takeStartupConfigSnapshot(engine) ?? openRequestConfigSnapshot(engine) : null;
const asPreview = await (await import('./as-preview.ts')).openAsPreview(engine, cliOpts.as, command); // GBRA-218 local --as <member>
+ // GST-2476 G2: an enforced read runs as the member's stdio server would answer it; an enforced write is checked first.
+ const enforced = enforcedClass ? await import('./enforced-member.ts') : null;
+ if (enforced && enforcedClass === 'read') await enforced.checkEnforcedReadArgs(engine, command, op.name, params);
try {
const { withTimeout, OperationTimeoutError } = await import('../core/timeout.ts');
@@ -703,7 +723,21 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
}
let rawResult: unknown;
- if (op.scope === 'read') {
+ const enforcedReadOf = enforced && enforcedClass === 'read'
+ ? (p: Record<string, unknown>) => enforced.enforcedRead(engine, command, op.name, p, { sourceId: ctx.sourceId, localFederatedSourceIds: ctx.localFederatedSourceIds, config: ctx.config })
+ : null;
+ if (enforced && enforcedClass === 'write') await enforced.checkEnforcedWrite(engine, command, op.name, params, ctx.sourceId);
+ if (enforcedReadOf) {
+ try {
+ rawResult = await withTimeout(enforcedReadOf(params), wallclockMs, `gbrain ${command}`);
+ } catch (e: unknown) {
+ if (e instanceof OperationTimeoutError) {
+ onWallclockTimeout(e);
+ return;
+ }
+ throw e;
+ }
+ } else if (op.scope === 'read') {
try {
rawResult = await withTimeout(
configSnapshot!.run(() => withRequestIdentityMemo(() => asPreview.run(() => op.handler(ctx, params)))).catch(async (e: unknown) => { // large pages: a segmented page streams to stdout
@@ -725,6 +759,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
} else {
rawResult = await withRequestIdentityMemo(() => asPreview.run(() => op.handler(ctx, params)));
if (op.mutating) await captureCapacityNotices(engine); // #6696 (A4)
+ if (enforced && enforcedClass === 'write') await enforced.recordEnforcedReceipts(op.name, rawResult, params);
}
if (op.name === 'get_page' && rawResult === (await import('./page-render.ts')).SEGMENTED_STREAMED) return;
captureRetrievalNotices(op.name, rawResult, lastRetrievalMeta, params, ctx.config);
@@ -733,7 +768,11 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// routed path. Date → ISO string; bigint → string (postgres.js shape);
// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
const { result, stderr: noticeText } = applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true, { op: op.name, retrieval: lastRetrievalMeta });
- const paged = op.name === 'get_page' && await (await import('./page-render.ts')).finishAsOfRead(async p => normalizeLocalResult(await op.handler(ctx, p)) as Record<string, any>, result as Record<string, any>, params, writeStdoutFinal); // GBRA-217
+ if (enforced && await enforced.namesHiddenPage(engine, command, result)) {
+ process.stderr.write(enforced.WITHHELD_LINE(command));
+ return;
+ }
+ const paged = op.name === 'get_page' && await (await import('./page-render.ts')).finishAsOfRead(async p => normalizeLocalResult(enforcedReadOf ? await enforcedReadOf(p) : await op.handler(ctx, p)) as Record<string, any>, result as Record<string, any>, params, writeStdoutFinal); // GBRA-217
const output = paged ? '' : formatResult(op.name, result, params);
// Awaited delivery (#3423): queued stdout writes past 64KiB lose their
// tail to a slow pipe reader when the exit grace lapses — see
@@ -752,6 +791,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// bounds a hung one.
// #5232: the reporter owns the write verdict; never overwrite it.
const { reportPersistenceCliError } = await import('../commands/persistence-delegate.ts');
+ if (enforced && enforcedClass === 'write' && e instanceof OperationError && e.writeRequest) await enforced.recordEnforcedReceipts(op.name, e.writeRequest, params);
const receipt = !(e instanceof OperationError) || !!e.writeRequest;
if (!receipt || !await reportPersistenceCliError(e, params.json === true || !!(e as OperationError)?.writeRequest)) {
setCliExitVerdict(writeCliError(e, command));
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index 62d7183518..d1d6a7bf92 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -504,6 +504,11 @@ async function recallVerbResult(engine: BrainEngine, flags: ParsedFlags, sourceI
} : {}),
};
const stamped = (result: RecallVerbResult, stamp: RecallVerbResult['degraded'] | null): RecallVerbResult => (stamp ? { ...result, degraded: stamp } : result);
+ if (process.env.GBRAIN_ENFORCED_MEMBER !== undefined) { // GST-2476 G2: read as the enforced member's stdio server would answer
+ const { enforcedRead } = await import('../cli/enforced-member.ts');
+ const result = await enforcedRead(engine, 'recall', 'recall', params, { sourceId: ctx.sourceId, config: ctx.config }) as RecallVerbResult;
+ return stamped(result, degradedStampFor('recall', result, null, []));
+ }
if (!oneShot || !isThinClient(ctx.config)) {
const result = await op.handler(ctx, params) as RecallVerbResult;
return stamped(result, degradedStampFor('recall', result, { retrieval }, notices));
@@ -708,14 +713,19 @@ async function runRecallOnce(
const resolvedSince: Date | null = cursor ? cursor.since : flags.since;
// #6945: only the local cursor read can page (oldest first, by keyset);
// thin-client and --supersessions keep the newest-N window.
- const pageable = cursor !== null && !thinClient && !flags.supersessions;
+ const enforced = process.env.GBRAIN_ENFORCED_MEMBER !== undefined; // GST-2476 G2: the remote arm, answered in process as the member
+ const pageable = cursor !== null && !thinClient && !enforced && !flags.supersessions;
let rows: FactRow[];
let pendingCount: number | undefined;
- if (thinClient) {
+ if (thinClient || enforced) {
const cfg = loadConfig();
const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
+ const { enforcedRead } = await import('../cli/enforced-member.ts');
+ const fetchRecall = async <T>(p: Record<string, unknown>): Promise<T> => (enforced
+ ? await enforcedRead(engine, 'recall', 'recall', p, { sourceId }) as T
+ : unpackToolResult<T>(await callRemoteTool(cfg!, 'recall', p, { timeoutMs: 30_000 })));
const params: Record<string, unknown> = {
limit: flags.limit,
include_expired: flags.includeExpired,
@@ -732,12 +742,11 @@ async function runRecallOnce(
// explicit `--source default` silently queried a different source.
if (sourceId !== 'default' || flags.sourceExplicit) params.source_id = sourceId;
- const raw = await callRemoteTool(cfg!, 'recall', params, { timeoutMs: 30_000 });
- const unpacked = unpackToolResult<{
+ const unpacked = await fetchRecall<{
facts: Array<Record<string, unknown>>;
total: number;
pending_consolidation_count?: number;
- }>(raw);
+ }>(params);
rows = unpacked.facts.map(remoteFactToRow);
pendingCount = unpacked.pending_consolidation_count;
@@ -748,12 +757,11 @@ async function runRecallOnce(
if (entityTextFallbackApplies(flags, rows.length)) {
const fbParams: Record<string, unknown> = { ...params, grep: flags.entity!.toLowerCase() };
delete fbParams.entity;
- const fbRaw = await callRemoteTool(cfg!, 'recall', fbParams, { timeoutMs: 30_000 });
- const fb = unpackToolResult<{
+ const fb = await fetchRecall<{
facts: Array<Record<string, unknown>>;
total: number;
pending_consolidation_count?: number;
- }>(fbRaw);
+ }>(fbParams);
if (fb.facts.length > 0) {
noteEntityTextFallback(flags.entity!, fb.facts.length);
rows = fb.facts.map(remoteFactToRow);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 2e39a28afa..eb81c30038 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -105,7 +105,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],
- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--as', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--as', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--include-cross-entity', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--as', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index e4697b204d..64198db7dc 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -724,7 +724,18 @@ export function drainStdoutQueueSync(deadlineMs: number = resolveStdoutDrainDead
* (EAGAIN mid-payload) or a prior in-flight write defers to the async tail,
* preserving order.
*/
+let stdoutCapture: ((text: string) => void) | null = null;
+
+/** GST-2476 G2: while set, every fd-1 write this module makes goes to the capture instead (enforced member mode withholds an allowed command's output). */
+export function setStdoutCapture(capture: ((text: string) => void) | null): void {
+ stdoutCapture = capture;
+}
+
function chainStdoutWrite(data: string | Uint8Array, encoding?: BufferEncoding): Promise<void> {
+ if (stdoutCapture) {
+ stdoutCapture(typeof data === 'string' ? data : Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('utf8'));
+ return Promise.resolve();
+ }
const buf =
typeof data === 'string'
? Buffer.from(data, encoding ?? 'utf8')
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2a82cc6782..3b2ec44823 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -312,6 +312,7 @@ export const CODES = {
embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },
embedding_width_mismatch: { class: 'caller', summary: "The embedding model cannot produce the width of the brain's vector column; nothing was changed." },
embedded_core_required: { class: 'caller', summary: "openEngine (gbrain/engine-open) was called without embedded_core: true, so no engine was opened.", why: 'Opening an engine from settings alone is an experimental embedding surface that is off by default; a host opts in explicitly so no existing caller changes behavior.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Pass embedded_core: true in the settings; the CLI, gbrain serve and mounts open brains through their own connect path and need nothing.' },
+ enforced_member_refused: { class: 'consent', exit: 3, actor: 'user', reasons: ['command_not_allowed', 'member_not_usable', 'target_not_readable', 'label_change', 'thin_client', 'as_flag', 'arguments_not_allowed', 'remember_needs_entity'], summary: "The CLI runs under GBRAIN_ENFORCED_MEMBER and refused the command before it read or changed anything: the command or its arguments are not on the enforced member allow-list, the variable names no usable member, a target page or source is outside what the member reads, or the write would change an access or privacy label.", why: 'A launcher pins GBRAIN_ENFORCED_MEMBER so a shared agent turn acts as one member: reads show only what that member reads, writes never touch a page it cannot read or change a label, and anything not classified is refused rather than run as the trusted owner. Stderr starts with gbrain: refused under GBRAIN_ENFORCED_MEMBER=<member>: <command> [GBRAIN_ENFORCED_REFUSED].', docs: 'docs/guides/enforced-member.md#refused', suggestion: 'Do not retry here; nothing was changed. Ask the brain owner to run the command in a direct session, one without GBRAIN_ENFORCED_MEMBER.' },
engine_embedding_mismatch: { class: 'host_only', actor: 'user', summary: "An engine opened from settings names an embedding model or width that differs from the one its database already records, so initSchema changed nothing.", why: 'The vector column has one width and the brain one embedding model; seeding another over it would make every stored and future embedding unreadable. Changing it is an explicit re-embed the user decides on.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: "Pass the database's recorded model and width in settings.embedding, or read the recorded identity with gbrain migrate embeddings --status on the brain host and preview a migration from there.", fix: { argv: ['gbrain', 'migrate', 'embeddings', '--status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: "Read-only: reports the brain's recorded embedding model and width and what a migration would change." } },
embedded_engine_required: { class: 'caller', summary: "An operation that serves an embedding host (file_register, file_verify) was called on an engine the CLI or a server opened, so it did nothing.", why: 'These operations trust a host that stores bytes itself; a brain opened the usual way stores files through file_upload, so the operations stay off there and its behavior is unchanged.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Call it on an engine opened from settings with settings.storage; a brain the CLI or a server opens stores files only through file_upload (gbrain files upload).' },
engine_closed: { class: 'caller', summary: 'An engine opened from settings was disconnected, which closes it for good, so connect() and reconnect() refuse and nothing was reopened.', docs: 'docs/ENGINES.md#opening-an-engine-from-settings-experimental', suggestion: 'Call openEngine again with the settings to open a new engine.' },
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index b4ae3db318..5da7c612d1 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -312,6 +312,8 @@ export interface DispatchOpts {
stdioSurface?: OperationContext['stdioSurface'];
/** GST-363: OperationContext.stdioMember, from the stdio server's own argv (serve --stdio-member); no other transport sets it. */
stdioMember?: string;
+ /** GST-2476 G2: an enforced member CLI read (cli/enforced-member.ts): privacy stays hidden whatever the hatches say, and no owner relaxation. */
+ enforcedMember?: true;
/** Threaded into OperationContext.revealTools (stdio session tool reveal). */
revealTools?: (names: string[]) => void;
/**
@@ -1029,6 +1031,7 @@ export async function dispatchToolCall(
access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience, opts.transport === 'stdio' && !opts.auth ? opts.stdioMember : undefined);
// GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).
if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');
+ if (opts.enforcedMember) access = { ...access, hidePrivate: true, owner: false, privateReadableSources: [] };
} catch (e) {
// GST-359: a call that names a person gets every failure here (a lock timeout reading its link included) in the
// envelope QM reads, never a thrown call; anything else keeps the caller's own error path.
diff --git a/test/enforced-member-classes.test.ts b/test/enforced-member-classes.test.ts
new file mode 100644
index 0000000000..e047a2c751
--- /dev/null
+++ b/test/enforced-member-classes.test.ts
@@ -0,0 +1,48 @@
+/**
+ * GST-2476 G2: the enforced member allow-list (src/cli/enforced-member-classes.ts) classifies every CLI command and every
+ * operation exactly once.
+ *
+ * 1. Protects: a new CLI command or operation cannot ship unclassified under GBRAIN_ENFORCED_MEMBER, and the table
+ * names nothing that no longer exists.
+ * 2. Fails when: a command in CLI_COMMANDS or an operation in OPERATION_MANIFEST has no class, a classified name is
+ * stale or listed twice, or an unknown command stops resolving to refused.
+ * 3. Existing coverage: test/enforced-member.serial.test.ts (behaviour of each class as real subprocesses).
+ * 4. Real seams: the command table and operation manifest the CLI dispatches from.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI_COMMANDS } from '../src/cli/command-table.ts';
+import { OPERATION_MANIFEST } from '../src/cli/op-manifest.ts';
+import { CLI_COMMAND_CLASSES, OPERATION_CLASSES, OPERATION_SUBCOMMANDS, enforcedClassOf } from '../src/cli/enforced-member-classes.ts';
+
+const CLASSES_SRC = readFileSync(join(import.meta.dir, '..', 'src', 'cli', 'enforced-member-classes.ts'), 'utf8');
+
+describe('enforced member allow-list', () => {
+ test('every CLI-only command has exactly one class, and no class names a missing command', () => {
+ const commands = CLI_COMMANDS.map(c => c.name).sort();
+ expect(Object.keys(CLI_COMMAND_CLASSES).sort()).toEqual(commands);
+ });
+
+ test('every operation has exactly one class, and no class names a missing operation', () => {
+ const ops = OPERATION_MANIFEST.map(o => o.name).sort();
+ expect(Object.keys(OPERATION_CLASSES).sort()).toEqual(ops);
+ const listed = [...CLASSES_SRC.matchAll(/^const (READ|WRITE|REFUSED)_OPS = \[([\s\S]*?)\] as const;/gm)]
+ .flatMap(m => [...m[2]!.matchAll(/'([a-z_]+)'/g)].map(x => x[1]!));
+ expect(listed.length).toBe(new Set(listed).size);
+ });
+
+ test('subcommand overrides sit on commands the operation path dispatches', () => {
+ const cliOnly = new Set(CLI_COMMANDS.map(c => c.name));
+ const opNames = new Set(OPERATION_MANIFEST.flatMap(o => [o.cliHints?.name ?? o.name, ...(o.cliHints?.aliases ?? [])]));
+ for (const name of Object.keys(OPERATION_SUBCOMMANDS)) expect({ name, op: opNames.has(name), cliOnly: cliOnly.has(name) }).toEqual({ name, op: true, cliOnly: false });
+ });
+
+ test('an unknown command or operation resolves to refused', () => {
+ expect(enforcedClassOf('no-such-command-example', [], undefined)).toBe('refused');
+ expect(enforcedClassOf('no-such-command-example', [], 'no_such_op_example')).toBe('refused');
+ expect(enforcedClassOf('search', ['modes'], 'search')).toBe('refused');
+ expect(enforcedClassOf('sync', ['status'], undefined)).toBe('refused');
+ expect(enforcedClassOf('git', ['commit-push'], undefined)).toBe('write');
+ });
+});
diff --git a/test/enforced-member.serial.test.ts b/test/enforced-member.serial.test.ts
new file mode 100644
index 0000000000..b8117a6264
--- /dev/null
+++ b/test/enforced-member.serial.test.ts
@@ -0,0 +1,467 @@
+/**
+ * GST-2476 G2: enforced member mode (GBRAIN_ENFORCED_MEMBER) as real CLI subprocesses against a repo-less brain on
+ * disk (PGLite, and Postgres when DATABASE_URL is set).
+ *
+ * 1. Protects: under the mode every read-filtered command shows no slug, title, body, fact or count of a page the member
+ * cannot read (another member's readers, visibility: private, a folder rule it does not satisfy, another member's
+ * personal source); every refused class, an unknown member, an empty value and the owner id refuse with the exact
+ * first line; hook succeeds silently; writes refuse a page the member cannot read and every label change, and an
+ * allowed write lands exactly as a trusted local write (an owner-bound key reads it); unset changes nothing.
+ * 2. Fails when: any of those reads names a hidden page, a refusal prints anything else first or exits 0, a write
+ * reaches a hidden page or changes a label, a mode write lands member-private, or the variable unset changes output.
+ * 3. Existing coverage: test/access-as.serial.test.ts (--as, which keeps ctx.remote false and is refused here).
+ * 4. Real seams: src/cli.ts and src/cli/main.ts dispatch, MCP dispatch as the member's stdio server, local writes.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createEngine } from '../src/core/engine-factory.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { proposeRevision } from '../src/core/access/policy.ts';
+import { bindCredential } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { OPERATION_CLASSES } from '../src/cli/enforced-member-classes.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const CLI = join(resolve(import.meta.dir, '..'), 'src', 'cli.ts');
+const MEMBER = 'alice-example';
+const OWNER = 'owner-example';
+const FIRST = (who: string, command: string) => 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + who + ': ' + command + ' [GBRAIN_ENFORCED_REFUSED]';
+const NOTICE = 'gbrain: results limited to what GBRAIN_ENFORCED_MEMBER=' + MEMBER + ' may read';
+const REMEMBER_FIRST = 'gbrain: refused under GBRAIN_ENFORCED_MEMBER=' + MEMBER + ': remember saves a fact only with --entity <slug of a page you can read>; nothing was saved [GBRAIN_ENFORCED_REFUSED]';
+const REMEMBER_RETRY = 'Retry: gbrain remember "<one fact>" --entity <exact slug of a page you can read, from gbrain find or gbrain search> --provenance "<where you learned it>"';
+
+const PAGES = {
+ open: { slug: 'notes/open-example', title: 'Open example plan', canary: 'canaryemopen', fm: {} as Record<string, unknown>, source: 'default' },
+ mine: { slug: 'notes/alice-example-plan', title: 'Alice example plan', canary: 'canaryemmine', fm: { readable_by: [MEMBER] }, source: 'default' },
+ team: { slug: 'team-a/roadmap-example', title: 'Team a roadmap', canary: 'canaryemteam', fm: {}, source: 'default' },
+ other: { slug: 'notes/bob-example-plan', title: 'Bob example secret', canary: 'canaryemother', fm: { readable_by: ['bob-example'] }, source: 'default' },
+ priv: { slug: 'notes/quiet-example', title: 'Quiet example memo', canary: 'canaryempriv', fm: { visibility: 'private' }, source: 'default' },
+ folder: { slug: 'team-b/budget-example', title: 'Team b budget', canary: 'canaryemfolder', fm: {}, source: 'default' },
+ personal: { slug: 'notes/dm-example', title: 'Direct example thread', canary: 'canaryempersonal', fm: {}, source: 'bob-dm' },
+} as const;
+type Key = keyof typeof PAGES;
+const VISIBLE: Key[] = ['open', 'mine', 'team'];
+const HIDDEN: Key[] = ['other', 'priv', 'folder', 'personal'];
+const HIDDEN_FACT = 'canaryemfacthidden';
+const OPEN_FACT = 'canaryemfactopen';
+const HIDDEN_MARKS = [...HIDDEN.flatMap(k => [PAGES[k].slug, PAGES[k].title, PAGES[k].canary]), HIDDEN_FACT];
+
+/** Every read-class operation with arguments, so a read op added to the allow-list without a row here fails. */
+const READS: Array<[op: string, args: string[]]> = [
+ ['search', ['search', 'harbor ledger', '--json']],
+ ['query', ['query', 'harbor ledger', '--no-expand', '--json']],
+ ['search_exact', ['search', '--exact', 'harbor', '--json']],
+ ['list_pages', ['list', '--json']],
+ ['find_pages', ['find', 'notes/*', '--json']],
+ ['get_page', ['get', PAGES.open.slug]],
+ ['get_backlinks', ['backlinks', PAGES.open.slug, '--json']],
+ ['get_timeline', ['timeline', PAGES.open.slug, '--json']],
+ ['get_links', ['links', PAGES.open.slug, '--json']],
+ ['get_tags', ['tags', PAGES.open.slug]],
+ ['get_versions', ['history', PAGES.open.slug]],
+ ['get_stats', ['stats', '--by', 'type', '--json']],
+ ['whoami', ['whoami', '--json']],
+ ['entity', ['entity', PAGES.open.slug, '--json']],
+ ['whois', ['whois', 'Bob example', '--json']],
+ ['traverse_graph', ['graph', PAGES.open.slug, '--json']],
+];
+/** recall (a CLI-only read): its facts arms and its page arm. */
+const RECALLS: string[][] = [
+ ['recall', PAGES.open.slug, '--json'],
+ ['recall', PAGES.other.slug, '--json'],
+ ['recall', '--since', '30d', '--json'],
+ ['recall', '--question', 'harbor ledger canary', '--json'],
+ ['recall', '--query', 'harbor ledger', '--json'],
+];
+
+test('every read-class operation has a no-trace row', () => {
+ const classified = Object.entries(OPERATION_CLASSES).filter(([, c]) => c === 'read').map(([op]) => op).sort();
+ expect([...new Set(READS.map(([op]) => op))].sort()).toEqual(classified);
+});
+
+for (const kind of testBackends()) {
+ describe('enforced member mode (' + kind + ', repo-less)', () => {
+ let root: string, home: string;
+ let config: Record<string, unknown>;
+ let closePg: (() => Promise<void>) | null = null;
+ let ownerToken = '';
+
+ function env(extra: Record<string, string | undefined>): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GBRAIN_ENFORCED_MEMBER']) delete out[k];
+ const merged: Record<string, string | undefined> = { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_CLI_SOCKET: '0', ...extra };
+ return Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined)) as Record<string, string>;
+ }
+ async function cli(args: string[], opts: { member?: string | null; stdin?: string } = {}) {
+ const member = opts.member === undefined ? MEMBER : opts.member;
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env({ GBRAIN_ENFORCED_MEMBER: member ?? undefined }),
+ stdin: opts.stdin === undefined ? 'ignore' : new Blob([opts.stdin]), stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+ }
+ async function withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T> {
+ const engine = await createEngine(config as never);
+ await engine.connect(config as never);
+ try { return await run(engine); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ }
+ const leaks = (text: string) => HIDDEN_MARKS.filter(m => text.toLowerCase().includes(m.toLowerCase()));
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-enforced-'));
+ home = join(root, 'home');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ if (kind === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ await pg.engine.disconnect();
+ config = { engine: 'postgres', database_url: pg.databaseUrl };
+ closePg = pg.close;
+ } else {
+ config = { engine: 'pglite', database_path: join(root, 'db') };
+ }
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+ await withBrain(async engine => {
+ if (kind === 'pglite') await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('bob-dm', 'bob-dm', '{\"federated\": true}'::jsonb) ON CONFLICT (id) DO NOTHING");
+ for (const id of [MEMBER, 'bob-example', OWNER]) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await engine.executeRaw("INSERT INTO access_groups (id) VALUES ('team-a'), ('team-b') ON CONFLICT DO NOTHING");
+ await engine.executeRaw("INSERT INTO access_group_members (group_id, member_id) VALUES ('team-a', $1), ('team-b', 'bob-example')", [MEMBER]);
+ await engine.executeRaw("INSERT INTO access_member_sources (member_id, source_id) VALUES ('bob-example', 'bob-dm')");
+ await proposeRevision(engine, 'default', [
+ { id: 'team-a', prefix: 'team-a/', readable_by: ['group:team-a'] },
+ { id: 'team-b', prefix: 'team-b/', readable_by: ['group:team-b'] },
+ ] as never, { origin: 'cli', store: 'database' } as never);
+ for (const key of Object.keys(PAGES) as Key[]) {
+ const p = PAGES[key];
+ const fm = Object.entries(p.fm).map(([k, v]) => k + ': ' + JSON.stringify(v)).join('\n');
+ await importFromContent(engine, p.slug, '---\ntype: note\ntitle: ' + JSON.stringify(p.title) + '\n' + (fm ? fm + '\n' : '') + '---\n# ' + p.title + '\n\nHarbor ledger planning notes ' + p.canary + ' for the roadmap.\n', { sourceId: p.source, noEmbed: true });
+ }
+ await engine.addLink(PAGES.open.slug, PAGES.other.slug, 'see the secret plan', 'mentions');
+ await engine.addLink(PAGES.other.slug, PAGES.open.slug, 'back to open', 'mentions');
+ await engine.addTimelineEntry(PAGES.other.slug, { date: '2026-01-02', summary: 'Hidden event ' + HIDDEN_FACT } as never, { sourceId: 'default' });
+ await engine.insertFact({ fact: 'Harbor ledger fact ' + HIDDEN_FACT, entity_slug: PAGES.other.slug, visibility: 'world', source: 'test', embedding: null }, { source_id: 'default' });
+ await engine.insertFact({ fact: 'Harbor ledger fact ' + OPEN_FACT, entity_slug: PAGES.open.slug, visibility: 'world', source: 'test', embedding: null }, { source_id: 'default' });
+ const minted = await mintLegacyToken(engine, { name: 'owner-key', scopes: ['read'], takesHolders: ['world'] } as never);
+ ownerToken = minted.token;
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: OWNER });
+ await setOwner(engine, OWNER);
+ });
+ }, 240_000);
+
+ afterAll(async () => {
+ rmSync(root, { recursive: true, force: true });
+ await closePg?.();
+ }, 60_000);
+
+ test('fixture control: the trusted CLI (variable unset) reads the hidden pages', async () => {
+ const r = await cli(['list', '--json'], { member: null });
+ expect(r.exitCode).toBe(0);
+ for (const key of ['other', 'priv', 'folder'] as Key[]) expect(r.stdout).toContain(PAGES[key].slug);
+ const personal = await cli(['get', PAGES.personal.slug, '--source', 'bob-dm'], { member: null });
+ expect(personal.stdout).toContain(PAGES.personal.canary);
+ const search = await cli(['search', 'harbor ledger', '--json'], { member: null });
+ expect(search.stdout).toContain(PAGES.other.slug);
+ }, 120_000);
+
+ test("another member's personal source is out of scope for reads and writes", async () => {
+ const cases: Array<[string[], string, string | undefined]> = [
+ [['list', '--source', 'bob-dm'], 'list', undefined],
+ [['get', PAGES.personal.slug, '--source', 'bob-dm'], 'get', undefined],
+ [['search', 'harbor ledger', '--source', 'bob-dm'], 'search', undefined],
+ [['put', 'notes/alice-example-dm', '--source', 'bob-dm'], 'put', '---\ntype: note\ntitle: X\n---\n# X\n\nBody.\n'],
+ ];
+ for (const [args, command, stdin] of cases) {
+ const r = await cli(args, { stdin });
+ expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0], leaks: leaks(r.stdout + r.stderr) }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, command), leaks: [] });
+ }
+ }, 300_000);
+
+ test('every read-filtered command shows no trace of a page the member cannot read, and prints the constant line', async () => {
+ for (const [op, args] of READS) {
+ const r = await cli(args);
+ expect({ op, leaks: leaks(r.stdout + r.stderr), exit: r.exitCode, notice: r.stderr.includes(NOTICE), withheld: r.stderr.includes('output is withheld') })
+ .toEqual({ op, leaks: [], exit: 0, notice: true, withheld: false });
+ if (['search', 'search_exact', 'list_pages', 'find_pages'].includes(op)) expect({ op, open: r.stdout.includes(PAGES.open.slug) }).toEqual({ op, open: true });
+ }
+ }, 600_000);
+
+ test('visible pages still read under the mode', async () => {
+ const list = await cli(['list', '--json']);
+ for (const key of VISIBLE) expect({ key, seen: list.stdout.includes(PAGES[key].slug) }).toEqual({ key, seen: true });
+ const stats = await cli(['stats', '--by', 'type', '--json']);
+ expect(JSON.parse(stats.stdout).total_pages).toBe(VISIBLE.length);
+ const get = await cli(['get', PAGES.mine.slug]);
+ expect(get.stdout).toContain(PAGES.mine.canary);
+ }, 240_000);
+
+ test('recall shows no hidden fact or page on its facts arms and its page arm', async () => {
+ for (const args of RECALLS) {
+ const r = await cli(args);
+ expect({ args: args.join(' '), leaks: leaks(r.stdout + r.stderr), notice: r.stderr.includes(NOTICE) }).toEqual({ args: args.join(' '), leaks: [], notice: true });
+ }
+ const open = await cli(['recall', PAGES.open.slug, '--json']);
+ expect(open.stdout).toContain(OPEN_FACT);
+ }, 300_000);
+
+ test('a hidden page reads exactly like a missing one', async () => {
+ const missing = await cli(['get', 'notes/never-written-example']);
+ for (const key of HIDDEN) {
+ const r = await cli(['get', PAGES[key].slug]);
+ const norm = (t: string) => t.split(PAGES[key].slug).join('<slug>').split('notes/never-written-example').join('<slug>');
+ expect({ key, exit: r.exitCode, out: norm(r.stdout), err: norm(r.stderr) }).toEqual({ key, exit: missing.exitCode, out: norm(missing.stdout), err: norm(missing.stderr) });
+ }
+ }, 240_000);
+
+ test('each refused class refuses with the exact first line, exit 3', async () => {
+ const cases: Array<[string[], string]> = [
+ [['config', 'show'], 'config'], [['doctor', '--fix'], 'doctor'], [['call', 'get_page', '{}'], 'call'], [['serve'], 'serve'],
+ [['sources', 'list'], 'sources list'], [['sources', 'status'], 'sources status'], [['sync', 'status'], 'sync status'],
+ [['auth', 'list'], 'auth'], [['access', 'member', 'list'], 'access'], [['search', 'modes'], 'search modes'],
+ [['stats', '--json'], 'stats'], [['get', PAGES.open.slug, '--as', MEMBER], 'get'], [['context-pack', 'harbor'], 'context-pack'],
+ [['put-pages'], 'put-pages'], [['status'], 'status'], [['jobs', 'list'], 'jobs'],
+ [['upgrade'], 'upgrade'], [['autopilot', 'status'], 'autopilot'], [['repair', 'frontmatter'], 'repair'], [['delete', PAGES.open.slug], 'delete'],
+ [['reindex'], 'reindex'], [['embed', '--stale'], 'embed'], [['dream'], 'dream'], [['write-requests'], 'write-requests'],
+ [['sources', 'writer', 'status'], 'sources writer'],
+ ];
+ for (const [args, command] of cases) {
+ const r = await cli(args);
+ expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, command) });
+ expect(r.stderr).toContain('Recovery: do not retry here; nothing was changed.');
+ expect(r.stderr).toContain('docs/guides/enforced-member.md#refused');
+ }
+ }, 600_000);
+
+ test('an unknown member, an empty value and the owner id refuse every read', async () => {
+ for (const [who, label] of [['nobody-example', 'nobody-example'], ['', ''], [OWNER, OWNER], ['Not Valid!', '<invalid>']] as const) {
+ for (const args of [['search', 'harbor ledger'], ['list'], ['recall', PAGES.open.slug]]) {
+ const r = await cli(args, { member: who });
+ expect({ who, args: args[0], exit: r.exitCode, first: r.stderr.split('\n')[0], out: r.stdout }).toEqual({ who, args: args[0], exit: 3, first: FIRST(label, args[0]!), out: '' });
+ }
+ }
+ }, 600_000);
+
+ test('hook succeeds silently: nothing on stdout, the constant line, exit 0', async () => {
+ for (const event of ['session-start', 'user-prompt']) {
+ const r = await cli(['hook', event]);
+ expect({ event, exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ event, exit: 0, out: '', err: NOTICE + '\n' });
+ }
+ }, 120_000);
+
+ test('writes refuse a hidden target and every label change', async () => {
+ const page = (title: string, fm = '') => '---\ntype: note\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nBody text.\n';
+ const refused: Array<[string[], string, string | undefined]> = [
+ [['put', PAGES.other.slug], 'put', page('Overwrite')],
+ [['put', PAGES.folder.slug], 'put', page('Overwrite')],
+ [['put', 'team-b/new-example'], 'put', page('New under rule')],
+ [['put', 'notes/labelled-example'], 'put', page('Labelled', 'readable_by: [alice-example]\n')],
+ [['put', 'notes/private-new-example'], 'put', page('Private new', 'visibility: private\n')],
+ [['put', PAGES.open.slug], 'put', page('Open example plan', 'visibility: private\n')],
+ [['link', PAGES.open.slug, PAGES.other.slug], 'link', undefined],
+ [['tag', PAGES.priv.slug, 'x'], 'tag', undefined],
+ [['remember', 'A fact', '--entity', PAGES.open.slug, '--provenance', 'test', '--visibility', 'private'], 'remember', undefined],
+ ];
+ for (const [args, command, stdin] of refused) {
+ const r = await cli(args, { stdin });
+ expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.join(' '), exit: 3, first: FIRST(MEMBER, command) });
+ expect(r.stderr.toLowerCase()).not.toContain('exists');
+ }
+ for (const args of [['remember', 'A fact', '--provenance', 'test'], ['remember', 'A fact', '--entity', PAGES.other.slug, '--provenance', 'test'], ['remember', 'A fact', '--entity', 'Notes/Open-Example', '--provenance', 'test']]) {
+ const r = await cli(args);
+ const lines = r.stderr.split('\n');
+ expect({ args: args.join(' '), exit: r.exitCode, first: lines[0], second: lines[1], out: r.stdout }).toEqual({ args: args.join(' '), exit: 3, first: REMEMBER_FIRST, second: REMEMBER_RETRY, out: '' });
+ expect(r.stderr).toContain('Recovery: nothing was saved, so retrying with --entity is safe.');
+ expect(r.stderr.toLowerCase()).not.toContain('exists');
+ }
+ await withBrain(async engine => {
+ const rows = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact = 'A fact'");
+ expect(rows[0]!.n).toBe(0);
+ });
+ const control = await cli(['get', PAGES.other.slug], { member: null });
+ expect(control.stdout).toContain(PAGES.other.canary);
+ }, 600_000);
+
+ test('an allowed write lands as a trusted local write, readable by an owner-bound key', async () => {
+ const put = await cli(['put', 'notes/alice-example-draft'], { stdin: '---\ntype: note\ntitle: Alice draft\n---\n# Alice draft\n\nDraft canaryemdraft.\n' });
+ expect({ exit: put.exitCode, err: put.exitCode === 0 ? '' : put.stderr }).toEqual({ exit: 0, err: '' });
+ const remember = await cli(['remember', 'Harbor ledger fact canaryemremember', '--entity', PAGES.open.slug, '--provenance', 'test turn']);
+ expect({ exit: remember.exitCode, err: remember.exitCode === 0 ? '' : remember.stderr }).toEqual({ exit: 0, err: '' });
+ await withBrain(async engine => {
+ const [row] = await engine.executeRaw<{ frontmatter: unknown }>("SELECT frontmatter FROM pages WHERE slug = 'notes/alice-example-draft'");
+ const fm = (typeof row!.frontmatter === 'string' ? JSON.parse(row!.frontmatter) : row!.frontmatter) as Record<string, unknown>;
+ expect(fm.readable_by).toBeUndefined();
+ expect(fm.visibility).toBeUndefined();
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(ownerToken) as unknown as AuthInfo;
+ const call = async (op: string, params: Record<string, unknown>) => (await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'] })).content.map(c => c.text).join('\n');
+ expect(await call('get_page', { slug: 'notes/alice-example-draft' })).toContain('canaryemdraft');
+ expect(await call('recall', { entity: PAGES.open.slug })).toContain('canaryemremember');
+ });
+ }, 300_000);
+
+ test("write-request reads the member's own receipts; any other id answers exactly as an unknown one", async () => {
+ const body = '---\ntype: note\ntitle: Receipt example\n---\n# Receipt example\n\nBody.\n';
+ const own = await cli(['put', 'notes/alice-example-receipt', '--json'], { stdin: body });
+ expect(own.exitCode).toBe(0);
+ const ownId = JSON.parse(own.stdout).request_id as string;
+ const other = await cli(['put', 'notes/owner-example-receipt', '--json'], { member: null, stdin: body });
+ const otherId = JSON.parse(other.stdout).request_id as string;
+ expect({ ownId: typeof ownId, otherId: typeof otherId, same: ownId === otherId }).toEqual({ ownId: 'string', otherId: 'string', same: false });
+ expect((await cli(['write-request', otherId], { member: null })).exitCode).toBe(0);
+ for (const json of [false, true]) {
+ const flag = json ? ['--json'] : [];
+ const mine = await cli(['write-request', ownId, ...flag]);
+ expect({ json, exit: mine.exitCode, id: mine.stdout.includes(ownId) }).toEqual({ json, exit: 0, id: true });
+ const unknown = await cli(['write-request', crypto.randomUUID(), ...flag]);
+ expect(unknown.exitCode).not.toBe(0);
+ for (const id of [otherId, otherId.toUpperCase(), 'not-a-request-id']) {
+ const r = await cli(['write-request', id, ...flag]);
+ expect({ json, id, exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ json, id, exit: unknown.exitCode, out: unknown.stdout, err: unknown.stderr });
+ expect((r.stdout + r.stderr).toLowerCase()).not.toContain('exists');
+ expect(r.stdout + r.stderr).not.toContain('owner-example-receipt');
+ }
+ }
+ }, 300_000);
+
+ test('doctor under the mode prints only check names, statuses and counts', async () => {
+ const trusted = await cli(['doctor', '--json'], { member: null });
+ const r = await cli(['doctor', '--json']);
+ expect({ exit: r.exitCode, leaks: leaks(r.stdout + r.stderr) }).toEqual({ exit: trusted.exitCode, leaks: [] });
+ for (const mark of ['bob-dm', 'team-b', 'notes/']) expect({ mark, seen: (r.stdout + r.stderr).includes(mark) }).toEqual({ mark, seen: false });
+ const report = JSON.parse(r.stdout) as { status: string; checks: Array<Record<string, string>>; counts: Record<string, number> };
+ expect(Object.keys(report).sort()).toEqual(['checks', 'counts', 'status']);
+ expect(report.checks.length).toBe((JSON.parse(trusted.stdout).checks as unknown[]).length);
+ for (const c of report.checks) expect({ keys: Object.keys(c).sort(), name: /^[a-z0-9_]+$/.test(c.name!), status: /^[a-z0-9_]+$/.test(c.status!) }).toEqual({ keys: ['name', 'status'], name: true, status: true });
+ expect(Object.values(report.counts).reduce((a, b) => a + b, 0)).toBe(report.checks.length);
+ expect(r.stderr).toBe('gbrain: doctor shows check names, statuses and counts only under GBRAIN_ENFORCED_MEMBER\n');
+ const plain = await cli(['doctor']);
+ const lines = plain.stdout.trim().split('\n');
+ expect(lines.slice(0, -1).every(l => /^[a-z0-9_]+ [a-z0-9_]+$/.test(l))).toBe(true);
+ expect(leaks(plain.stdout + plain.stderr)).toEqual([]);
+ }, 300_000);
+
+ test('variable unset: output is unchanged', async () => {
+ for (const args of [['list', '--json'], ['get', PAGES.other.slug], ['stats', '--json']]) {
+ const a = await cli(args, { member: null });
+ const b = await cli(args, { member: null });
+ expect({ args: args[0], exit: a.exitCode, out: a.stdout }).toEqual({ args: args[0], exit: b.exitCode, out: b.stdout });
+ expect(a.stderr).not.toContain('GBRAIN_ENFORCED_MEMBER');
+ }
+ }, 300_000);
+ });
+}
+
+for (const kind of testBackends()) {
+ describe('enforced member mode: git commit-push and sync (' + kind + ')', () => {
+ let root: string, home: string, checkout: string;
+ let config: Record<string, unknown>;
+ let closePg: (() => Promise<void>) | null = null;
+
+ function env(member: string | null): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
+ for (const k of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GBRAIN_ENFORCED_MEMBER']) delete out[k];
+ return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_CLI_SOCKET: '0',
+ GIT_AUTHOR_NAME: 'Example', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Example', GIT_COMMITTER_EMAIL: '[email protected]', ...(member === null ? {} : { GBRAIN_ENFORCED_MEMBER: member }) };
+ }
+ async function cli(args: string[], member: string | null = MEMBER) {
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: checkout, env: env(member), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+ }
+ const git = (...args: string[]) => execFileSync('git', ['-C', checkout, ...args], { env: env(null), stdio: ['ignore', 'pipe', 'pipe'] }).toString();
+ const note = (title: string, fm = '') => '---\ntype: note\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nHarbor notes.\n';
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-enforced-git-'));
+ home = join(root, 'home');
+ checkout = join(root, 'checkout');
+ const remote = join(root, 'remote.git');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ execFileSync('git', ['init', '-q', '--bare', '-b', 'main', remote]);
+ execFileSync('git', ['clone', '-q', remote, checkout], { stdio: 'ignore' });
+ mkdirSync(join(checkout, 'notes'), { recursive: true });
+ writeFileSync(join(checkout, 'notes', 'open-git.md'), note('Open git'));
+ writeFileSync(join(checkout, 'notes', 'bob-git.md'), note('Bob git', 'readable_by: [bob-example]\n'));
+ git('checkout', '-q', '-b', 'main');
+ git('add', '-A');
+ git('commit', '-qm', 'synthetic content');
+ git('push', '-q', 'origin', 'main');
+ if (kind === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ await pg.engine.disconnect();
+ config = { engine: 'postgres', database_url: pg.databaseUrl };
+ closePg = pg.close;
+ } else {
+ config = { engine: 'pglite', database_path: join(root, 'db') };
+ }
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+ const engine = await createEngine(config as never);
+ await engine.connect(config as never);
+ try {
+ if (kind === 'pglite') await engine.initSchema();
+ for (const id of [MEMBER, 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('repo-src', 'repo-src', $1)", [checkout]);
+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ const synced = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed'], null);
+ expect({ exit: synced.exitCode, err: synced.exitCode === 0 ? '' : synced.stderr }).toEqual({ exit: 0, err: '' });
+ }, 300_000);
+
+ afterAll(async () => {
+ rmSync(root, { recursive: true, force: true });
+ await closePg?.();
+ }, 60_000);
+
+ test('commit-push refuses a hidden file, a label change, a policy file and the refused modes', async () => {
+ writeFileSync(join(checkout, 'notes', 'bob-git.md'), note('Bob git', 'readable_by: [bob-example]\n') + 'More.\n');
+ writeFileSync(join(checkout, 'notes', 'open-git.md'), note('Open git', 'visibility: private\n'));
+ mkdirSync(join(checkout, '.gbrain'), { recursive: true });
+ writeFileSync(join(checkout, '.gbrain', 'access.yml'), 'rules: []\n');
+ const cases: string[][] = [
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md'],
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/open-git.md'],
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes'],
+ ['git', 'commit-push', '--path', checkout, '-m', 'x', '--', '.gbrain/access.yml'],
+ ['git', 'commit-push', '--path', checkout, '--pending'],
+ ['git', 'commit-push', '--path', checkout, '--push-only'],
+ ['git', 'guard', '--install'],
+ ];
+ for (const args of cases) {
+ const r = await cli(args);
+ const command = args[1] === 'guard' ? 'git guard' : 'git commit-push';
+ expect({ args: args.slice(-1)[0], exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ args: args.slice(-1)[0], exit: 3, first: FIRST(MEMBER, command) });
+ }
+ expect(git('status', '--porcelain')).toContain('notes/bob-git.md');
+ git('checkout', '-q', '--', 'notes');
+ rmSync(join(checkout, '.gbrain'), { recursive: true, force: true });
+ }, 300_000);
+
+ test('commit-push of a readable new file and --pull run with their output withheld', async () => {
+ writeFileSync(join(checkout, 'notes', 'alice-git.md'), note('Alice git'));
+ const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note', '--', 'notes/alice-git.md']);
+ expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: git commit-push finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ expect(git('log', '--format=%s', '-1').trim()).toBe('alice note');
+ const pull = await cli(['git', 'commit-push', '--path', checkout, '--pull']);
+ expect({ exit: pull.exitCode, out: pull.stdout, err: pull.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: git commit-push finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ }, 300_000);
+
+ test('sync runs with its output withheld; sync status is refused', async () => {
+ const r = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed']);
+ expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ const json = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed', '--json']);
+ expect({ exit: json.exitCode, out: json.stdout, err: json.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });
+ const status = await cli(['sync', 'status', '--source', 'repo-src']);
+ expect({ exit: status.exitCode, first: status.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'sync status') });
+ }, 300_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 88a04eddc1..bde89a7d9e 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -89,6 +89,7 @@ test/edge-whitespace-twins.test.ts
test/embed-once-per-content-version.serial.test.ts
test/embed-stale-images-managed-6529.test.ts
test/embedding-completion-atomic.serial.test.ts
+test/enforced-member.serial.test.ts
test/engine-sql-facts-keyset.test.ts
test/extract-all-stamp-intersection.serial.test.ts
test/extract-atoms-input-truncated-6503.test.ts