Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Make access.enforced_member_writes three-valued and close named-path commit-push under refuse
garrytan3c26618f9959
diff --git a/changelog.d/capy-enforced-member-writes-off.md b/changelog.d/capy-enforced-member-writes-off.mdindex 538932c458..2c1e1c8baa 100644--- a/changelog.d/capy-enforced-member-writes-off.md+++ b/changelog.d/capy-enforced-member-writes-off.md@@ -1,4 +1,4 @@-**A brain owner can now make member CLIs read-only: with `access.enforced_member_writes` set to `refuse`, every page write under `GBRAIN_ENFORCED_MEMBER` refuses.**+**A brain owner can now make member CLIs read-only: with `access.enforced_member_writes` set to `refuse`, every write under `GBRAIN_ENFORCED_MEMBER` refuses.**### Added-- `gbrain config set access.enforced_member_writes refuse` makes enforced member mode refuse `put`, `link`, `unlink`, `tag`, `untag`, `timeline-add`, `remember`, `edit_page` and `append_page` with exit 3 and reason `writes_off`. The refusal comes before any page or source lookup, so it reads the same for a new, readable or hidden target and names none. The key lives in the brain's database, so it works on a brain with no repository, and a member can't change it because `config` is refused under the mode. Unset or `checked` keeps today's checked writes; any other value, or a config read that fails, refuses. Reads, a CLI without the variable, `git commit-push`, `sync`, `sources refresh` and `write-request` are unchanged. See docs/guides/enforced-member.md#writes-off.+- `gbrain config set access.enforced_member_writes refuse` makes enforced member mode refuse `put`, `link`, `unlink`, `tag`, `untag`, `timeline-add`, `remember`, `edit_page`, `append_page` and `git commit-push` with named paths, with exit 3 and reason `writes_off`. `refuse_pages` refuses the same page writes and leaves named-path `git commit-push` to its usual checks, for a host whose member turns still commit files. The refusal comes before any page, path or source lookup, so it reads the same for a new, readable or hidden target and names none. The key lives in the brain's database, so it works on a brain with no repository, and a member can't change it because `config` is refused under the mode. Unset or `checked` keeps today's checked writes; any other value, or a config read that fails, counts as `refuse`. Reads, a CLI without the variable, `git commit-push --pull` and `--dry-run`, `sync`, `sources refresh` and `write-request` are unchanged. See docs/guides/enforced-member.md#writes-off.diff --git a/docs/architecture/key-files/access.md b/docs/architecture/key-files/access.mdindex ea6c76514a..57c51b4cf5 100644--- a/docs/architecture/key-files/access.md+++ b/docs/architecture/key-files/access.md@@ -11,4 +11,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/access/requester-scope.ts` + `src/commands/doctor/checks/unscoped-shared-reads.ts` (GST-363 PR 2) — on a brain that serves several people (`servesPolicyFrom` in `search/private-visibility.ts`, read from the request config snapshot: explicit `access.serves` wins, else `access.serves_derived`; a brain pinned `one` never gates) a remote read from a connection bound to no member (no member identity, no audience, not attested, no `reads_unscoped`) is refused `requester_scope_required` before any work. Deny by default: every op not `mutating: true`, and every read-scope one (`think`), except `REQUESTER_SCOPE_EXEMPT` and `OWN_JOB_OPS` for a non-admin credential; `test/requester-scope.test.ts` pins the list and spies every handler. `requesterScopeGate` runs in `dispatchToolCall` after access resolves (attested calls exempt; an unreachable op keeps the unknown-tool envelope) and in `brain-allowlist.ts` `scopedJobAccess` per job tool call; a bound caller's access is never changed. `readsUnscoped`/`createdAt` come from the verifiers (`token-binding.ts` `credentialScopeFields`), else `credentialScopeFor`. Grace: 14 days from `access.serves_since` (migration v309's trigger sets it once) for connections created at or before it (unknown creation and stdio count as old), with `_meta.access.requester_scope`; `access.requester_scope_enforce false` (hosted) gives the notice only. An unreadable policy (`servesUnknown`) is read once more (`withServesReread`); a second failure refuses `requester_scope_unknown` (retryable). `assertCredentialScoped` refuses unbound `auth create`/`register-client` and `POST /admin/api/api-keys` (`credential_scope_required`); `--reads-unscoped [none]` changes go to the `access-reads-unscoped` audit file. `unscopedConnections` feeds doctor `unscoped_shared_reads`, `whoami` (`requesterScopeView`) and post-upgrade.- `src/core/access/stdio-bind-route.ts` + `src/commands/doctor/checks/shared-stdio-binding.ts` (GST-363 PR 2) — `stdioBindRoute()` is the one place that says how to bind an unbound stdio connection: `gbrain setup claude-code|codex --stdio-member <id>` for a harness one person uses (that harness entry, either engine), else a per-person `serve --http` key. The requester-scope refusal and notice, `gbrain access owner`'s Bind-one line and whoami's unbound note read it. Doctor `shared_stdio_binding` fails when `mcp.stdio_member` is set and `sharedStdioHarness()` (`setup-serves.ts`; a `hermes` on PATH counts only as a script, not React Native's compiled engine) finds OpenClaw or Hermes on a brain that serves several people (not applicable on a one-person brain); fix `gbrain config unset mcp.stdio_member`. `requesterScopeRefuses()` lets dispatch drop hot memory from the ops the gate does not cover for a connection it would refuse. Tests: `test/shared-stdio-binding.test.ts`.- `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`; `v5.json` marks context_pack `scope_read`, v4's markings frozen as `V4_SCOPE_READ_OPS`). 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. The gate classifies before help: a refused command refuses with `--help` too, and an allowed one prints only its static help. `checkEnforcedOpArgs` first refuses every write operation except `get_write_request` with reason `writes_off` when the brain's config `access.enforced_member_writes` (database only, read by `enforcedWritesRefused`) is anything but unset or `checked`, or cannot be read, before any member, page or source lookup; then it refuses a named source (`--source`, `--source-id`, `--source-ids`) the member cannot read or that is not registered, alike. Reads go through `dispatchToolCall` (with only the operation's declared params; the source travels as the call's `sourceId`) 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`); sync and `sources refresh` take only their listed flags and a readable source (`syncSourceArg`); `entity` and every coverage notice drop the mention coverage count (`withoutCoverageCounts`); `timeline-add` refuses a gbrain fence marker; `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), `test/enforced-member-writes-off.test.ts` (the switch's values and a failed read).+- `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. The gate classifies before help: a refused command refuses with `--help` too, and an allowed one prints only its static help. `checkEnforcedOpArgs` first refuses every write operation except `get_write_request` with reason `writes_off` (`refuseWritesOff`) when the brain's config `access.enforced_member_writes` (database only, read by `enforcedWritesMode`: `checked` or unset, `refuse_pages`, else `refuse`, also on a failed read) is not `checked`, before any member, page or source lookup, and `checkEnforcedCommitPush` refuses a named-path commit the same way under `refuse` before any path lookup; then it refuses a named source (`--source`, `--source-id`, `--source-ids`) the member cannot read or that is not registered, alike. Reads go through `dispatchToolCall` (with only the operation's declared params; the source travels as the call's `sourceId`) 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`); sync and `sources refresh` take only their listed flags and a readable source (`syncSourceArg`); `entity` and every coverage notice drop the mention coverage count (`withoutCoverageCounts`); `timeline-add` refuses a gbrain fence marker; `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), `test/enforced-member-writes-off.test.ts` (the switch's values and a failed read).diff --git a/docs/guides/enforced-member.md b/docs/guides/enforced-member.mdindex 3d83c21d1a..eea24118c0 100644--- a/docs/guides/enforced-member.md+++ b/docs/guides/enforced-member.md@@ -61,38 +61,48 @@ change against HEAD; `--pending`, `--push-only` and `--resolve` are refused.<a id="writes-off"></a>## Turn member writes off-A brain owner who wants member CLIs to read and never write sets one key in the+A brain owner who wants member CLIs to read and not write sets one key in thebrain's config, from a direct session (one without `GBRAIN_ENFORCED_MEMBER`):```gbrain config set access.enforced_member_writes refuse```-Then every page write under the mode refuses: `put` (a new slug, a page the member-reads and a page it can't read alike), `link`, `unlink`, `tag`, `untag`,-`timeline-add`, `remember`, and `edit_page` and `append_page`. The refusal-comes before any page or source lookup, so it reads the same for every target-and names none:+| Value | Page writes | `git commit-push` with named paths |+|---|---|---|+| `checked` (default, or no value) | checked as described above | checked as described above |+| `refuse_pages` | refused | checked as described above |+| `refuse` (and any other value) | refused | refused |++Page writes are `put` (a new slug, a page the member reads and a page it can't+read alike), `link`, `unlink`, `tag`, `untag`, `timeline-add`, `remember`, and+`edit_page` and `append_page`. Use `refuse_pages` when a host's member turns+still commit files on purpose. The refusal comes before any page, path or+source lookup, so it reads the same for every target and names none:```gbrain: refused under GBRAIN_ENFORCED_MEMBER=alice-example: writes are off for members on this brain; nothing was saved [GBRAIN_ENFORCED_REFUSED]-Why: This brain turned off page writes under this mode: its config access.enforced_member_writes is not checked, or could not be read.+Why: This brain turned off member writes under this mode: its config access.enforced_member_writes is refuse (or a value other than checked and refuse_pages), or could not be read.Fix: ask the brain owner to save it in a direct session (one without GBRAIN_ENFORCED_MEMBER).Recovery: nothing was saved; the same call refuses every time, so do not retry here.Docs: docs/guides/enforced-member.md#refused```+Under `refuse_pages` the Why line reads: `This brain turned off member page+writes under this mode: its config access.enforced_member_writes is+refuse_pages.`+- The key lives in the brain's database, so it works on a brain with norepository and no environment variable overrides it. `config` is refusedunder the mode, so a member can't change it.-- `checked`, or no value, is the default: writes are checked as described- above. Any other value, or a config read that fails, refuses (fail closed).+- Any value other than `checked` and `refuse_pages`, or a config read that+ fails, counts as `refuse` (fail closed).`gbrain config set access.enforced_member_writes checked` turns writes back on.- Reads are never affected, and neither is a CLI without`GBRAIN_ENFORCED_MEMBER`.-- `git commit-push` (named paths, `--pull`, `--dry-run`), `sync`,- `sources refresh` and `write-request` keep their behaviour under the- switch.+- Under every value, `git commit-push --pull`, `git commit-push --dry-run`,+ `sync`, `sources refresh` and `write-request` keep their behaviour: they+ bring in or read what is already committed.<a id="refused"></a>## Refuseddiff --git a/src/cli/enforced-commit-push.ts b/src/cli/enforced-commit-push.tsindex 68e6af6a58..49a7b67817 100644--- a/src/cli/enforced-commit-push.ts+++ b/src/cli/enforced-commit-push.ts@@ -1,15 +1,15 @@/*** 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.+ * --pull run (their output withheld by the caller); every other publishing mode is refused, and a named-path commit+ * refuses when the brain's access.enforced_member_writes is refuse. 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';+import { enforcedAccess, enforcedWritesMode, markdownLabels, memberPageView, refuseEnforced, refuseWritesOff } 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', '--untrack']);@@ -45,6 +45,7 @@ export async function checkEnforcedCommitPush(engine: BrainEngine, args: readonl}if (pull && !named.length) return;if (!named.length) return dryRun ? undefined : refuseEnforced(command, 'arguments_not_allowed', { engine });+ if (!dryRun && await enforcedWritesMode(engine) === 'refuse') return refuseWritesOff(engine, command, 'refuse');const { checkoutRoot, scopePaths } = await import('../core/git/commit-push.ts');let repo: string;let files: string[];diff --git a/src/cli/enforced-member.ts b/src/cli/enforced-member.tsindex 5fdc7a81b1..446e9c35b0 100644--- a/src/cli/enforced-member.ts+++ b/src/cli/enforced-member.ts@@ -30,7 +30,7 @@ const REASON_TEXT: Record<EnforcedReason, string> = {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.',- writes_off: 'This brain turned off page writes under this mode: its config access.enforced_member_writes is not checked, or could not be read.',+ writes_off: 'This brain turned off member writes under this mode: its config access.enforced_member_writes is refuse (or a value other than checked and refuse_pages), or could not be read.',};/** The mode's member value, or undefined when the mode is off (the variable unset). */@@ -80,25 +80,25 @@ const OWNER_FIX = 'ask the brain owner to run this in a direct session (one withconst 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 {+export function refusalText(command: string, reason: EnforcedReason, retry?: string, why?: 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],+ 'Why: ' + (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) {+export function enforcedRefusalError(command: string, reason: EnforcedReason, why?: string) {const next = REASON_NEXT[reason];- return opError('enforced_member_refused', 'Refused under ' + ENFORCED_MEMBER_ENV + ': ' + (REASON_HEADLINE[reason] ?? commandLabel(command)) + '. ' + REASON_TEXT[reason],+ return opError('enforced_member_refused', 'Refused under ' + ENFORCED_MEMBER_ENV + ': ' + (REASON_HEADLINE[reason] ?? commandLabel(command)) + '. ' + (why ?? 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 });+export async function refuseEnforced(command: string, reason: EnforcedReason, opts: { engine?: BrainEngine | null; retry?: string; why?: string } = {}): Promise<never> {+ try { process.stderr.write(refusalText(command, reason, opts.retry, opts.why)); } catch { /* stderr gone */ }+ const code = writeCliError(enforcedRefusalError(command, reason, opts.why), 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);@@ -208,15 +208,26 @@ function namedSources(op: { params: Record<string, unknown> }, params: Record<stexport const ENFORCED_MEMBER_WRITES_KEY = 'access.enforced_member_writes';+export type EnforcedWritesMode = 'checked' | 'refuse_pages' | 'refuse';+/*** The brain's switch for writes under the mode, read from the database config (never the environment): unset or checked- * keeps writes checked; refuse, any other value and a failed read refuse them.+ * keeps writes checked; refuse_pages refuses page-write operations and leaves named-path git commit-push to its checks;+ * refuse, any other value and a failed read refuse both.*/-export async function enforcedWritesRefused(engine: BrainEngine): Promise<boolean> {+export async function enforcedWritesMode(engine: BrainEngine): Promise<EnforcedWritesMode> {try {- const value = await engine.getConfig(ENFORCED_MEMBER_WRITES_KEY);- return value !== null && value.trim().toLowerCase() !== 'checked';- } catch { return true; }+ const value = (await engine.getConfig(ENFORCED_MEMBER_WRITES_KEY))?.trim().toLowerCase() ?? null;+ if (value === null || value === 'checked') return 'checked';+ return value === 'refuse_pages' ? 'refuse_pages' : 'refuse';+ } catch { return 'refuse'; }+}++const PAGE_WRITES_OFF_WHY = 'This brain turned off member page writes under this mode: its config access.enforced_member_writes is refuse_pages.';++/** Refuses a write the brain's switch turned off: the same headline for every target, the Why naming what the mode turned off. */+export async function refuseWritesOff(engine: BrainEngine, command: string, mode: Exclude<EnforcedWritesMode, 'checked'>): Promise<never> {+ return refuseEnforced(command, 'writes_off', { engine, ...(mode === 'refuse_pages' ? { why: PAGE_WRITES_OFF_WHY } : {}) });}/**@@ -226,7 +237,10 @@ export async function enforcedWritesRefused(engine: BrainEngine): Promise<boolea* already drops hidden sources), and get_stats only with --by.*/export async function checkEnforcedOpArgs(engine: BrainEngine, command: string, op: { name: string; params: Record<string, unknown> }, params: Record<string, unknown>): Promise<void> {- if (OPERATION_CLASSES[op.name] === 'write' && op.name !== 'get_write_request' && await enforcedWritesRefused(engine)) await refuseEnforced(command, 'writes_off', { engine });+ if (OPERATION_CLASSES[op.name] === 'write' && op.name !== 'get_write_request') {+ const mode = await enforcedWritesMode(engine);+ if (mode !== 'checked') await refuseWritesOff(engine, command, mode);+ }await enforcedAccess(engine, command);for (const s of namedSources(op, params)) if (s !== '__all__') await checkEnforcedSource(engine, command, s);if (op.name === 'get_stats' && params.by === undefined) await refuseEnforced(command, 'arguments_not_allowed', { engine });diff --git a/test/enforced-member-writes-off.test.ts b/test/enforced-member-writes-off.test.tsindex 97100f10d8..27a5f42a33 100644--- a/test/enforced-member-writes-off.test.ts+++ b/test/enforced-member-writes-off.test.ts@@ -1,34 +1,37 @@/**- * GST-2675: the brain setting access.enforced_member_writes, read by enforcedWritesRefused (src/cli/enforced-member.ts).+ * GST-2675: the brain setting access.enforced_member_writes, read by enforcedWritesMode (src/cli/enforced-member.ts).*- * 1. Protects: under enforced member mode a write refuses unless the brain's config says checked (or holds no value),- * and a config read that fails refuses too.- * 2. Fails when: a failed config read, an unknown value or refuse lets a member write through.+ * 1. Protects: under enforced member mode writes stay checked only when the brain's config says checked (or holds no+ * value); refuse_pages turns off page writes, and refuse, any other value and a failed config read turn off both+ * page writes and named-path git commit-push.+ * 2. Fails when: a failed config read, an unknown value or refuse reads as anything less strict than refuse.* 3. Existing coverage: test/enforced-member.serial.test.ts (every write as a real subprocess with the key set).* 4. Real seams: the engine's getConfig, faked here so the read can fail.*/import { describe, expect, test } from 'bun:test';import type { BrainEngine } from '../src/core/engine.ts';-import { ENFORCED_MEMBER_WRITES_KEY, enforcedWritesRefused } from '../src/cli/enforced-member.ts';+import { ENFORCED_MEMBER_WRITES_KEY, enforcedWritesMode } from '../src/cli/enforced-member.ts';const engineWith = (getConfig: (key: string) => Promise<string | null>) => ({ getConfig }) as unknown as BrainEngine;-describe('enforcedWritesRefused', () => {+describe('enforcedWritesMode', () => {test('reads access.enforced_member_writes from the brain config', async () => {const seen: string[] = [];- await enforcedWritesRefused(engineWith(async key => { seen.push(key); return null; }));+ await enforcedWritesMode(engineWith(async key => { seen.push(key); return null; }));expect({ key: ENFORCED_MEMBER_WRITES_KEY, seen }).toEqual({ key: 'access.enforced_member_writes', seen: ['access.enforced_member_writes'] });});- test('unset and checked allow checked writes; refuse, any other value and a failed read refuse', async () => {- const cases: Array<[string, () => Promise<string | null>, boolean]> = [- ['unset', async () => null, false],- ['checked', async () => 'checked', false],- ['refuse', async () => 'refuse', true],- ['unknown value', async () => 'chekced', true],- ['empty value', async () => '', true],- ['read fails', async () => { throw new Error('connection lost'); }, true],+ test('unset and checked keep writes checked; refuse_pages; refuse, any other value and a failed read are refuse', async () => {+ const cases: Array<[string, () => Promise<string | null>, string]> = [+ ['unset', async () => null, 'checked'],+ ['checked', async () => 'checked', 'checked'],+ ['refuse_pages', async () => 'refuse_pages', 'refuse_pages'],+ ['refuse_pages, spaced and upper case', async () => ' REFUSE_PAGES ', 'refuse_pages'],+ ['refuse', async () => 'refuse', 'refuse'],+ ['unknown value', async () => 'chekced', 'refuse'],+ ['empty value', async () => '', 'refuse'],+ ['read fails', async () => { throw new Error('connection lost'); }, 'refuse'],];- for (const [name, read, refused] of cases) expect({ name, refused: await enforcedWritesRefused(engineWith(read)) }).toEqual({ name, refused });+ for (const [name, read, mode] of cases) expect({ name, mode: await enforcedWritesMode(engineWith(read)) }).toEqual({ name, mode });});});diff --git a/test/enforced-member.serial.test.ts b/test/enforced-member.serial.test.tsindex b2c331e4ac..ba20026390 100644--- a/test/enforced-member.serial.test.ts+++ b/test/enforced-member.serial.test.ts@@ -534,6 +534,7 @@ for (const kind of testBackends()) {expect(texts.size).toBe(1);const [text] = [...texts];expect(text).toContain('Recovery: nothing was saved');+ expect(text).toContain('Why: This brain turned off member writes under this mode');expect(text).toContain('brain owner');for (const slug of ['notes/writes-off-new-example', PAGES.open.slug, PAGES.other.slug, 'notes', 'harbor']) expect({ slug, named: text!.includes(slug) }).toEqual({ slug, named: false });const json = await cli(['put', 'notes/writes-off-new-example', '--json'], { stdin: page('Writes off new') });@@ -545,8 +546,15 @@ for (const kind of testBackends()) {for (const value of ['chekced', 'REFUSE ']) {await setKey(value);const r = await cli(['tag', PAGES.open.slug, 'writes-off-tag']);- expect({ value, exit: r.exitCode, first: r.stderr.split('\n')[0] }).toEqual({ value, exit: 3, first: WRITES_OFF_FIRST });+ expect({ value, exit: r.exitCode, first: r.stderr.split('\n')[0], why: r.stderr.includes('turned off member writes') }).toEqual({ value, exit: 3, first: WRITES_OFF_FIRST, why: true });}+ await setKey('refuse_pages');+ for (const [args, stdin] of writes) {+ const r = await cli(args, { stdin });+ expect({ args: args.join(' '), exit: r.exitCode, first: r.stderr.split('\n')[0], why: r.stderr.includes('Why: This brain turned off member page writes under this mode') })+ .toEqual({ args: args.join(' '), exit: 3, first: WRITES_OFF_FIRST, why: true });+ }+ expect(await readAll()).toEqual(checkedReads);expect(await counts()).toEqual(before);await setKey('refuse');for (const [args, stdin] of writes.filter(([a]) => a[0] !== 'put' || a[1] === 'notes/writes-off-new-example')) {@@ -670,18 +678,41 @@ for (const kind of testBackends()) {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('access.enforced_member_writes refuse leaves git commit-push and sync as they are', async () => {- const set = await cli(['config', 'set', 'access.enforced_member_writes', 'refuse'], null);- expect({ exit: set.exitCode, err: set.exitCode === 0 ? '' : set.stderr }).toEqual({ exit: 0, err: '' });- try {- writeFileSync(join(checkout, 'notes', 'alice-git-refuse.md'), note('Alice git refuse'));- const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note under refuse', '--', 'notes/alice-git-refuse.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 under refuse');- const refused = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md']);- expect({ exit: refused.exitCode, first: refused.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'git commit-push') });+ test('access.enforced_member_writes: refuse closes named-path commit-push, refuse_pages keeps it; --pull, --dry-run and sync run under both', async () => {+ const setKey = async (value: string) => {+ const r = await cli(['config', 'set', 'access.enforced_member_writes', value], null);+ expect({ value, exit: r.exitCode, err: r.exitCode === 0 ? '' : r.stderr }).toEqual({ value, exit: 0, err: '' });+ };+ const WITHHELD = (command: string) => 'gbrain: ' + command + ' finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n';+ const stillRuns = async (mode: string) => {+ const pull = await cli(['git', 'commit-push', '--path', checkout, '--pull']);+ expect({ mode, exit: pull.exitCode, out: pull.stdout, err: pull.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('git commit-push') });+ const dry = await cli(['git', 'commit-push', '--path', checkout, '--dry-run', '-m', 'dry', '--', 'notes/alice-git-mode.md']);+ expect({ mode, exit: dry.exitCode, out: dry.stdout, err: dry.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('git commit-push') });const sync = await cli(['sync', '--source', 'repo-src', '--no-pull', '--no-embed']);- expect({ exit: sync.exitCode, out: sync.stdout, err: sync.stderr }).toEqual({ exit: 0, out: '', err: 'gbrain: sync finished; its output is withheld under GBRAIN_ENFORCED_MEMBER\n' });+ expect({ mode, exit: sync.exitCode, out: sync.stdout, err: sync.stderr }).toEqual({ mode, exit: 0, out: '', err: WITHHELD('sync') });+ };+ try {+ writeFileSync(join(checkout, 'notes', 'alice-git-mode.md'), note('Alice git mode'));+ await setKey('refuse');+ const headBefore = git('rev-parse', 'HEAD').trim();+ const texts = new Set<string>();+ for (const path of ['notes/alice-git-mode.md', 'notes/bob-git.md', 'notes/never-written-git.md']) {+ const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', path]);+ expect({ path, exit: r.exitCode, first: r.stderr.split('\n')[0], out: r.stdout }).toEqual({ path, exit: 3, first: WRITES_OFF_FIRST, out: '' });+ texts.add(r.stderr);+ }+ expect(texts.size).toBe(1);+ expect([...texts][0]).toContain('turned off member writes');+ expect(git('rev-parse', 'HEAD').trim()).toBe(headBefore);+ await stillRuns('refuse');+ await setKey('refuse_pages');+ const r = await cli(['git', 'commit-push', '--path', checkout, '-m', 'alice note under refuse_pages', '--', 'notes/alice-git-mode.md']);+ expect({ exit: r.exitCode, out: r.stdout, err: r.stderr }).toEqual({ exit: 0, out: '', err: WITHHELD('git commit-push') });+ expect(git('log', '--format=%s', '-1').trim()).toBe('alice note under refuse_pages');+ const hidden = await cli(['git', 'commit-push', '--path', checkout, '-m', 'x', '--', 'notes/bob-git.md']);+ expect({ exit: hidden.exitCode, first: hidden.stderr.split('\n')[0] }).toEqual({ exit: 3, first: FIRST(MEMBER, 'git commit-push') });+ await stillRuns('refuse_pages');} finally {const engine = await createEngine(config as never);await engine.connect(config as never);