Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
access rule add: refuse a reader list that leaves out the brain owner (GST-2698)
garrytan331e03688180
diff --git a/behavior-changes.d/access_rule_keeps_owner_gst2698.md b/behavior-changes.d/access_rule_keeps_owner_gst2698.mdnew file mode 100644index 0000000000..2f381c1b60--- /dev/null+++ b/behavior-changes.d/access_rule_keeps_owner_gst2698.md@@ -0,0 +1 @@+gbrain access rule add now refuses a reader list that leaves out the brain owner when one is set (gbrain access owner), the same refusal gbrain repair visibility --readers already gives (readers_omit_owner), because such a rule closes the folder or page to the owner's own keys. Add the owner to --readers, or pass --allow-without-owner when the owner should not read it. A group that holds the owner does not count. Rules already in place are not changed, and a brain with no owner set behaves as before.diff --git a/changelog.d/capy-access-rule-owner-check.md b/changelog.d/capy-access-rule-owner-check.mdnew file mode 100644index 0000000000..7b8861d234--- /dev/null+++ b/changelog.d/capy-access-rule-owner-check.md@@ -0,0 +1,10 @@+**`gbrain access rule add` no longer lets a hand-typed reader list lock the brain owner out of a folder.** When an owner is set, a rule whose `--readers` leaves the owner out is refused with `readers_omit_owner`, the same check and message `gbrain repair visibility --readers` already uses, and nothing is written. Pass `--allow-without-owner` when the owner really should not read it. A brain with no owner set is unchanged, and it works the same on a repo-less source (rules in the database) and a git source (`.gbrain/access.yml`).++<!-- behavior-change: access_rule_keeps_owner_gst2698 -->++### Itemized changes++- `src/commands/access-rules.ts`: `rule add` checks the owner before previewing or writing; new `--allow-without-owner` flag, named in `gbrain access --help`.+- `src/core/access/owner.ts`: the owner lookup and the `readers_omit_owner` error now live here and are shared with `src/core/repair/readers.ts`.+- Docs: `docs/guides/access-designations.md` and the setup skill name the flag.+- Tests: new `test/access-rule-owner-gst2698.test.ts` (refusal, override and no-owner case on a repo-less and a git source, PGLite and Postgres); two existing tests that rule a page away from the owner on purpose now pass `--allow-without-owner`.diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.mdindex d9f72b843f..2610d7aa23 100644--- a/docs/guides/access-designations.md+++ b/docs/guides/access-designations.md@@ -147,7 +147,9 @@ add --prefix <folder>/ --readers <list>` does the same for a folder, and `--slugat the source root, or one whose file left git, which a `visibility` edit cannot reach; upgrade every host that sharesthe brain first, because an older one stops syncing a git-backed source that holds a page rule). This is the boundary between people in ashared brain, and it binds the owner too: the owner reads such a page only when listed, unless the brain operator-turns on the owner opt-in (below). No grant or hatch relaxes it. Use it for a page that belongs to specific people in a shared brain; a single-user brain needs+turns on the owner opt-in (below). So when an owner is set, `gbrain access rule add` and `repair visibility --readers`+refuse a reader list that leaves the owner out (`readers_omit_owner`; a group that holds the owner does not count), and+`--allow-without-owner` accepts it when that is what you want. No grant or hatch relaxes it. Use it for a page that belongs to specific people in a shared brain; a single-user brain needsnone. The page's writers set it; on an existing page the brain host sets or removes it with`gbrain repair visibility --slug <page> --readers <list>` (or `--slugs-file`), which keeps the page's trust tier andchanges only that line ([how](repair.md)). Widening a folder rule waits for `gbrain access apply`. On a git-canonicaldiff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.mdindex 78bb3284f3..14a725da75 100644--- a/plugin/skills/setup/SKILL.md+++ b/plugin/skills/setup/SKILL.md@@ -40,7 +40,7 @@ Use the user's existing context; do not repeat choices they already made.| --- | --- || Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. || Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |-| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word). Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). || Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. || Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. || Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |diff --git a/skills/setup/SKILL.md b/skills/setup/SKILL.mdindex e6dab2ad0e..158a055976 100644--- a/skills/setup/SKILL.md+++ b/skills/setup/SKILL.md@@ -39,7 +39,7 @@ Use the user's existing context; do not repeat choices they already made.| --- | --- || Add memory inside Grok Bot | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`, the Bot runs in the vendor cloud), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in the Bot. No always-on machine: follow [Grok Bot](https://github.com/garrytan/gbrain/blob/master/docs/guides/grok-bot.md) and the isolated [setup helper](https://github.com/garrytan/gbrain/blob/master/docs/guides/in-agent-setup.md). Root: `/workspace/gbrain`, with data under `.gbrain`. || Add memory inside Muse | First choice: use the brain on your own computer over MCP — [remote-mcp](../remote-mcp/SKILL.md) publishes it (`--funnel`), then [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md) installs the private handoff in Muse. No always-on machine: follow [Muse](https://github.com/garrytan/gbrain/blob/master/docs/guides/muse.md). Either way, establish its durable user-files location first. Do not invent `MUSE.md`, a persistent path, or a native MCP mechanism. |-| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word). Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). |+| Memory for a bot that answers several people | `gbrain setup <harness> --serves several --members <id,...>`; ask the user who the people are, never guess. Relay key file paths, never keys, and the `open pages` lines: ask who reads each folder (`--labelled-only` only on their word); keep the owner in every `--readers` list, and pass `--allow-without-owner` only on their word. Fix a `setup_serves_several`, `requester_scope_required` or `credential_scope_required` refusal with its `fix`. Pass `--stdio-member <id>` (claude-code, codex) only for a harness one person uses: it binds that harness's entry alone; refused where OpenClaw or Hermes runs. [Guide](https://github.com/garrytan/gbrain/blob/master/docs/guides/setup.md#a-brain-that-serves-several-people). || Add memory to another existing agent | Follow [INSTALL_FOR_AGENTS.md](https://github.com/garrytan/gbrain/blob/master/INSTALL_FOR_AGENTS.md); the [coding-agent tutorial](https://github.com/garrytan/gbrain/blob/master/docs/tutorials/connect-coding-agent.md) covers Claude Code and Codex. || Connect an existing hosted brain | Follow [mcp-access](../mcp-access/SKILL.md) and [hosted harness access](https://github.com/garrytan/gbrain/blob/master/docs/guides/hosted-harness-access.md). Select native OAuth/PKCE or a private machine handoff for the intended harness. || Use the brain from other devices, apps or cloud agents over MCP | Follow [remote-mcp](../remote-mcp/SKILL.md): `gbrain mcp expose` publishes the local server on the Tailscale tailnet (Funnel only for cloud agents), then [mcp-access](../mcp-access/SKILL.md) / hosted access selects native OAuth or a private machine handoff for each consumer. |diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.jsonindex 8b6937202c..c21663ecd8 100644--- a/skills/skills.lock.history.json+++ b/skills/skills.lock.history.json@@ -1083,6 +1083,7 @@"a0f9d72565b489c4a60f6546b89218ea9efc307b397ac5ea22f3ed4c737f73f1","b73d9f9c93d419d812b39e47160790f8510bcd8564910b9f02aee51e673ad41f","c82b1e1b97e058991bc52287c24a26628d7d66bed409642023a20457e7f15f05",+ "d5250abf65d7fb822646232ed6a27a09ac4443377065b58182292023c6b3606a","d6b82f858e60699ff8c5ee82d61c94a98c2fbc7a852b5f74571e7ab3f0921139","f014513080eb81e90f0cc0203ca944698fdff250059be0267f0498c5b69c5416"],diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex cbf1bca7db..264cbc85d4 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -212,7 +212,7 @@"resolve-before-asking/routing-eval.jsonl": "bac1bcf30337f5255ef4ce1a2a8a2b38d58ebcd576503c483190c79ec6e69489","schema-author/SKILL.md": "38efb8b48399a2dc526d7084579aa265b2ab232882605bc2f86f6ba2869619f5","schema-unify/SKILL.md": "36259f1510fd693253535bd203e32db1bfa24aaae7278c7a2e8b7d6859022708",- "setup/SKILL.md": "427f8703034bf220b87698d0a6b66a74fe767180ba0bd9108d56e781facd679b",+ "setup/SKILL.md": "d5250abf65d7fb822646232ed6a27a09ac4443377065b58182292023c6b3606a","signal-detector/SKILL.md": "426a8a3b01a007dd25638e61adef510c18c3d9ce6f1c18ba3d77fdfcd3281d60","skill-autobench/SKILL.md": "29f5760dcfd823c5f7d4fb50a3cf4e36601b1b8125e57d6bf83645a41f97f613","skill-autobench/routing-eval.jsonl": "8d961ed6403b7e2f690948e4c18529d40f26f6f21064befc56d465966b1a9ec0",@@ -226,7 +226,7 @@"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e","skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb","skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",- "skills.lock.history.json": "3f5386a5c2fb876f5842a296e9206f247db37455751dd7a447f7cfa36a25c6fb",+ "skills.lock.history.json": "9743603c04e940a73e4757197c7d878adb736f0d42a53c0be0e25eb95de6bca9","smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5","soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8","storage-manifest/SKILL.md": "1debbefba61007a17cda1525496875d1edfde90642adf3ec031f25a71724807e",diff --git a/src/commands/access-rules.ts b/src/commands/access-rules.tsindex ef7428536e..66cfbf608d 100644--- a/src/commands/access-rules.ts+++ b/src/commands/access-rules.ts@@ -1,7 +1,7 @@/*** GBRA-218 (PR A2): `gbrain access rule|apply|resume`, the operator surface for folder rules.*- * gbrain access rule add --prefix <folder/> | --slug <page> --readers a,group:b [--raw-only] [--id <rule>] [--source <id>] [--yes] [--expect <rev>] [--operation <id>]+ * gbrain access rule add --prefix <folder/> | --slug <page> --readers a,group:b [--raw-only] [--allow-without-owner] [--id <rule>] [--source <id>] [--yes] [--expect <rev>] [--operation <id>]* gbrain access rule rm <rule> [--source <id>] [--yes] [--expect <rev>] [--operation <id>]* gbrain access rule list|status|history [--source <id>] [--operation <id>] [--limit <n>]* gbrain access rule revert --to <revision> [--source <id>] [--yes]@@ -28,7 +28,7 @@ import { heldRowsInVersions } from '../core/facts/fence-fact-append.ts';import { identityFor } from '../core/access/principals.ts';import { openTwins, openTwinsLines, OPEN_TWINS_PAGES, type OpenTwins } from '../core/access/open-twins.ts';import { boundCredentials, listGroups, listMembers } from '../core/access/members.ts';-import { ownerReadsRestrictedOn, ownerView } from '../core/access/owner.ts';+import { ownerReadsRestrictedOn, ownerView, readersOmitOwnerError, readersOwner } from '../core/access/owner.ts';import {appliedRules, applyApproved, getRevision, listRevisions, newOperationId, policyStatus, previewApply, proposeRevision, readAccessStore, resumePolicy,ensurePolicyState, type AccessStore, type ProposalResult, type RestampProgress,@@ -363,6 +363,10 @@ async function ruleCmd(engine: BrainEngine, sub: string | undefined, args: strinif (taken) throw opError('access_rule_invalid', `Rule id "${taken.id}" already names ${taken.prefix}, and ${r.rule.prefix} derives the same id.`, `Nothing was written. Name the new rule yourself: gbrain access rule add --id <rule> ${r.rule.prefix.endsWith('/') ? '--prefix' : '--slug'} ${r.rule.prefix} --readers <list>.`);const clash = base.find(b => b.prefix === r.rule.prefix && b.id !== r.rule.id);if (clash) throw opError('access_rule_invalid', `Rule "${clash.id}" already covers ${r.rule.prefix}.`, `Nothing was written. Change that rule's readers instead: gbrain access rule add --id ${clash.id} ${r.rule.prefix.endsWith('/') ? '--prefix' : '--slug'} ${r.rule.prefix} --readers <list>.`);+ const { owner, live } = await readersOwner(engine);+ if (owner && !r.rule.readable_by.includes(`member:${owner}`) && !args.includes('--allow-without-owner')) {+ throw readersOmitOwnerError(owner, live, r.rule.readable_by, r.rule.prefix.endsWith('/') ? `the pages under ${r.rule.prefix}` : `the page ${r.rule.prefix}`);+ }desired = sortRules([...base.filter(b => b.id !== r.rule.id), r.rule]);message = `access: rule ${r.rule.id} on ${r.rule.prefix} readable by ${r.rule.readable_by.map(reader).join(', ')}${coversDerived(r.rule) ? '' : ' (raw only)'}`;} else if (sub === 'rm') {diff --git a/src/commands/access.ts b/src/commands/access.tsindex 05dcc6e874..fdb5804524 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -98,10 +98,12 @@ Serves several people (GST-363):pages labelled for it (never the owner)Folder rules (one rulebook per source; the database store on a repo-less source, .gbrain/access.yml on a git one):- gbrain access rule add --prefix <folder/> | --slug <page> --readers a,group:b [--raw-only] [--id <rule>] [--source <id>] [--yes]+ gbrain access rule add --prefix <folder/> | --slug <page> --readers a,group:b [--raw-only] [--allow-without-owner] [--id <rule>] [--source <id>] [--yes]Preview first; narrowing applies at once. --raw-only: the rule keepsits pages, not their derived pages and facts (transcripts; a widening- held for gbrain access apply when it changes an existing rule)+ held for gbrain access apply when it changes an existing rule).+ Readers that leave out the brain owner refuse readers_omit_owner;+ --allow-without-owner accepts themgbrain access rule rm <rule> [--source <id>] [--yes]A widening: recorded and held until gbrain access applygbrain access rule list|status|history [--source <id>] [--operation <id>]diff --git a/src/core/access/owner.ts b/src/core/access/owner.tsindex b39af636a2..7ccc246611 100644--- a/src/core/access/owner.ts+++ b/src/core/access/owner.ts@@ -15,7 +15,7 @@ import type { BrainEngine } from '../engine.ts';import { OWNER_MEMBER_KEY, OWNER_READS_RESTRICTED_KEY } from '../search/private-visibility.ts';import { hostOnlyError } from '../ops/op-fix.ts';import { opError, type OperationError } from '../ops/contract.ts';-import { ACCESS_ID_RE } from './principals.ts';+import { ACCESS_ID_RE, normalizePrincipal } from './principals.ts';import { boundCredentials, memberIdentity } from './members.ts';import type { CredentialRef } from './members.ts';@@ -51,6 +51,29 @@ export async function ownerView(engine: BrainEngine): Promise<OwnerView> {}}+/**+ * GST-2698: the owner a reader list must name: the live owner, else a configured owner that is a member id but not+ * enabled now (live false). Null when no owner is set, so a brain without an owner never refuses a list.+ */+export async function readersOwner(engine: BrainEngine): Promise<{ owner: string | null; live: boolean }> {+ const view = await ownerView(engine);+ if (view.owner) return { owner: view.owner, live: true };+ const inactive = view.inactive ? normalizePrincipal(view.inactive.value) : null;+ return { owner: inactive?.startsWith('member:') ? inactive.slice('member:'.length) : null, live: false };+}++/**+ * GST-2476, GST-2698: readers that leave out the owner close `what` to the owner's own keys on every read path+ * (access/caller.ts), so `gbrain repair visibility --readers` and `gbrain access rule add` refuse such a list unless+ * --allow-without-owner. A group that holds the owner does not count. `principals` are normalized (member:<id>, group:<id>).+ */+export function readersOmitOwnerError(owner: string, live: boolean, principals: string[], what: string): OperationError {+ const shown = principals.map(p => p.startsWith('member:') ? p.slice('member:'.length) : p);+ return opError('invalid_params', 'These readers leave out the brain owner "' + owner + '"' + (live ? '' : ' (configured, not enabled now)') + ', so the owner\'s own keys could no longer read ' + what + '; nothing was written. Name the owner, or pass --allow-without-owner.',+ 'Add the owner to the list (--readers ' + [...shown, owner].join(',') + '), or pass --allow-without-owner if the owner should not read it. A group that holds the owner does not count.',+ { reason: 'readers_omit_owner' });+}+/** GST-2490: is access.owner_reads_restricted on? Unset, anything but '1', or unreadable is off (nothing widens). */export async function ownerReadsRestrictedOn(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {try {diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8edb3dd05d..31c924bfa8 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,7 +14,7 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--kind', '--labelled-only', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--no-open-pages', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--allow-without-owner', '--approved', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--attest-sources', '--bind-token', '--brain', '--client', '--dry-run', '--email', '--expect', '--file', '--grant-types', '--groups', '--help', '--http', '--id', '--if-version', '--json', '--kind', '--labelled-only', '--limit', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--name', '--no-open-pages', '--operation', '--operations', '--prefix', '--private-pages', '--qm', '--raw-only', '--readers', '--reads-unscoped', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--slug', '--source', '--sources', '--stdio-member', '--takes-holders', '--to', '--token', '--tools-json', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],diff --git a/src/core/repair/readers.ts b/src/core/repair/readers.tsindex a80850d89d..4bcbcf672a 100644--- a/src/core/repair/readers.ts+++ b/src/core/repair/readers.ts@@ -21,7 +21,7 @@ import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';import { opError } from '../ops/contract.ts';import { getMember, listGroups } from '../access/members.ts';-import { ownerView } from '../access/owner.ts';+import { readersOmitOwnerError, readersOwner } from '../access/owner.ts';import { normalizePrincipal, normalizeReaders } from '../access/principals.ts';import { READERS_KEY, type LabelEdit } from '../persistence/label-edit.ts';import { digest } from '../persistence/digest.ts';@@ -59,9 +59,7 @@ const same = (a: string[] | null, b: string[] | null) => JSON.stringify(a) === J* group, and a list without the owner unless the flag is passed; nothing is written before this passes.*/async function checkedReaders(engine: BrainEngine, request: ReadersRequest): Promise<{ readers: string[] | null; owner: string | null }> {- const view = await ownerView(engine);- const inactive = view.inactive ? normalizePrincipal(view.inactive.value) : null;- const owner = view.owner ?? (inactive?.startsWith('member:') ? shown(inactive) : null);+ const { owner, live } = await readersOwner(engine);if (request.readers.trim() === 'none') return { readers: null, owner };const entries = request.readers.split(',').map(entry => entry.trim()).filter(Boolean);if (!entries.length) throw invalid('--readers names no reader.', 'Pass member ids and group:<id>, comma-separated (e.g. --readers alice-example,group:team-a), or none to remove the readers.');@@ -84,11 +82,7 @@ async function checkedReaders(engine: BrainEngine, request: ReadersRequest): Promember ? member.status : 'unknown');}}- if (owner && !principals.includes('member:' + owner) && !request.allowWithoutOwner) {- throw invalid('These readers leave out the brain owner "' + owner + '"' + (view.owner ? '' : ' (configured, not enabled now)') + ', so the owner\'s own keys could no longer read the page; nothing was written. Name the owner, or pass --allow-without-owner.',- 'Add the owner to the list (--readers ' + [...principals.map(shown), owner].join(',') + '), or pass --allow-without-owner if the owner should not read it. A group that holds the owner does not count.',- 'readers_omit_owner');- }+ if (owner && !principals.includes('member:' + owner) && !request.allowWithoutOwner) throw readersOmitOwnerError(owner, live, principals, 'the page');return { readers: principals.map(shown), owner };}diff --git a/test/access-rule-owner-gst2698.test.ts b/test/access-rule-owner-gst2698.test.tsnew file mode 100644index 0000000000..33bbec0e3a--- /dev/null+++ b/test/access-rule-owner-gst2698.test.ts@@ -0,0 +1,97 @@+/**+ * GST-2698 (GST-2670 decision d2): `gbrain access rule add` refuses a reader list that leaves out the brain owner, as+ * `gbrain repair visibility --readers` already does (readers_omit_owner), because such a rule closes the folder to the+ * owner's own keys.+ *+ * 1. Protects: with an owner set, a rule whose readers do not name the owner refuses on the preview and on --yes, with+ * nothing written; --allow-without-owner accepts it; a list that names the owner applies; a brain with no owner set+ * is unchanged.+ * 2. Fails when: a rule without the owner is written without the flag, the flag is ignored, or a brain with no owner+ * starts refusing.+ * 3. Real seams: the gbrain access rule CLI module on a repo-less source (database store) and on a managed git source+ * (.gbrain/access.yml through the door), PGLite and Postgres.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runAccessRules } from '../src/commands/access-rules.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++async function cli(engine: BrainEngine, args: string[]): Promise<any> {+ const lines: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });+ try { await runAccessRules(engine, args[0]!, [...args.slice(1), '--json'], true); } finally { spy.mockRestore(); }+ const text = lines.join('\n');+ try { return JSON.parse(text); } catch { throw new Error(`gbrain access ${args.join(' ')} printed no JSON: ${text}`); }+}++async function members(engine: BrainEngine, owner: string | null): Promise<void> {+ for (const id of ['owner-example', 'alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1) ON CONFLICT DO NOTHING', [id]);+ if (owner) await engine.setConfig('access.owner_member', owner);+ else await engine.executeRaw("DELETE FROM config WHERE key = 'access.owner_member'");+}++const refusal = (engine: BrainEngine, args: string[]) => cli(engine, args).then(() => null, (e: any) => ({ code: e.code, reason: e.reason, message: e.message, suggestion: e.suggestion }));+const ruleIds = async (engine: BrainEngine) => (await cli(engine, ['rule', 'list'])).rules.map((r: { id: string }) => r.id).sort();++/** The three cases on one source: refusal (preview and --yes), the override, the owner named, and no owner set. */+async function ownerCases(engine: BrainEngine, after: (expected: string[]) => void | Promise<void>): Promise<void> {+ await members(engine, 'owner-example');+ for (const yes of [[], ['--yes']]) {+ expect(await refusal(engine, ['rule', 'add', '--prefix', 'team/', '--readers', 'alice-example,bob-example', ...yes])).toEqual({+ code: 'invalid_params', reason: 'readers_omit_owner',+ message: 'These readers leave out the brain owner "owner-example", so the owner\'s own keys could no longer read the pages under team/; nothing was written. Name the owner, or pass --allow-without-owner.',+ suggestion: 'Add the owner to the list (--readers alice-example,bob-example,owner-example), or pass --allow-without-owner if the owner should not read it. A group that holds the owner does not count.',+ });+ }+ expect(await refusal(engine, ['rule', 'add', '--slug', 'notes/one-example', '--readers', 'alice-example', '--yes'])).toMatchObject({ reason: 'readers_omit_owner', message: expect.stringContaining('read the page notes/one-example;') });+ expect(await ruleIds(engine)).toEqual([]);+ await after([]);++ expect((await cli(engine, ['rule', 'add', '--prefix', 'team/', '--readers', 'alice-example,owner-example', '--yes'])).state).toBe('applied');+ expect((await cli(engine, ['rule', 'add', '--prefix', 'alice/', '--readers', 'alice-example', '--allow-without-owner', '--yes'])).state).toBe('applied');+ expect(await ruleIds(engine)).toEqual(['alice', 'team']);++ await members(engine, null);+ expect((await cli(engine, ['rule', 'add', '--prefix', 'bob/', '--readers', 'bob-example', '--yes'])).state).toBe('applied');+ expect(await ruleIds(engine)).toEqual(['alice', 'bob', 'team']);+ await after(['alice', 'bob', 'team']);+}++for (const backend of testBackends()) {+ describe(`access rule add keeps the owner in the readers on a repo-less brain (${backend})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const pglite = new PGLiteEngine(); await pglite.connect({ engine: 'pglite' } as never); await pglite.initSchema(); engine = pglite; close = () => pglite.disconnect(); }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }, 180_000);+ afterAll(async () => { await close?.(); });++ test('refuses a list without the owner, accepts it with --allow-without-owner, and a brain with no owner is unchanged (database store)', async () => {+ await ownerCases(engine, async () => {+ expect((await cli(engine, ['rule', 'status'])).store).toBe((await ruleIds(engine)).length ? 'database' : null);+ });+ }, 120_000);+ });++ describe(`access rule add keeps the owner in the readers on a git source (${backend})`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), 'archive/\n'); durableGitRepo(root, ['.gitignore']); };++ test('refuses a list without the owner before access.yml is written, and the override and no-owner rules land in it', () => managedBrain(async ({ engine, root }) => {+ const file = join(root, '.gbrain', 'access.yml');+ await ownerCases(engine, ids => {+ if (!ids.length) return void expect(existsSync(file)).toBe(false);+ const text = readFileSync(file, 'utf8');+ for (const id of ids) expect(text).toContain(`id: ${id}`);+ });+ }, { databaseUrl, setup }), 240_000);+ });+}diff --git a/test/folder-holding-page-gst2492.test.ts b/test/folder-holding-page-gst2492.test.tsindex b4b2e26bd4..c46c027cdf 100644--- a/test/folder-holding-page-gst2492.test.ts+++ b/test/folder-holding-page-gst2492.test.ts@@ -366,12 +366,12 @@ for (const backend of testBackends()) describe(`[${backend}] the folder-rule holWHERE p.source_id = 'default' AND p.slug = $1 AND v.timeline IS NULL ORDER BY v.id`, [HOLD]);const untimed = await nullTimelines();const before = await versionBodies(engine, HOLD);- const preview = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--source', 'default', '--json']);+ const preview = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--allow-without-owner', '--source', 'default', '--json']);const carrying = before.filter(v => v.body.includes(claim)).length;expect(carrying).toBeGreaterThan(0);// The preview counts what the apply's receipt records: the versions carrying the row now, plus the one the move saves.expect(preview.held_versions_editing).toEqual({ rows: carrying + 1, versions: carrying + 1, pages: [{ slug: HOLD, rows: carrying + 1, versions: carrying + 1 }] });- const applied = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--source', 'default', '--yes', '--expect', String(preview.expect), '--json']);+ const applied = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--allow-without-owner', '--source', 'default', '--yes', '--expect', String(preview.expect), '--json']);expect(applied.held_facts).toEqual({ moved: 1, unmovable: [] });await settleManagedGitEffects(engine);const after = new Map((await versionBodies(engine, HOLD)).map(v => [v.id, v.body]));@@ -397,7 +397,7 @@ for (const backend of testBackends()) describe(`[${backend}] the folder-rule hol// Git history is never rewritten: the shared page's earlier commit still holds the row.expect(git(root, 'log', '-p', '--format=%H', '--', `${HOLD}.md`)).toContain(claim);// A second apply finds nothing to move and edits nothing.- const again = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--source', 'default', '--json']);+ const again = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--allow-without-owner', '--source', 'default', '--json']);expect(again.held_versions_editing).toEqual({ rows: 0, versions: 0 });expect((await cli(engine, ['resume', '--source', 'default', '--json'])).held_facts).toBeUndefined();expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved ?? 0).toBe(0);diff --git a/test/label-repair-derived-stamps-gst2603.test.ts b/test/label-repair-derived-stamps-gst2603.test.tsindex 23d3fee294..6e5e6d4c9c 100644--- a/test/label-repair-derived-stamps-gst2603.test.ts+++ b/test/label-repair-derived-stamps-gst2603.test.ts@@ -316,7 +316,7 @@ for (const backend of testBackends()) describe('[' + backend + '] label repairsexpect(applied.applied).toBe(1);const lines: string[] = [];const spy = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); });- try { await runAccessRules(engine, 'rule', ['add', '--slug', 'notes/ruled-example', '--readers', 'alice-example', '--source', 'default', '--yes', '--json'], true); } finally { spy.mockRestore(); }+ try { await runAccessRules(engine, 'rule', ['add', '--slug', 'notes/ruled-example', '--readers', 'alice-example', '--allow-without-owner', '--source', 'default', '--yes', '--json'], true); } finally { spy.mockRestore(); }expect(JSON.parse(lines.join(NL)).state).toBe('applied');expect((await row(engine, 'notes/labelled-example')).frontmatter.visibility).toBe('private');expect((await row(engine, 'notes/ruled-example')).frontmatter.visibility).toBeUndefined();@@ -346,7 +346,7 @@ for (const backend of testBackends()) describe('[' + backend + '] label repairsconst rules = async (engine: BrainEngine, argv: string[]) => {const lines: string[] = [];const spy = spyOn(console, 'log').mockImplementation((...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); });- try { await runAccessRules(engine, 'rule', [...argv, '--json'], true); } finally { spy.mockRestore(); }+ try { await runAccessRules(engine, 'rule', [...argv, '--allow-without-owner', '--json'], true); } finally { spy.mockRestore(); }return JSON.parse(lines.join(NL));};diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex a4716d57ef..55d9c75452 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -35,6 +35,7 @@ test/access-page-rule-fileless.test.tstest/access-qm-actor.test.tstest/access-raw-only-rules.test.tstest/access-room.test.ts+test/access-rule-owner-gst2698.test.tstest/access-token-grant-columns.test.tstest/access-ungranted-member-writes.test.tstest/access-writes.test.ts