Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(access): brain owner reads private pages; repair private-labels; access designations doc (GST-2059)
garrytand10ab46d035f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8cadb056cf..400a207174 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**The brain owner's own agents now read the whole personal brain, and pages stamped `access: private` by default can be cleared in reviewed batches.** On a single-user brain, writer templates stamped `access: private` on ordinary research and ops pages, and every remote caller got `not_found` for them, the owner's own agent included. `gbrain access owner set <member>` now names the owner (config `access.owner_member`, database state, so repo-less brains work the same). Every token, OAuth client or stdio server bound to that member reads `visibility: private` pages, privacy-alias pages, derived and pinned-question pages and private facts through `get_page`, `search`, `query`, `recall` and the other page reads, within its source grant. `readable_by` and folder rules still bind it, a shared-room audience gets no relaxation, and other members, unbound and public callers read exactly as before. `gbrain repair private-labels` previews the existing labels with counts per category, keeps real restrictions, and clears the over-stamped ones in reviewed, recorded, reversible batches. The bulk-ingestion page template no longer writes an `access:` line, and docs/guides/access-designations.md defines every designation.++### Itemized changes++- `src/core/access/owner.ts` (new), `src/commands/access.ts`: `gbrain access owner [set <member>|clear]`; the member must be enabled; `gbrain access check --token <name>` reports `owner`.+- `src/core/access/caller.ts`, `src/core/search/private-visibility.ts`: `CallerAccess.owner`, set when the credential's live member is the owner and no audience other than the owner is asserted; the owner reads with privacy relaxed (member access stays mandatory); the request's config snapshot carries the owner key; `_meta.access.relaxation` gains `owner`.+- `src/core/ops/facts.ts`: remote `recall` returns private facts to the owner.+- `src/cli/as-preview.ts`: `--as <owner>` previews the owner's view.+- `src/core/repair/private-labels.ts` (new), `src/commands/repair-private-labels.ts` (new): `gbrain repair private-labels`, explicit-only and preview-bound; classes `alias`, `alias-and-visibility`, `git-publish` (named only) and `restore`; a ledger under the gbrain home records each change.+- Skills and docs: `skills/conventions/page-privacy.md` (new), `skills/bulk-ingestion` (template), `skills/brain-ops`, `skills/_AGENT_README.md`, `skills/frontmatter-guard`; `docs/guides/access-designations.md` (new), linked from multi-source brains, company brain, page anatomy and brains-and-sources; `docs/protocol/MCP_META_CHANNELS.md`.+- Tests: `test/access-owner-reads.test.ts`, `test/repair-private-labels.test.ts`.+## [0.60.620.0] - 2026-11-09**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.mdindex 9f3384bd47..f29345cd5c 100644--- a/docs/architecture/brains-and-sources.md+++ b/docs/architecture/brains-and-sources.md@@ -352,7 +352,7 @@ fail-closed and tested:(federated grant array > scalar source floor > nothing). A caller without agrant for a source cannot read its pages, chunks, or edges.- **Facts visibility** — facts carry `private`/`world` visibility; remote- callers see `world` only.+ callers see `world` only, except the brain owner's `recall`.- **Takes holders** — per-token allow-lists (`gbrain auth permissions <token>set-takes-holders ...`) scope which held takes a remote caller sees.- **Write-side slug fences** — a client bound to slug prefixes can only write@@ -371,9 +371,12 @@ The exact frontmatter value `private` hides that concrete page row;derived pages: an extracted atom or synthesized concept with no `visibility`is private, an atom whose origin page is private is hidden, and so is asynthesized concept built from a private atom. Trusted local CLI callers-retain access. Operator settings can opt out of private-page+retain access, and so does a credential bound to the brain owner+(`gbrain access owner set <member>`). Operator settings can opt out of private-pagefiltering, so source grants remain an independent boundary: keep content in anungranted source when remote callers must have no access to that source.+Every designation, who reads it and when to use it:+[access designations](../guides/access-designations.md).## Further readingdiff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.mdnew file mode 100644index 0000000000..f4a1eff620--- /dev/null+++ b/docs/guides/access-designations.md@@ -0,0 +1,132 @@+# Access designations: what each one means++This is the one definition of every access and visibility designation gbrain honours: what each one does to+retrieval, when a writer should use it, and who may set or clear it. The code that enforces it is+`src/core/search/private-visibility.ts` (privacy), `src/core/access/` (members, folder rules, the owner) and+`src/core/facts/visibility.ts` (facts). When this page and the code disagree, the code is right and this page is a bug.++**The default for an ordinary page is no designation.** Research notes, project and ops pages, people and company+pages, meeting notes you took and summaries of world pages carry no `visibility`, no `access` and no+`readable_by`. A personal brain should have very little marked private.++## Who reads what++Five kinds of caller read a brain:++- **Local CLI** on the brain host (`remote = false`). Reads everything.+- **The owner**: a remote credential (token or OAuth client) or stdio server bound to the member named by+ `gbrain access owner set <member>` (config `access.owner_member`). Bind each of the owner's agents, delegates and+ sub-agents included, with `gbrain auth rescope --token <name> --member <owner>` (stdio: `gbrain config set+ mcp.stdio_member <owner>`). On a single-user brain this is how the owner's own agent reads the whole brain.+- **Other members**: credentials bound to any other enabled member.+- **Public or unbound callers**: credentials bound to no member, and audiences that include a guest.+- **Shared rooms**: a shared agent speaking for an audience of several people (`X-Gbrain-On-Behalf-Of` /+ `_meta.on_behalf_of` with more than one entry, a group or a guest), and attested QM calls.++| Designation | Local CLI | Owner and the owner's bound delegates | Other members | Public or unbound | Shared rooms |+|---|---|---|---|---|---|+| none (the default) | reads | reads | reads | reads | reads |+| `visibility: private` | reads | reads | hidden | hidden | hidden |+| privacy alias (`access: private`, ...) with no `visibility` | reads | reads | hidden | hidden | hidden |+| derived page with no `visibility` (atom, pinned question, synthesized concept) | reads | reads | hidden | hidden | hidden |+| derived from a private page (lineage) | reads | reads | hidden | hidden | hidden |+| `pinned_question` | reads | reads | hidden | hidden | hidden |+| `readable_by: [...]` | reads | only when listed | only when listed | hidden | only when every entry is listed |+| folder rule (`gbrain access rule`) | reads | only when listed | only when listed | hidden | only when every entry is listed |+| derived from a `readable_by` page | reads | hidden | hidden | hidden | hidden |+| fact `visibility: private` | reads | `recall` reads | hidden | hidden | hidden |++"Hidden" means the same `not_found` a missing page gets, on every read path (get_page, search, query, recall, lists,+links, timelines, versions). The owner reads through `get_page`, `search`, `query`, `recall` and the other page+reads in every source its grant reads; the owner's source grant still bounds which sources those are. Facts outside+`recall` (hot memory, turn context, context packs) stay world-only for every remote caller, the owner included.++Two grants relax privacy for callers that are not the owner, and both are operator decisions:+`gbrain auth rescope --private-pages granted-sources` (private pages in the sources that grant names) and the+escape hatches `GBRAIN_REMOTE_PRIVATE_PAGES=1` / `gbrain config set search.remote_private_pages visible` (every+remote caller). Neither relaxes `readable_by` or folder rules, and neither reaches a shared-room audience.++`gbrain access check --token <name>` reports whether a credential reads as the owner, and+`gbrain <operation> --as <member>` previews a member's view, the owner's included. Every remote response names the+relaxation it was answered under in `_meta.access.relaxation` (`none`, `granted_sources`, `operator` or `owner`).++## Each designation++### No designation++A page with no `visibility`, no privacy alias and no `readable_by` is world: every caller entitled to its source+reads it. Use it for everything that is not one of the cases below. Anyone who may write the page may leave it so.++### `visibility: private`++Hides the page from every remote caller except the owner (and the two operator grants above). Facts, chronicle+events and timeline rows derived from it are private too. On a source with `canonical: git` a private page is+database-only: its bytes never enter Git history.++Use it only when the content genuinely needs it:+- another person's private information shared with you in confidence (a DM, someone's health or money details);+- something written for one shared room that must not reach the others;+- a page the owner explicitly asked to keep private.++Connectors set it for content that is private at its source: private Slack channels, private or confidential+calendar events, private meetings, and sources added with `--visibility private`.++Who sets it: any writer of the page, local or remote. Who clears it: the owner or the brain operator, on purpose,+on the brain host (an edit through `put_page`, a git edit, or `gbrain repair private-labels`). A remote writer+cannot rewrite a page its write policy hides, so an agent cannot clear a label it cannot see. Clearing widens what+other members and public callers read; do it only on the owner's ask.++### Privacy aliases: `access` and `confidentiality`++`access: private|restricted|confidential` and `confidentiality: confidential|secret|private|restricted` on a page+with no `visibility` read exactly like `visibility: private` (unless the operator turned+`visibility.honor_aliases` off). They exist so imported pages that already carry such a field stay private.++Writers never add them to new pages: write `visibility: private` when a page needs privacy, and nothing otherwise.+`gbrain repair private-labels` previews and clears `access: private` labels that were stamped on ordinary pages, and+keeps `restricted`, `confidential` and `confidentiality` as real restrictions.++### Derived pages and lineage++These rules follow the origin, so nobody writes them by hand:+- an extracted atom, a pinned-question page and a synthesized concept with no `visibility` read as private (their+ origin may be a private transcript);+- an atom whose origin page is private, a concept with a private input, a chronicle event from a private meeting,+ and any page whose `derived_from` names a private page are private whatever their own field says;+- anything derived from a page that names `readable_by` is hidden from every remote caller.++`gbrain repair visibility` stamps the explicit value on derived pages (tighten-only). The owner reads them all.++### `pinned_question`++Pinned-question pages are the owner's own and read as private. The owner reads them; a `--private-pages granted-sources` grant never widens them.++### `readable_by` and folder rules (member access)++`readable_by: [alice-example, group:team-a]` keeps a page to the members and groups it lists; `gbrain access rule+add --prefix <folder>/ --readers <list>` does the same for a folder. This is the boundary between people in a+shared brain, and it binds the owner too: the owner reads such a page only when listed. No grant, hatch or owner+binding relaxes it. Use it for a page that belongs to specific people in a shared brain; a single-user brain needs+none. The page's writers set it; widening a folder rule waits for `gbrain access apply`. See+[company brain, Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape).++### Fact visibility (`private` | `world`)++Each fact row has its own visibility. `remember` defaults to `world`, except into a private page or under an+explicit private `facts.default_visibility`; extracted facts follow `facts.default_visibility` (private when unset)+and are never wider than their page. Remote `recall` returns private facts to the owner only.++### The owner (`gbrain access owner`)++`gbrain access owner set <member>` names the member who owns the brain; it must be an enabled member+(`gbrain access member add <id>` first). Only the local CLI sets or clears it, and everything lives in the+database, so a repo-less brain works the same. The owner relaxation applies to a credential bound to that member+when it speaks for itself (no audience, or an audience of the owner alone); never to a shared-room audience or an+attested call. `gbrain access owner clear` turns it off.++## Related++- [Multi-source brains](multi-source-brains.md): sources and grants.+- [Company brain](../tutorials/company-brain.md): members, groups and `readable_by`.+- [What confines remote callers](../architecture/brains-and-sources.md#what-confines-remote-callers-and-what-does-not).+- [Page anatomy](page-anatomy.md): every frontmatter field.diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex 4e0a19a4e9..d5085cda6f 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -263,6 +263,10 @@ who may read it, before any member's bot connects:whose declared lineage is private; pinned questions stay owner-only.`--private-pages none` hides them again on the next request, and`gbrain auth list` shows each token's setting.+- **On a personal brain, name the owner instead.** `gbrain access owner set+ <member>` lets every credential bound to that member read the private pages+ in all the sources its grant reads. What each designation means for each+ caller: [access designations](access-designations.md).> **Warning: one shared source has no boundary inside it.** A bot that answers> everyone with one unscoped token over a single source exposes everything indiff --git a/docs/guides/page-anatomy.md b/docs/guides/page-anatomy.mdindex b24ae52828..180993be80 100644--- a/docs/guides/page-anatomy.md+++ b/docs/guides/page-anatomy.md@@ -63,7 +63,7 @@ doesn't know. These are the ones it reads:| `tags` | A list of tags. || `aliases` | Other names for the page. Entity lookup (`entity`, `recall <name>`, `remember --entity <name>`) and `gbrain whois` match them. A wikilink resolves by slug or file name, so write `[[people/alice-example]]` for a dependable link. || `email`, `emails` | Exact identity for `gbrain whois`. |-| `visibility` | `private` hides the page from remote (MCP) callers by default and keeps facts derived from it private; on a [git-canonical](../designs/GIT_CANONICAL_MEMORY.md) source a private page is never committed. A page without `visibility` is normally world, but some are private anyway: privacy aliases such as `access: private`, derived pages whose origin is private, and pinned-question pages. See [what confines remote callers](../architecture/brains-and-sources.md#what-confines-remote-callers-and-what-does-not). |+| `visibility` | `private` hides the page from remote (MCP) callers by default and keeps facts derived from it private; on a [git-canonical](../designs/GIT_CANONICAL_MEMORY.md) source a private page is never committed. A page without `visibility` is normally world, but some are private anyway: privacy aliases such as `access: private`, derived pages whose origin is private, and pinned-question pages. The brain owner's credentials read them all. Write it only when the content needs it: [access designations](access-designations.md). || `status` | A free-form state such as `draft` or `archived`, returned on every search row. || `event_date`, `date`, `published`, `created` | The page's content date (`effective_date`), used by `--since`/`--until` and recency. Precedence: `event_date`, `date`, `published`, a leading `YYYY-MM-DD` in the file name, then `created` (or `created_at`, `date_created`). Under `daily/` and `meetings/` the file name comes first. || `slug` | Optional. When present it must name the same page as the path, or the write is refused and sync holds the file ([`frontmatter_slug_conflict`](write-refusals.md#frontmatter_slug_conflict)). |diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex 864420110a..a6bf416196 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -33,7 +33,7 @@ shape for it.| `brain_hot_memory` | dispatch `metaHook` on stdio and HTTP (`getBrainHotMemoryMeta`, [details](#brain_hot_memory)) | Hot-memory facts relevant to the call; each fact carries `trust_tier` and `origin`, and `suppressed` (`{withheld, review}`, present only when non-zero) counts unconfirmed agent-written facts activation control withheld, never their content || `degraded` | dispatch (`src/core/degraded-stamp.ts`), on every transport | `{reasons: [...]}`: present only when the result is partial or degraded; sorted, unique stable codes ([AGENT_OPERATOR_v1.md, Degraded stamp](AGENT_OPERATOR_v1.md#degraded-stamp)). Mirrored as the last content block, `[gbrain degraded: <codes>] …` || `retrieval` | `search`/`query` op handlers; `recall` and `find_experts` emit `{degraded[]}` when their page search degraded | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?, parts_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) |-| `access` | dispatch (`appliedAccessSummary`, `src/core/access/caller.ts`), every remote response that reached the operation | The view the call was answered under: `member` and `groups` it read as (null and `[]` for an unbound caller or an audience of several entries), `audience` (the normalized `on_behalf_of` principals, or null), `policy_rev` (each source's applied folder-rule revision; null on a brain with no restriction), `relaxation` (`none`, `granted_sources` or `operator`: what relaxed `visibility: private`). `whoami` returns the same object as `access.applied`. An attested call adds `actor` (`{system}`); an unlinked `memory_recall` carries `code: "actor_unlinked"`, `member: null` and the id as sent. |+| `access` | dispatch (`appliedAccessSummary`, `src/core/access/caller.ts`), every remote response that reached the operation | The view the call was answered under: `member` and `groups` it read as (null and `[]` for an unbound caller or an audience of several entries), `audience` (the normalized `on_behalf_of` principals, or null), `policy_rev` (each source's applied folder-rule revision; null on a brain with no restriction), `relaxation` (`none`, `granted_sources`, `operator` or `owner`: what relaxed `visibility: private`; `owner` is a credential bound to the brain owner, see [access designations](../guides/access-designations.md)). `whoami` returns the same object as `access.applied`. An attested call adds `actor` (`{system}`); an unlinked `memory_recall` carries `code: "actor_unlinked"`, `member: null` and the id as sent. || `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]`: a parameter a read ignored. This is the only place the warning appears; no content block or notice carries it, so a harness that stores tool output in its turns never stores it (writes refuse unknown parameters instead). || `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 749782ca4d..ab089384c0 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -130,7 +130,7 @@ gbrain access check --token alice-laptop # what this credential can reagbrain access who-can-read notes/renewal-notes # the members and groups a page admits```-A remote caller whose credential is bound to a listed member (directly or through a group) reads the page on every read path; every other remote caller, including an unbound token, an unbound stdio server, a bot with `--private-pages granted-sources` and an operator escape hatch (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), gets the same `not_found` as for a page that does not exist. `readable_by` only narrows: a `visibility: private` page stays private to a listed member unless the member's credential also has `--private-pages granted-sources`. A malformed `readable_by` reads as nobody. A page derived from a restricted page (an extracted atom, a synthesized concept, a chronicle event) is readable by no remote caller. The local CLI is unchanged; `--as <member>` previews one member's view. Pages that already carried `readable_by` before you upgraded read as nobody until `gbrain repair access` (preview, then `--apply`) derives their readers. This works the same on a repo-less brain: members, groups and bindings live in the database.+A remote caller whose credential is bound to a listed member (directly or through a group) reads the page on every read path; every other remote caller, including an unbound token, an unbound stdio server, a bot with `--private-pages granted-sources` and an operator escape hatch (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), gets the same `not_found` as for a page that does not exist. `readable_by` only narrows: a `visibility: private` page stays private to a listed member unless the member's credential also has `--private-pages granted-sources`. What every designation means for each kind of caller is in [access designations](../guides/access-designations.md). A malformed `readable_by` reads as nobody. A page derived from a restricted page (an extracted atom, a synthesized concept, a chronicle event) is readable by no remote caller. The local CLI is unchanged; `--as <member>` previews one member's view. Pages that already carried `readable_by` before you upgraded read as nobody until `gbrain repair access` (preview, then `--apply`) derives their readers. This works the same on a repo-less brain: members, groups and bindings live in the database.**Folder rules: keep a whole folder to some members.** Instead of tagging every page, give a prefix its readers. On a repo-less brain (the default install) the rules live in the database:diff --git a/plugin-variants/gbrain-coding/skills/_AGENT_README.md b/plugin-variants/gbrain-coding/skills/_AGENT_README.mdindex 0dab2fef65..605937bce7 100644--- a/plugin-variants/gbrain-coding/skills/_AGENT_README.md+++ b/plugin-variants/gbrain-coding/skills/_AGENT_README.md@@ -104,7 +104,9 @@ Start with keyless recall and explicit remembering:Choose verification that can read the intended visibility: trusted local CLIcan recall private facts; MCP (including stdio) and a thin CLI connected to MCP-currently recall and withdraw world-visible facts only. Preserve the user's intended privacy.+recall and withdraw world-visible facts only, except a credential bound to the brain owner, which also recalls+private facts. Preserve the user's intended privacy; new pages carry no privacy label by default+(`skills/conventions/page-privacy.md`).A committed remote private-write receipt confirms storage, not private recall; explainwhen trusted local readback is unavailable rather than claiming verification orwidening access. Use only harmless synthetic world-visible facts for andiff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.mdindex 55b34d62bc..8b807b298f 100644--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md@@ -65,9 +65,10 @@ suppresses writes for that turn, including when standing capture is enabled.> conversation is observed making the opted-in call.>> **Choose a readback path that can see the intended visibility.** Trusted local-> CLI callers can recall and withdraw private facts. Every MCP caller, including-> stdio, and a thin CLI connected to MCP currently have world-only fact recall-> and withdrawal. A+> CLI callers can recall and withdraw private facts. Every other MCP caller, including+> stdio, and a thin CLI connected to MCP have world-only fact recall+> and withdrawal; a credential bound to the brain owner (`gbrain access owner`)+> also recalls private facts. A> request to remember does not authorize making real private information> world-visible. Use a trusted local write/readback path for private memory> when available. If only remote access is available, a successful privatediff --git a/plugin-variants/gbrain-coding/skills/conventions/page-privacy.md b/plugin-variants/gbrain-coding/skills/conventions/page-privacy.mdnew file mode 100644index 0000000000..3ec87ea64d--- /dev/null+++ b/plugin-variants/gbrain-coding/skills/conventions/page-privacy.md@@ -0,0 +1,15 @@+# Page privacy: write no designation by default++Every page you write carries no `visibility`, no `access` and no `readable_by` unless one of these is true:++- It holds another person's private information shared in confidence (a DM, someone's health or money details),+ or it was written for one shared room and must not reach the others: write `visibility: private`.+- The user asked for this page to be private: write `visibility: private`.+- In a shared brain, only named people may read it: write `readable_by: [<member>, group:<group>]`.++Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.+Never write `access:` or `confidentiality:` on a page: gbrain reads them as private.+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.++The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller+gets `not_found`. Full definition: `docs/guides/access-designations.md`.diff --git a/plugin-variants/gbrain-daily/skills/_AGENT_README.md b/plugin-variants/gbrain-daily/skills/_AGENT_README.mdindex 0dab2fef65..605937bce7 100644--- a/plugin-variants/gbrain-daily/skills/_AGENT_README.md+++ b/plugin-variants/gbrain-daily/skills/_AGENT_README.md@@ -104,7 +104,9 @@ Start with keyless recall and explicit remembering:Choose verification that can read the intended visibility: trusted local CLIcan recall private facts; MCP (including stdio) and a thin CLI connected to MCP-currently recall and withdraw world-visible facts only. Preserve the user's intended privacy.+recall and withdraw world-visible facts only, except a credential bound to the brain owner, which also recalls+private facts. Preserve the user's intended privacy; new pages carry no privacy label by default+(`skills/conventions/page-privacy.md`).A committed remote private-write receipt confirms storage, not private recall; explainwhen trusted local readback is unavailable rather than claiming verification orwidening access. Use only harmless synthetic world-visible facts for andiff --git a/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.md b/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.mdindex 7ab7ebb0a3..f748cb6f77 100644--- a/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/bulk-ingestion/SKILL.md@@ -113,8 +113,7 @@ source_id: <id> # unique ID from the source systemcreated: YYYY-MM-DDupdated: YYYY-MM-DDtags: []-access: <per your brain's access policy>-visibility: <private for anything remote agents must not read; omit for world>+# no visibility, access or readable_by: see conventions/page-privacy.md---# Titlediff --git a/plugin-variants/gbrain-daily/skills/conventions/page-privacy.md b/plugin-variants/gbrain-daily/skills/conventions/page-privacy.mdnew file mode 100644index 0000000000..3ec87ea64d--- /dev/null+++ b/plugin-variants/gbrain-daily/skills/conventions/page-privacy.md@@ -0,0 +1,15 @@+# Page privacy: write no designation by default++Every page you write carries no `visibility`, no `access` and no `readable_by` unless one of these is true:++- It holds another person's private information shared in confidence (a DM, someone's health or money details),+ or it was written for one shared room and must not reach the others: write `visibility: private`.+- The user asked for this page to be private: write `visibility: private`.+- In a shared brain, only named people may read it: write `readable_by: [<member>, group:<group>]`.++Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.+Never write `access:` or `confidentiality:` on a page: gbrain reads them as private.+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.++The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller+gets `not_found`. Full definition: `docs/guides/access-designations.md`.diff --git a/plugin/skills/_AGENT_README.md b/plugin/skills/_AGENT_README.mdindex 0dab2fef65..605937bce7 100644--- a/plugin/skills/_AGENT_README.md+++ b/plugin/skills/_AGENT_README.md@@ -104,7 +104,9 @@ Start with keyless recall and explicit remembering:Choose verification that can read the intended visibility: trusted local CLIcan recall private facts; MCP (including stdio) and a thin CLI connected to MCP-currently recall and withdraw world-visible facts only. Preserve the user's intended privacy.+recall and withdraw world-visible facts only, except a credential bound to the brain owner, which also recalls+private facts. Preserve the user's intended privacy; new pages carry no privacy label by default+(`skills/conventions/page-privacy.md`).A committed remote private-write receipt confirms storage, not private recall; explainwhen trusted local readback is unavailable rather than claiming verification orwidening access. Use only harmless synthetic world-visible facts for andiff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.mdindex 55b34d62bc..8b807b298f 100644--- a/plugin/skills/brain-ops/SKILL.md+++ b/plugin/skills/brain-ops/SKILL.md@@ -65,9 +65,10 @@ suppresses writes for that turn, including when standing capture is enabled.> conversation is observed making the opted-in call.>> **Choose a readback path that can see the intended visibility.** Trusted local-> CLI callers can recall and withdraw private facts. Every MCP caller, including-> stdio, and a thin CLI connected to MCP currently have world-only fact recall-> and withdrawal. A+> CLI callers can recall and withdraw private facts. Every other MCP caller, including+> stdio, and a thin CLI connected to MCP have world-only fact recall+> and withdrawal; a credential bound to the brain owner (`gbrain access owner`)+> also recalls private facts. A> request to remember does not authorize making real private information> world-visible. Use a trusted local write/readback path for private memory> when available. If only remote access is available, a successful privatediff --git a/plugin/skills/bulk-ingestion/SKILL.md b/plugin/skills/bulk-ingestion/SKILL.mdindex 7ab7ebb0a3..f748cb6f77 100644--- a/plugin/skills/bulk-ingestion/SKILL.md+++ b/plugin/skills/bulk-ingestion/SKILL.md@@ -113,8 +113,7 @@ source_id: <id> # unique ID from the source systemcreated: YYYY-MM-DDupdated: YYYY-MM-DDtags: []-access: <per your brain's access policy>-visibility: <private for anything remote agents must not read; omit for world>+# no visibility, access or readable_by: see conventions/page-privacy.md---# Titlediff --git a/plugin/skills/conventions/page-privacy.md b/plugin/skills/conventions/page-privacy.mdnew file mode 100644index 0000000000..3ec87ea64d--- /dev/null+++ b/plugin/skills/conventions/page-privacy.md@@ -0,0 +1,15 @@+# Page privacy: write no designation by default++Every page you write carries no `visibility`, no `access` and no `readable_by` unless one of these is true:++- It holds another person's private information shared in confidence (a DM, someone's health or money details),+ or it was written for one shared room and must not reach the others: write `visibility: private`.+- The user asked for this page to be private: write `visibility: private`.+- In a shared brain, only named people may read it: write `readable_by: [<member>, group:<group>]`.++Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.+Never write `access:` or `confidentiality:` on a page: gbrain reads them as private.+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.++The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller+gets `not_found`. Full definition: `docs/guides/access-designations.md`.diff --git a/plugin/skills/frontmatter-guard/SKILL.md b/plugin/skills/frontmatter-guard/SKILL.mdindex 6c5546a99d..8e1bb5a48a 100644--- a/plugin/skills/frontmatter-guard/SKILL.md+++ b/plugin/skills/frontmatter-guard/SKILL.md@@ -58,6 +58,7 @@ Without a guard, these accumulate silently until `gbrain sync` chokes or searchExit 1 means fix it first. The default is the strict producer rule: YAML gbrain could still import by quoting a value fails too, because other tools reject it. `--importable` answers the narrower question "would sync hold it?".- Never write a key gbrain reads for access or identity (`visibility`, `derived_from`, `slug`, `type`, `id`, `source_id`) from untrusted text.+- Write no `visibility`, `access`, `confidentiality` or `readable_by` unless the page needs it ([page privacy](../conventions/page-privacy.md)).## Held files: read them, then fix themdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 91c4fa72d0..00c54f56c1 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1687 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row+src/core/behavior-change-notice.ts 1688 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2059: owner_reads_private rowdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 408ef8c6d8..d8efd29ede 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -571,6 +571,7 @@ src/core/repair/overwritten-edits.ts previewEdit call:serializePageToMarkdown SEsrc/core/repair/overwritten-edits.ts versionMarkdown call:serializePageToMarkdown SEGW inline versions only: a segmented version has no lost_digest and is never previewed; the restore goes through revert_version, which refuses a segmented page or versionsrc/core/repair/overwritten-edits.ts versionMarkdown field SEGW inline versions only: overwriteContent returns null for a segmented version, which answers version_changedsrc/core/repair/overwritten-edits.ts versionMarkdown sql SEGW selects body_storage; a segmented version answers version_changed+src/core/repair/private-labels.ts privateLabelsRepair call:serializePageToMarkdown SEGW a segmented page returns segmented_page before the read and keeps its labelsrc/core/repair/redacted-facts.ts pageTexts field INLINE inline branch only (a segmented page's body is read through readBodyRange in segmentedText)src/core/repair/redacted-facts.ts pageTexts sql INLINE page_versions rows that hold a body copy (compiled_truth IS NOT NULL); a segmented version has none and is not readsrc/core/repair/redacted-facts.ts restoreFencedRows call:serializePageToMarkdown INLINE inline pages only: a segmented page returns before the read, and its fenced rows preview as class segmenteddiff --git a/skills/_AGENT_README.md b/skills/_AGENT_README.mdindex 0dab2fef65..605937bce7 100644--- a/skills/_AGENT_README.md+++ b/skills/_AGENT_README.md@@ -104,7 +104,9 @@ Start with keyless recall and explicit remembering:Choose verification that can read the intended visibility: trusted local CLIcan recall private facts; MCP (including stdio) and a thin CLI connected to MCP-currently recall and withdraw world-visible facts only. Preserve the user's intended privacy.+recall and withdraw world-visible facts only, except a credential bound to the brain owner, which also recalls+private facts. Preserve the user's intended privacy; new pages carry no privacy label by default+(`skills/conventions/page-privacy.md`).A committed remote private-write receipt confirms storage, not private recall; explainwhen trusted local readback is unavailable rather than claiming verification orwidening access. Use only harmless synthetic world-visible facts for andiff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.mdindex f89228b704..b7d7ea9b6b 100644--- a/skills/brain-ops/SKILL.md+++ b/skills/brain-ops/SKILL.md@@ -64,9 +64,10 @@ suppresses writes for that turn, including when standing capture is enabled.> conversation is observed making the opted-in call.>> **Choose a readback path that can see the intended visibility.** Trusted local-> CLI callers can recall and withdraw private facts. Every MCP caller, including-> stdio, and a thin CLI connected to MCP currently have world-only fact recall-> and withdrawal. A+> CLI callers can recall and withdraw private facts. Every other MCP caller, including+> stdio, and a thin CLI connected to MCP have world-only fact recall+> and withdrawal; a credential bound to the brain owner (`gbrain access owner`)+> also recalls private facts. A> request to remember does not authorize making real private information> world-visible. Use a trusted local write/readback path for private memory> when available. If only remote access is available, a successful privatediff --git a/skills/bulk-ingestion/SKILL.md b/skills/bulk-ingestion/SKILL.mdindex f052a2103e..a4b5878077 100644--- a/skills/bulk-ingestion/SKILL.md+++ b/skills/bulk-ingestion/SKILL.md@@ -112,8 +112,7 @@ source_id: <id> # unique ID from the source systemcreated: YYYY-MM-DDupdated: YYYY-MM-DDtags: []-access: <per your brain's access policy>-visibility: <private for anything remote agents must not read; omit for world>+# no visibility, access or readable_by: see conventions/page-privacy.md---# Titlediff --git a/skills/conventions/page-privacy.md b/skills/conventions/page-privacy.mdnew file mode 100644index 0000000000..3ec87ea64d--- /dev/null+++ b/skills/conventions/page-privacy.md@@ -0,0 +1,15 @@+# Page privacy: write no designation by default++Every page you write carries no `visibility`, no `access` and no `readable_by` unless one of these is true:++- It holds another person's private information shared in confidence (a DM, someone's health or money details),+ or it was written for one shared room and must not reach the others: write `visibility: private`.+- The user asked for this page to be private: write `visibility: private`.+- In a shared brain, only named people may read it: write `readable_by: [<member>, group:<group>]`.++Research, project, ops, people, company and meeting pages and summaries of world pages get nothing.+Never write `access:` or `confidentiality:` on a page: gbrain reads them as private.+Never remove a privacy label you did not set unless the user asks; the bulk path is `gbrain repair private-labels`.++The brain owner's agents (credentials bound to `gbrain access owner`) read private pages; every other remote caller+gets `not_found`. Full definition: `docs/guides/access-designations.md`.diff --git a/skills/frontmatter-guard/SKILL.md b/skills/frontmatter-guard/SKILL.mdindex 7e1ea41a28..3091e6e846 100644--- a/skills/frontmatter-guard/SKILL.md+++ b/skills/frontmatter-guard/SKILL.md@@ -57,6 +57,7 @@ Without a guard, these accumulate silently until `gbrain sync` chokes or searchExit 1 means fix it first. The default is the strict producer rule: YAML gbrain could still import by quoting a value fails too, because other tools reject it. `--importable` answers the narrower question "would sync hold it?".- Never write a key gbrain reads for access or identity (`visibility`, `derived_from`, `slug`, `type`, `id`, `source_id`) from untrusted text.+- Write no `visibility`, `access`, `confidentiality` or `readable_by` unless the page needs it ([page privacy](../conventions/page-privacy.md)).## Held files: read them, then fix themdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 76abef9092..98a94e30e4 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -1,6 +1,6 @@{"RESOLVER.md": "587768c702e0badf5e7d6201cd5902b7313b218e5663ab527e3a8365f5c438ee",- "_AGENT_README.md": "ab51e36e9a0b53f4d0609294b0556444399147834932d9c1acfdc7aa367c70b8",+ "_AGENT_README.md": "d66098abeb735975ffed54cb9c89d51255996500a9554ae1d1e996db4171631f","_brain-filing-rules.json": "4e6ecee2d94867d146583d60bf98dccdd9205bb70793af56fe1397a2b258ae0d","_brain-filing-rules.md": "ff42b331bce542d708f97ff0a73ff0fb5664b46ee9b1862a5478b15dc637487e","_friction-protocol.md": "51353207240142024ff1facc25f225712275ecdb4a034ffffdd83740c8d328e3",@@ -20,7 +20,7 @@"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33","brain-link-discipline/SKILL.md": "db2a77319475dd8eb370e9a3bb0eafe81d3b19d2de126113b30df7454dd9a069","brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",- "brain-ops/SKILL.md": "332af1d0a1e66fdaae7bb193c715e91f458dbf3b49a6669b9523948e2243255e",+ "brain-ops/SKILL.md": "7b438179ab497d0b06af26320b484d11036752c700ac8e85e26b8edf4a97526b","brain-pdf/SKILL.md": "2dfffd2373f00b5f11c1e4b39a75be48e90870201b4c11979d520bd5975dcae4","brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734","brain-taxonomist/SKILL.md": "418fd4cdac3355551c42a70fea4d76e3d9255fe04698358b2c1e89dc666bf11d",@@ -28,7 +28,7 @@"briefing/SKILL.md": "551c2f308c27b8a0823e2dfbbcdf7e8ace78ff6498afaa3ac21da852c7cf0d16","briefing/routing-eval.jsonl": "c056fea88f673e324d6a72cb70438cd6fcdbd09ec2cd036d44eb31a9ea6bf33d","bulk-ingestion/MANIFEST-PATTERN.md": "deb3abad5d8026822a663810abb1f39d60df8bb797a42587ffa6d44eefa15a0b",- "bulk-ingestion/SKILL.md": "48c10ec94fc23cd6f1ecfa4ec7254cc1cb3f5ea8cc43daf2fbe109c59ce1cda4",+ "bulk-ingestion/SKILL.md": "7aaadd9ab9e604d8a8a82d48029c21632bae4ac10671033f6590c2051473f441","bulk-ingestion/routing-eval.jsonl": "2bf8ffaf90b8ef761fa3cef54bf3af2eb8cc3ef736d054b5bf8b9361f6448d5a","capture/SKILL.md": "11434d995ae4d2d40211f3593f75fa48b3b0e6b6c5445547476462510f63da7f","chat-connectors/SKILL.md": "44b63309c779b5394c0be8ec6cabff8381099cfb8c0944143a859c48594ddf01",@@ -53,6 +53,7 @@"conventions/exec-output.md": "75f3abbc4041413bd4ee38af44fe82e91657b2c84525e6b92f627400e0abab47","conventions/line-grammar.md": "9d00254359153064e9fc0959d8c15743b5ff860890ed556178185bee32c7aeb1","conventions/model-routing.md": "c0d5031e4372c108d7e94346dc2958c21389f3b67544524578bbc9ea32d53c34",+ "conventions/page-privacy.md": "5b970a726de467f8535525b2929b98fe5b06bed04586b2bb938ffcad6eaf5298","conventions/path-discipline.md": "8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954","conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6","conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac",@@ -83,7 +84,7 @@"enrich/SKILL.md": "cbe6068373f4cd5006a6171a1795c3e619cfc82009ec4b3d86174b8ee2bcee2e","fact-check/SKILL.md": "49f0d356eee44541eddbc9cd501dc36707d417d84ca10446c0d315321f259674","fact-check/routing-eval.jsonl": "7519c6eada244813264b0df34ed67613e2d4404cfdf3cb209051b461749f5662",- "frontmatter-guard/SKILL.md": "a64ab4281d3a7d05b596b9c56e5c63c9c45c229e4a43f4270850682335402af6",+ "frontmatter-guard/SKILL.md": "0f805093fdc06c49698e215a5652d8fa319236e725711ef522caf01aab82467f","frontmatter-guard/routing-eval.jsonl": "243c28b04b557bac5360318c0f47bb6f1dd56d2f720aad3763b93fc0b2ea081e","functional-area-resolver/SKILL.md": "fe6e35fbb34dffec7af9ce4a6cc9c0b0eaa8345f97f33262a2abe0983431b421","functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028",diff --git a/src/cli/as-preview.ts b/src/cli/as-preview.tsindex fc97c34bb5..0dbe349132 100644--- a/src/cli/as-preview.ts+++ b/src/cli/as-preview.ts@@ -1,7 +1,7 @@/*** GBRA-218 local `--as <member>`: an operation's reads previewed as one member.* The handler runs under that member's identity with the remote read policy- * (readers and privacy), while ctx.remote stays false, so upload confinement+ * (readers and privacy; GST-2059: the brain owner reads with privacy relaxed), while ctx.remote stays false, so upload confinement* and write trust are unchanged. An unknown or ill-formed member is refused* before any work.*/@@ -33,15 +33,18 @@ const PASSTHROUGH: AsPreview = { run: fn => fn(), context: ctx => ctx };export async function openAsPreview(engine: BrainEngine, member: string | undefined, command: string): Promise<AsPreview> {if (member === undefined) return PASSTHROUGH;let identity: string[];+ let owner: boolean;try {- identity = (await (await import('../core/access/members.ts')).memberIdentity(engine, member)).identity;+ const resolved = await (await import('../core/access/members.ts')).memberIdentity(engine, member);+ identity = resolved.identity;+ owner = resolved.member === await (await import('../core/access/owner.ts')).ownerMemberId(engine);} catch (e: unknown) {await finishCliTeardown({ engine });exitCliError(e, command);}const { withCallerAccess } = await import('../core/search/private-visibility.ts');const folder = await (await import('../core/access/caller.ts')).folderAccessFor(engine, identity);- const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] };+ const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: !owner, owner, privateReadableSources: [] };return {run: fn => withCallerAccess(access, fn),context: ctx => ({ ...ctx, accessIdentity: identity, applyRemoteReadPolicy: true }),diff --git a/src/commands/access.ts b/src/commands/access.tsindex 12db4eeeae..add674ebfc 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -23,6 +23,7 @@ import { isPrivacyPrivatePage } from '../core/search/private-visibility.ts';import { identityFor, normalizePrincipal, normalizeReaders, readersAllow } from '../core/access/principals.ts';import { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '../core/access/audience.ts';import { linkMember, listMemberLinks, unlinkMember } from '../core/access/actor.ts';+import { clearOwner, ownerMemberId, ownerView, setOwner, type OwnerView } from '../core/access/owner.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, type MemberRecord,@@ -46,6 +47,11 @@ Members and groups:removing the group (--yes applies)gbrain access group list [<group>]+Owner (one member who owns this brain; credentials bound to it read every page, private ones included):+ gbrain access owner Show the owner and the credentials that read as it+ gbrain access owner set <member> The member must be enabled; bind credentials with --member <id>+ gbrain access owner clear No owner: every caller reads under the ordinary policy+Folder rules (one rulebook per source; the database store on a repo-less source, .gbrain/access.yml on a git one):gbrain access rule add --prefix <folder/> --readers a,group:b [--id <rule>] [--source <id>] [--yes]Preview first; narrowing applies at once@@ -135,6 +141,8 @@ export interface AccessCheckResult {identity: string[];may_act_for: string[] | null;verdict: 'reads_as_member' | 'unbound' | 'refused';+ /** GST-2059: the credential reads as the brain owner (config access.owner_member). */+ owner: boolean;explanation: string;audience?: Array<{ principal: string; covered_by_may_act_for: boolean }>;}@@ -164,14 +172,16 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;const identity = live ? identityFor(member!.id, member!.groups) : [];const mayActFor = Array.isArray(row.may_act_for) ? (row.may_act_for as string[]) : null;const verdict: AccessCheckResult['verdict'] = !member ? 'unbound' : live ? 'reads_as_member' : 'refused';+ const owner = live && member!.id === await ownerMemberId(engine);const explanation = verdict === 'unbound' ? 'Bound to no member: reads every page its grant allows except pages that name readers (readable_by).': verdict === 'refused' ? `Bound to member "${member!.id}", which is ${member!.status}: the credential is refused at verification (access_member_disabled).`- : `Reads as member "${member!.id}"${member!.groups.length ? ` (groups: ${member!.groups.join(', ')})` : ''}: pages naming readers are visible when they list the member or one of its groups, within the grant below.`;+ : `Reads as member "${member!.id}"${member!.groups.length ? ` (groups: ${member!.groups.join(', ')})` : ''}: pages naming readers are visible when they list the member or one of its groups, within the grant below.`+ + (owner ? ' It is the brain owner: it also reads visibility: private pages, privacy-alias pages, derived and pinned-question pages and private facts in every source the grant reads.' : '');const result: AccessCheckResult = {credential,grant: { scopes: grant.scopes, sources: grant.sources, takes_holders: grant.takesHolders, private_pages: grant.privatePages,operations: grant.allowedOperations ?? 'unrestricted', revision: grant.revision },- member, identity, may_act_for: mayActFor, verdict, explanation,+ member, identity, may_act_for: mayActFor, verdict, owner, explanation,};if (target.as !== undefined) {const audience: NonNullable<AccessCheckResult['audience']> = [];@@ -190,7 +200,7 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;const missing = audience.filter(a => !a.covered_by_may_act_for).map(a => a.principal);result.explanation += missing.length? ` A request naming this audience is refused (on_behalf_of_not_permitted): may_act_for does not list ${missing.join(', ')}.`- : ` A request naming this audience reads only the pages every entry may read${singleMemberAudience(audience.map(a => a.principal)) ? '' : ' and no visibility: private page'}, within the grant above.`;+ : ` A request naming this audience reads only the pages every entry may read${singleMemberAudience(audience.map(a => a.principal)) ? (owner && audience[0]!.principal !== `member:${member!.id}` ? ', without the owner\'s privacy relaxation' : '') : ' and no visibility: private page'}, within the grant above.`;}return result;}@@ -253,6 +263,35 @@ async function memberLinksCmd(engine: BrainEngine, sub: 'link' | 'unlink' | 'linr.applied ? 'Takes effect on the next attested call.' : `Apply without --dry-run.`]);}+function ownerLines(v: OwnerView): string[] {+ if (!v.owner) return v.inactive ? [`Owner: none in effect. access.owner_member names "${v.inactive.value}": ${v.inactive.reason}`, 'Fix it with gbrain access owner set <member> or gbrain access owner clear.']+ : ['Owner: none. Every remote caller reads under the ordinary policy (no visibility: private page without a grant).', 'Name one: gbrain access owner set <member>'];+ return [`Owner: ${v.owner}`,+ ` Credentials that read as the owner (${v.bound_credentials.length}): ${v.bound_credentials.map(c => `${c.kind} ${c.name}`).join(', ') || 'none'}`,+ ` Bind one: gbrain auth rescope --token <name> --member ${v.owner} (a stdio server: gbrain config set mcp.stdio_member ${v.owner})`];+}++async function ownerCmd(engine: BrainEngine, sub: string | undefined, args: string[], json: boolean): Promise<void> {+ switch (sub) {+ case undefined:+ case '--json':+ case 'show': {+ const v = await ownerView(engine);+ return print(json, v, () => ownerLines(v));+ }+ case 'set': {+ const v = await setOwner(engine, positionals(args)[0]);+ return print(json, v, () => ownerLines(v));+ }+ case 'clear': {+ const v = await clearOwner(engine);+ return print(json, v, () => ownerLines(v));+ }+ default:+ throw usageError(`Unknown access owner subcommand: ${sub}.`, 'Use gbrain access owner, gbrain access owner set <member> or gbrain access owner clear.');+ }+}+async function groupCmd(engine: BrainEngine, sub: string | undefined, args: string[], json: boolean): Promise<void> {const id = positionals(args)[0];const members = parseIdList(flagValue(args, '--members'), 'member');@@ -292,6 +331,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<voif (await runAccessRules(engine, cmd!, rest, json)) return;switch (cmd) {case 'member': return await memberCmd(engine, rest[0], rest.slice(1), json);+ case 'owner': return await ownerCmd(engine, rest[0], rest.slice(1), json);case 'group': return await groupCmd(engine, rest[0], rest.slice(1), json);case 'who-can-read': {const slug = positionals(rest)[0];@@ -317,7 +357,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<vo` ${r.explanation}`]);}default:- throw usageError(`Unknown access subcommand: ${cmd}.`, 'Use member, group, rule, apply, resume, who-can-read or check (gbrain access --help).', { code: 'unknown_command' });+ throw usageError(`Unknown access subcommand: ${cmd}.`, 'Use member, owner, group, rule, apply, resume, who-can-read or check (gbrain access --help).', { code: 'unknown_command' });}} catch (e) {exitCliError(e, 'access');diff --git a/src/commands/repair-private-labels.ts b/src/commands/repair-private-labels.tsnew file mode 100644index 0000000000..3b25cd0d0c--- /dev/null+++ b/src/commands/repair-private-labels.ts@@ -0,0 +1,27 @@+/**+ * The undo ledger of `gbrain repair private-labels`, kept by the CLI so the+ * repair core touches no filesystem (GBRA-248): one JSON line per cleared or+ * restored page at <gbrain home>/repair/private-labels/<brain_id>.jsonl, in a+ * 0700 directory, the file 0600. The core reads the lines for --class restore+ * and appends through `record`.+ */+import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync } from 'node:fs';+import { dirname } from 'node:path';+import { gbrainPath } from '../core/config.ts';+import type { PrivateLabelsLedger, PrivateLabelsLedgerLine } from '../core/repair/private-labels.ts';++export function privateLabelsLedger(brainId: string): PrivateLabelsLedger {+ const path = gbrainPath('repair', 'private-labels', `${brainId.replace(/[^A-Za-z0-9._-]/g, '_')}.jsonl`);+ const lines: PrivateLabelsLedgerLine[] = [];+ let unreadable = 0;+ for (const text of existsSync(path) ? readFileSync(path, 'utf8').split('\n') : []) {+ if (!text.trim()) continue;+ try { lines.push(JSON.parse(text) as PrivateLabelsLedgerLine); } catch { unreadable++; }+ }+ return { path, lines, unreadable, record(line) {+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ chmodSync(dirname(path), 0o700);+ appendFileSync(path, `${JSON.stringify(line)}\n`, { mode: 0o600 });+ chmodSync(path, 0o600);+ } };+}diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 1f4c443733..822ee87e32 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -38,6 +38,7 @@ import { cliOptsToProgressOptions, getCliOptions } from '../core/cli-options.ts'import { resolveSecretRules } from '../core/secret-spans.ts';import { normalizeSeatLabel } from '../core/context/seat.ts';import { agentSessionFlagArgs } from '../core/repair/agent-session-facts.ts';+import { privateLabelsLedger } from './repair-private-labels.ts';import { isAbsolute } from 'node:path';/** The content-repair lane's command word (#6377): parsed like a kind, dispatched to repair-content.ts, never a RepairKind. */@@ -210,7 +211,7 @@ const VALUE_FLAGS = new Set(['--rules', '--source', '--limit', '--expect', '--onconst KIND_FLAGS: Record<string, readonly string[]> = {'--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'legacy-twins', 'rename-identity', 'url-clone-fences'],'--include-cross-entity': ['duplicate-facts'],- '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility'], '--since': ['file-drift', 'generations'],+ '--slug': ['fences', 'file-drift', 'rename-identity', 'overwritten-edits', 'origin-twins', 'timeline-order', 'contact-rows', 'provenance', 'secret-spans', 'segmented-tiling'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift', 'visibility', 'private-labels'], '--since': ['file-drift', 'generations'],'--held': ['file-drift', 'generations'], '--side': ['file-drift'], '--state': ['file-drift'], '--cursor': ['file-drift'], '--provenance': ['file-drift'],'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],@@ -525,7 +526,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proconst results = await runRepairKinds(kinds, scope, { apply, source, noEmbed, named: kind !== undefined }, k => runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous, ...(k === kind && includeCrossEntity ? { includeCrossEntity } : {}),...(k === kind && KIND_FLAGS['--only']!.includes(k) ? { only, skip } : {}), ...(k === kind && slugs.length ? { slugs } : {}),...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),- ...(k === kind && k === 'visibility' && driftClass ? { driftClass } : {}),+ ...(k === kind && (k === 'visibility' || k === 'private-labels') && driftClass ? { driftClass } : {}),+ ...(k === kind && k === 'private-labels' ? { privateLabelsLedger: privateLabelsLedger(scope.brain_id) } : {}),...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since, ...(held ? { held } : {}), ...(side ? { side } : {}), ...(state ? { state } : {}), ...(provenance ? { provenance } : {}), ...(cursor ? { cursor } : {}),progress: createProgress(cliOptsToProgressOptions(getCliOptions())) } : {}),...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex cc7570b0a3..5a2bb720a5 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -13,7 +13,7 @@*/import type { BrainEngine } from '../engine.ts';import type { AuthInfo } from '../ops/contract.ts';-import { remotePrivacyRelaxed, requestRemotePolicy, type CallerAccess, type FolderCoverage } from '../search/private-visibility.ts';+import { remotePrivacyRelaxed, requestRemotePolicy, type CallerAccess, type FolderCoverage, type RemotePolicy } from '../search/private-visibility.ts';import { ACCESS_ID_RE, identityFor, normalizePrincipal } from './principals.ts';import { catalogueError } from '../error-catalogue.ts';import { hostOnlyError } from '../ops/op-fix.ts';@@ -194,6 +194,8 @@ export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'execu* an entry outside may_act_for or naming no member), the source grant stays the caller's, and the caller's privacy* relaxation (granted_sources, an operator hatch) applies only when the audience is exactly one member: a channel* (several entries, a group or a guest) sees no visibility: private page.+ * GST-2059: a caller bound to the brain owner (config access.owner_member) reads with its privacy relaxed in every+ * source its grant reads (owner), with no audience or an audience of the owner alone; member access stays.*/export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string, audience?: readonly AudiencePrincipal[] | null): Promise<Partial<CallerAccess>> {const [relaxed, remotePolicy] = await Promise.all([remotePrivacyRelaxed(engine), requestRemotePolicy(engine)]);@@ -201,34 +203,47 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | uif (audience?.length) {const identities = await resolveAudienceIdentities(engine, { auth, transport }, audience);const single = singleMemberAudience(audience);+ const owner = single && audience[0] === `member:${remotePolicy.ownerMember}`+ && isOwner(await boundIdentity(engine, auth, transport), remotePolicy);return {identity: identities.length === 1 ? identities[0]! : [],audience: [...audience],audienceIdentities: identities.length > 1 ? identities : [],...(restricted ? await folderAccessForAll(engine, identities) : { satisfiedRuleIds: [], folderCoverage: [] }),privateReadableSources: single ? privateSources ?? [] : [],- hidePrivate: single ? !relaxed : true,+ hidePrivate: single ? !relaxed && !owner : true,+ owner,applyRemoteReadPolicy: false,restricted,remotePolicy,};}- const identity = !restricted ? []- : !auth && transport === 'stdio' ? await stdioMemberIdentity(engine)- : await memberIdentityFor(engine, auth);+ const identity = restricted || remotePolicy.ownerMember ? await boundIdentity(engine, auth, transport) : [];+ const owner = isOwner(identity, remotePolicy);return {identity,audience: null,audienceIdentities: [],...(restricted ? await folderAccessFor(engine, identity) : { satisfiedRuleIds: [], folderCoverage: [] }),privateReadableSources: privateSources ?? [],- hidePrivate: !relaxed,+ hidePrivate: !relaxed && !owner,+ owner,applyRemoteReadPolicy: false,restricted,remotePolicy,};}+/** The member identity a remote caller's credential (or, unauthenticated over stdio, config mcp.stdio_member) is bound to. */+async function boundIdentity(engine: BrainEngine, auth: AuthInfo | undefined, transport?: string): Promise<string[]> {+ return !auth && transport === 'stdio' ? stdioMemberIdentity(engine) : memberIdentityFor(engine, auth);+}++/** GST-2059: the live identity is the brain owner's (config access.owner_member). Only a live, enabled member has an identity. */+function isOwner(identity: readonly string[], policy: RemotePolicy): boolean {+ return !!policy.ownerMember && identity.includes(`member:${policy.ownerMember}`);+}+/*** GBRA-231: the view a remote call was answered under, as `_meta.access` on every remote response and `access.applied`* in whoami: the member and groups it read as (none for an audience of several entries), the asserted audience, the@@ -242,7 +257,7 @@ export interface AppliedAccess {/** GST-359 C1: present on an attested call (the system that named the person; the id is not echoed). */actor?: { system: string };policy_rev: Record<string, number> | null;- relaxation: 'none' | 'granted_sources' | 'operator';+ relaxation: 'none' | 'granted_sources' | 'operator' | 'owner';}export async function appliedAccessSummary(engine: Pick<BrainEngine, 'executeRaw'>, auth?: AuthInfo, sourceIds: readonly (string | undefined)[] = []): Promise<AppliedAccess> {@@ -264,7 +279,7 @@ export async function appliedAccessSummary(engine: Pick<BrainEngine, 'executeRawaudience: access.audience ? [...access.audience] : null,...(access.actor ? { actor: { system: access.actor.system } } : {}),policy_rev: policyRev,- relaxation: !access.hidePrivate ? 'operator' : access.privateReadableSources.length ? 'granted_sources' : 'none',+ relaxation: access.owner ? 'owner' : !access.hidePrivate ? 'operator' : access.privateReadableSources.length ? 'granted_sources' : 'none',};}diff --git a/src/core/access/owner.ts b/src/core/access/owner.tsnew file mode 100644index 0000000000..deb952c117--- /dev/null+++ b/src/core/access/owner.ts@@ -0,0 +1,55 @@+/**+ * GST-2059: the brain owner. On a personal brain the owner's own agents must read the whole brain, private pages+ * included, while every other remote caller keeps the read policy. The owner is named explicitly, never guessed: config+ * access.owner_member holds one member id, and a credential (token or OAuth client, bound with+ * `gbrain auth rescope --member <id>`) or a stdio server (config mcp.stdio_member) bound to that live member reads as+ * the owner (CallerAccess.owner, src/core/access/caller.ts). Everything lives in the database, so a repo-less brain+ * gets it unchanged. Only the trusted local CLI writes it.+ */+import type { BrainEngine } from '../engine.ts';+import { OWNER_MEMBER_KEY } from '../search/private-visibility.ts';+import { ACCESS_ID_RE } from './principals.ts';+import { boundCredentials, memberIdentity } from './members.ts';+import type { CredentialRef } from './members.ts';++export interface OwnerView {+ owner: string | null;+ /** The configured value when it names no enabled member (ill-formed, disabled, removed or missing): no caller reads as the owner. */+ inactive?: { value: string; reason: string };+ bound_credentials: CredentialRef[];+}++/** The owner member id, or null when unset or ill-formed (fail closed). */+export async function ownerMemberId(engine: Pick<BrainEngine, 'getConfig'>): Promise<string | null> {+ try {+ const raw = (await engine.getConfig(OWNER_MEMBER_KEY))?.trim();+ return raw && ACCESS_ID_RE.test(raw) ? raw : null;+ } catch {+ return null;+ }+}++/** The configured owner, whether it is live, and the credentials that read as it. */+export async function ownerView(engine: BrainEngine): Promise<OwnerView> {+ const raw = (await engine.getConfig(OWNER_MEMBER_KEY))?.trim() ?? '';+ if (!raw) return { owner: null, bound_credentials: [] };+ try {+ const { member } = await memberIdentity(engine, raw);+ return { owner: member, bound_credentials: await boundCredentials(engine, member) };+ } catch (e) {+ return { owner: null, inactive: { value: raw, reason: e instanceof Error ? e.message : String(e) }, bound_credentials: [] };+ }+}++/** Names the owner; refuses an ill-formed or non-enabled member before writing anything. */+export async function setOwner(engine: BrainEngine, raw: unknown): Promise<OwnerView> {+ const { member } = await memberIdentity(engine, raw);+ await engine.setConfig(OWNER_MEMBER_KEY, member);+ return ownerView(engine);+}++/** Names no owner: every caller reads under the ordinary read policy again. */+export async function clearOwner(engine: BrainEngine): Promise<OwnerView> {+ await engine.unsetConfig(OWNER_MEMBER_KEY);+ return { owner: null, bound_credentials: [] };+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2e82668a4c..91ce7a1318 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },+ { since: 'TBD', id: 'owner_reads_private_gst2059', text: 'A brain can now name its owner: `gbrain access owner set <member>` (config `access.owner_member`, an enabled member). Every remote credential or stdio server bound to that member reads the whole brain, `visibility: private` pages, privacy-alias pages (`access: private`, ...), derived and pinned-question pages included, through `get_page`, `search`, `query`, `recall` and the other page reads in the sources its grant reads, and `recall` returns its private facts. `readable_by` and folder rules still bind it, and it is not relaxed when it speaks for a shared-room audience. Other members, unbound and public callers are unchanged. `_meta.access.relaxation` reads `owner` for such a call, and `gbrain access check --token <name>` reports it. `gbrain repair private-labels` (named runs only) previews the `access: private` labels stamped on ordinary pages with counts per category, keeps real restrictions, and clears the rest in reviewed batches (`--apply --expect <hash>`), recording each change so `--class restore` can put it back. The bulk-ingestion page template no longer writes an `access:` line; what each designation means is in docs/guides/access-designations.md.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex 1a14786738..1e31097331 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -24,5 +24,6 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['serve.vector_prewarm', // config.ts loadConfigWithEngine (snapshot only) → serve.ts: a Postgres serve prewarms the HNSW indexes into shared_buffers at start when they fit, default off'mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers'persistence.adopt_quiet_ms', // persistence/local-edit-adoption.ts (GST-1601): how long a local edit must be quiet before it is adopted, default 5000+ 'access.owner_member', // access/owner.ts (GST-2059): the member who owns this brain; credentials bound to it read private pages (gbrain access owner set)'mcp.stdio_may_act_for', // access/audience.ts (GBRA-231): whom a local stdio server may act for (_meta.on_behalf_of); unset, stdio refuses every audience];diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 4a6a2663a4..9dbe67882c 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -364,14 +364,12 @@ const recall: Operation = {)];const scalarSource = factSources.length === 1 ? factSources[0] : undefined;- // Visibility filter: remote callers see world-only unless their token- // grants elevated visibility (future-proofing; v0.31 ships world-only- // for remote, all for local CLI).+ // Visibility filter: remote callers see world-only facts; the local CLI and (GST-2059) the brain owner see all.+ const { resolveExcludePrivatePages, callerIsOwner } = await import('../search/private-visibility.ts');const visibility =- ctx.remote === false+ ctx.remote === false || callerIsOwner()? undefined: ['world'] as ('private' | 'world')[];- const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote); // #4352: fact and page arms alikeconst eligibility = await resolveReadEligibility(ctx, { minTrust: p.min_trust }); // #5575 floor + quarantine/rederive hidingdiff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex e0d7a76cc4..81a86bb3de 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -26,6 +26,7 @@ import { preparePageMutation, prepareFileTarget } from './page-prepare.ts';import { prepareTakesMutation } from './takes-prepare.ts';import { digest, sha256 } from './digest.ts';import type { PreparedMutation } from './coordinator.ts';+import { withTrustKeep } from './context.ts';import { isTerminal, type WriteAuthority, type WriteRequest } from './model.ts';import { authorizePageVisibility } from './page-visibility.ts';import { nativeLockCapability } from './native-lock.ts';@@ -236,17 +237,19 @@ export function maintenanceGhostRefusal(sourceId: string, slug: string): Operati/** #5523: a Life Chronicle timeline row projected onto the depth page in the same publication. */export interface MaintenanceEventProjection { depth_slug: string; date: string; summary: string; }+/** `keepTrust`: the edit authors nothing (it only removes privacy labels), so the page keeps its stored trust tier (withTrustKeep). */type MaintenancePageOptions = { requestId?: string; expectedRevision: string | null; file?: boolean;- eventProjection?: MaintenanceEventProjection; derivation?: DerivationDeclaration };+ eventProjection?: MaintenanceEventProjection; derivation?: DerivationDeclaration; keepTrust?: true };/** A maintenance page publication's intent and request id; `batch` (G6) is the run's batch id, part of both. */function maintenancePageRequest(authority: MaintenanceAuthority, slug: string, content: string, options: MaintenancePageOptions, batch?: string) {const projection = options.eventProjection ? { event_projection: options.eventProjection } : {};const derivation = options.derivation ? { derivation: options.derivation } : {};const grouped = batch ? { maintenance_batch: batch } : {};- return { intent: { kind: 'managed_maintenance_page', content, expected_revision: options.expectedRevision, ...projection, ...derivation, ...grouped },+ const keep = options.keepTrust ? { keep_trust: true } : {};+ return { intent: { kind: 'managed_maintenance_page', content, expected_revision: options.expectedRevision, ...projection, ...derivation, ...grouped, ...keep },requestId: options.requestId ?? maintenanceRequestId({ authority: authority.writer, slug, content, revision: options.expectedRevision, file: options.file ?? true,- ...projection, ...derivation, ...grouped }) };+ ...projection, ...derivation, ...grouped, ...keep }) };}/** `derivation` (#5575 I2): the deriver's taint declaration; the page and its edges are stamped from it at publication. */@@ -595,8 +598,9 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coif (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);if (row.intent?.kind === 'managed_maintenance_meeting_timeline') return (await import('../extract-timeline-from-meetings.ts')).prepareMeetingTimeline(engine, row);if (row.intent?.kind === 'managed_maintenance_page') {- const prepared = await preparePageMutation(engine, row.intent.expected_revision === null+ const page = await preparePageMutation(engine, row.intent.expected_revision === null? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config, undefined, undefined, { clock });+ const prepared: PreparedMutation = row.intent.keep_trust === true ? { ...page, apply: (tx, preimage) => withTrustKeep(tx, ['pages'], () => page.apply(tx, preimage)) } : page;const projection = row.intent.event_projection as MaintenanceEventProjection | undefined;if (!projection) return prepared;// #5523: the event page and its depth-page timeline row commit together indiff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 8813a8229a..517d1114fb 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'atoms-restore' | 'extractor-facts' | 'unwithdrawn-facts' | 'conversation-labels' | 'captured-facts' | 'agent-session-facts' | 'redacted-facts' | 'loop-facts' | 'ontology-facts' | 'facts-rehome' | 'consolidate-ties' | 'duplicate-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'origin-twins' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity' | 'overwritten-edits' | 'legacy-twins' | 'missing-tables' | 'segmented-mirror' | 'segmented-tiling' | 'uncommitted-deletions' | 'visibility' | 'generations' | 'fact-claim-dates' | 'timeline-order' | 'contact-rows' | 'provenance' | 'secret-spans' | 'rows-behind' | 'private-labels';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 12f0d04f7e..346ed9c9d5 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -50,8 +50,9 @@ import { readFix } from '../ops/op-fix.ts';import { classifyItemFailure, ItemRun, type ItemFailure } from '../item-failure.ts';import type { ProgressReporter } from '../progress.ts';import type { GenerationsSelection } from '../generations/repair.ts';+import type { PrivateLabelsLedger } from './private-labels.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'accepted-takes', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'access', 'private-labels'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -132,7 +133,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb/** `secret-spans` (GST-327): the secret scanner rules to redact (`--rules`); default every named rule. */rules?: string[];/** `agent-session-facts` (#8064): operator evidence, sessions whose cwd is under a prefix (`--cwd`) or named (`--session`), and the note's agent (`--principal`). */- cwdPrefixes?: string[]; sessions?: string[]; principal?: string }+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string;+ /** `private-labels`: the undo ledger the CLI keeps (its path, lines for --class restore, and the append). */+ privateLabelsLedger?: PrivateLabelsLedger }export interface RepairHandler {kind: RepairKind;@@ -335,7 +338,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sprefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string;provenance?: string; cursor?: string; progress?: ProgressReporter;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];- cwdPrefixes?: string[]; sessions?: string[]; principal?: string;+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger;spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;/** GBRA-133: the CLI's termination signal; the apply stops before the next item with a result instead of dying mid-run. */stop?: AbortSignal;@@ -368,7 +371,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}), ...(opts.afterPage !== undefined ? { afterPage: opts.afterPage } : {}),...(opts.limit !== undefined ? { limit: opts.limit } : {}), ...(opts.generations ? { generations: opts.generations } : {}),...(opts.day ? { day: opts.day } : {}), ...(opts.rules?.length ? { rules: opts.rules } : {}),- ...(opts.cwdPrefixes?.length ? { cwdPrefixes: opts.cwdPrefixes } : {}), ...(opts.sessions?.length ? { sessions: opts.sessions } : {}), ...(opts.principal ? { principal: opts.principal } : {}) };+ ...(opts.cwdPrefixes?.length ? { cwdPrefixes: opts.cwdPrefixes } : {}), ...(opts.sessions?.length ? { sessions: opts.sessions } : {}), ...(opts.principal ? { principal: opts.principal } : {}),+ ...(opts.privateLabelsLedger ? { privateLabelsLedger: opts.privateLabelsLedger } : {}) };const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);diff --git a/src/core/repair/private-labels.ts b/src/core/repair/private-labels.tsnew file mode 100644index 0000000000..2fd3b594fb--- /dev/null+++ b/src/core/repair/private-labels.ts@@ -0,0 +1,279 @@+/**+ * gbrain repair private-labels: clear the privacy labels that writer templates+ * over-stamped on ordinary pages. Every live page that is private by its label+ * (visibility: private, or a privacy alias with no visibility) is classified:+ *+ * KEEP (counted, never changed)+ * pinned_question pinned_question in frontmatter, or type question+ * derived an atom, a synthesized concept or a life-chronicle event;+ * its privacy follows its origin (gbrain repair visibility owns it)+ * strong_alias access restricted or confidential, or a private confidentiality value+ * explicit_visibility visibility: private with no access: private (a deliberate writer or connector)+ *+ * CLEAR (the only pages changed)+ * alias access: private and no visibility: the access key is removed+ * alias-and-visibility access: private and visibility: private: both keys are removed+ * git-publish either of the two in a source with canonical git; private pages+ * there are database-only, so clearing commits the page into Git+ * for the first time. Applied only when named with --class git-publish.+ *+ * The preview lists one window (--limit, default PRIVATE_LABELS_WINDOW) of clear items in+ * (class, page id) order under a hash, with every category's count over the scope before+ * and after the window; --apply --expect <hash> applies exactly that window, re-deciding+ * each page against its live revision and labels first. A bare --apply is refused. Each+ * item is one revision-bound maintenance write, so it keeps the page's trust tier (no+ * trust_tier marker, no lower_page proposal) and its gate markers: a managed brain+ * publishes it through the maintenance door (the Git door on a repo source) with keep_trust,+ * an unmanaged one imports it in a maintenance transaction under the page lock, also+ * keeping the stored tier. readable_by and folder+ * rules are left as they are.+ *+ * Reversible: every applied item records a line with the exact removed values in the+ * ledger the caller passes (`privateLabelsLedger`; the CLI keeps it at+ * <gbrain home>/repair/private-labels/<brain_id>.jsonl, src/commands/repair-private-labels.ts),+ * and --class restore plans from its lines: each recorded page still live and still+ * without those keys gets them back (preview-bound the same way, with its own line).+ * An apply or a restore preview without a ledger is refused.+ */+import type { BrainEngine } from '../engine.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { opError } from '../ops/contract.ts';+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { withTrustKeep } from '../persistence/context.ts';+import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';+import { importFromContent } from '../import-file.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { PRIVACY_ALIASES, privacyAliasSql } from '../search/private-visibility.ts';+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions, type RepairScope } from './core.ts';++export type ClearClass = 'alias' | 'alias-and-visibility' | 'git-publish';+export type KeepClass = 'pinned_question' | 'derived' | 'strong_alias' | 'explicit_visibility';+type LabelsClass = ClearClass | 'restore';+const KEEP_CLASSES: readonly KeepClass[] = ['pinned_question', 'derived', 'strong_alias', 'explicit_visibility'];+const CLEAR_CLASSES: readonly ClearClass[] = ['alias', 'alias-and-visibility', 'git-publish'];+export const PRIVATE_LABELS_CLASSES: readonly LabelsClass[] = [...CLEAR_CLASSES, 'restore'];+/** Without --class a preview covers these; git-publish commits pages into Git and runs only when named. */+const DEFAULT_CLASSES: readonly ClearClass[] = ['alias', 'alias-and-visibility'];+export const PRIVATE_LABELS_WINDOW = 1000;+export const PRIVATE_LABELS_WINDOW_MAX = 10_000;+const SCAN_PAGE = 5000;+const bounded = { timeoutMs: 120_000 };++type Labels = { access?: string; visibility?: string };+interface LabelRow { id: number; source_id: string; slug: string; type: string; frontmatter: Record<string, unknown> | null; revision: string | null; chars: number; git: boolean }+interface Selection { source_ids: string[]; class: LabelsClass | null }+interface Approved { mode: 'clear' | 'restore'; class: LabelsClass; brain_id: string; source_id: string; slug: string; page_id: number; revision: string | null; labels: Labels; chars: number; selection: Selection }+interface LabelsItem extends RepairItem { entry: Approved; ledger: PrivateLabelsLedger; hash?: string; last?: boolean }+export interface PrivateLabelsLedgerLine { at: string; brain_id: string; source_id: string; slug: string; page_id: number; revision_before: string; request_id: string; removed?: Labels; restored?: Labels }+type LedgerLine = PrivateLabelsLedgerLine;+/** The undo ledger, kept by the caller: where it is, its lines (read for --class restore), unreadable line count, and the append. */+export interface PrivateLabelsLedger { path: string; lines: PrivateLabelsLedgerLine[]; unreadable: number; record(line: PrivateLabelsLedgerLine): void }+type Decision = { keep: KeepClass } | { clear: ClearClass; removed: Labels } | null;++/** KEEP or CLEAR for a page that is private by its label; null for a page no label makes private. */+export function classifyPrivateLabel(row: Pick<LabelRow, 'type' | 'frontmatter' | 'git'>): Decision {+ const fm = row.frontmatter ?? {};+ const value = (key: string) => typeof fm[key] === 'string' ? (fm[key] as string).trim().toLowerCase() : null;+ const aliased = Object.entries(PRIVACY_ALIASES).some(([key, values]) => values.includes(value(key) ?? ''));+ if (!(fm.visibility === 'private' || (fm.visibility == null && aliased))) return null;+ if (Object.hasOwn(fm, 'pinned_question') || row.type === 'question') return { keep: 'pinned_question' };+ if (row.type === 'atom' || (row.type === 'concept' && fm.synthesized_by != null)+ || (row.type === 'event' && typeof fm.captured_via === 'string' && fm.captured_via.startsWith('life-chronicle:'))) return { keep: 'derived' };+ const access = value('access');+ if (access === 'restricted' || access === 'confidential' || PRIVACY_ALIASES.confidentiality!.includes(value('confidentiality') ?? '')) return { keep: 'strong_alias' };+ if (access !== 'private') return { keep: 'explicit_visibility' };+ const removed: Labels = fm.visibility == null ? { access: fm.access as string } : { access: fm.access as string, visibility: 'private' };+ return { clear: row.git ? 'git-publish' : removed.visibility ? 'alias-and-visibility' : 'alias', removed };+}++/** Live pages of the sources that a label makes private, in page id order (`ids` narrows to those pages). */+async function scanLabelled(engine: BrainEngine, sourceIds: string[], visit: (row: LabelRow) => void, ids?: number[]): Promise<void> {+ for (let after = 0; ;) {+ const rows = await engine.executeRaw<LabelRow>(`SELECT p.id, p.source_id, p.slug, p.type, p.frontmatter, p.knowledge_revision::text AS revision,+ COALESCE(p.body_bytes, 0) AS chars, COALESCE(s.config->>'canonical' = 'git', false) AS git+ FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND p.id > $2+ AND (p.frontmatter->>'visibility' = 'private' OR (p.frontmatter->>'visibility' IS NULL AND ${privacyAliasSql('p')}))+ AND ($3::integer[] IS NULL OR p.id = ANY($3::integer[]))+ ORDER BY p.id LIMIT ${SCAN_PAGE}`, [sourceIds, after, ids ?? null], bounded);+ for (const row of rows) visit(row);+ if (rows.length < SCAN_PAGE) return;+ after = Number(rows[rows.length - 1]!.id);+ }+}++const describeLabels = (labels: Labels) => Object.entries(labels).map(([key, value]) => `${key}: ${value}`).join(', ');+const sameLabels = (a: Labels, b: Labels) => JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort());+const previewCommand = (scope: RepairScope, selection: Selection) =>+ `gbrain repair private-labels${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}${selection.class ? ` --class ${selection.class}` : ''}`;++function selectedClass(opts?: RepairPlanOptions): LabelsClass | null {+ const value = opts?.driftClass;+ if (value === undefined) return null;+ if ((PRIVATE_LABELS_CLASSES as readonly string[]).includes(value)) return value as LabelsClass;+ throw opError('invalid_params', `--class for gbrain repair private-labels takes ${PRIVATE_LABELS_CLASSES.join(', ')} (got "${value}").`,+ 'Preview the default classes with gbrain repair private-labels, or one with e.g. gbrain repair private-labels --class git-publish.');+}++const hashParts = (scope: RepairScope, selection: Selection, entries: Approved[]) => ({ kind: 'private-labels-v1', brain_id: scope.brain_id, selection,+ items: entries.map(e => [e.mode, e.class, e.source_id, e.page_id, e.slug, e.revision, Object.entries(e.labels).sort()]) });++/** Every category's count over the scope and the clear entries of the selected classes, in (class, page id) order. */+async function planClear(engine: BrainEngine, scope: RepairScope, selection: Selection, classes: readonly ClearClass[]) {+ const counts = Object.fromEntries([...KEEP_CLASSES, ...CLEAR_CLASSES].map(cls => [cls, 0])) as Record<KeepClass | ClearClass, number>;+ const entries: Approved[] = [];+ await scanLabelled(engine, scope.source_ids, row => {+ const decided = classifyPrivateLabel(row);+ if (!decided) return;+ if ('keep' in decided) { counts[decided.keep]++; return; }+ counts[decided.clear]++;+ if (classes.includes(decided.clear)) entries.push({ mode: 'clear', class: decided.clear, brain_id: scope.brain_id, source_id: row.source_id, slug: row.slug,+ page_id: Number(row.id), revision: row.revision, labels: decided.removed, chars: Number(row.chars), selection });+ });+ entries.sort((a, b) => CLEAR_CLASSES.indexOf(a.class as ClearClass) - CLEAR_CLASSES.indexOf(b.class as ClearClass) || a.page_id - b.page_id);+ return { counts: counts as Record<string, number>, entries, unreadable: 0 };+}++/** The ledger's latest line per page decides: a removal whose page is live and still lacks every removed key is restorable. */+async function planRestore(engine: BrainEngine, scope: RepairScope, selection: Selection, ledger: PrivateLabelsLedger) {+ const { lines, unreadable } = ledger;+ const latest = new Map<string, LedgerLine>();+ for (const line of lines) {+ if (line.brain_id === scope.brain_id && scope.source_ids.includes(line.source_id)) latest.set(`${line.source_id}:${line.page_id}`, line);+ }+ const removals = [...latest.values()].filter(line => line.removed);+ const live = removals.length ? await engine.executeRaw<LabelRow>(`SELECT id, source_id, slug, type, frontmatter, knowledge_revision::text AS revision, COALESCE(body_bytes, 0) AS chars+ FROM pages WHERE id = ANY($1::integer[]) AND deleted_at IS NULL`, [removals.map(line => line.page_id)], bounded) : [];+ const byId = new Map(live.map(row => [Number(row.id), row]));+ const counts = { restorable: 0, already_restored: latest.size - removals.length, page_gone: 0 };+ const entries: Approved[] = [];+ for (const line of removals) {+ const page = byId.get(line.page_id);+ if (!page || page.source_id !== line.source_id) { counts.page_gone++; continue; }+ if (Object.keys(line.removed!).some(key => Object.hasOwn(page.frontmatter ?? {}, key))) { counts.already_restored++; continue; }+ counts.restorable++;+ entries.push({ mode: 'restore', class: 'restore', brain_id: scope.brain_id, source_id: page.source_id, slug: page.slug, page_id: Number(page.id),+ revision: page.revision, labels: line.removed!, chars: Number(page.chars), selection });+ }+ entries.sort((a, b) => a.page_id - b.page_id);+ return { counts: counts as Record<string, number>, entries, unreadable };+}++/**+ * Unmanaged brains: the legacy maintenance import (an owner path: no write gate, no trust marker, gate markers kept),+ * under withTrustKeep so the page keeps its stored tier, bound to the previewed revision under the page lock. False when+ * the page moved.+ */+async function importAtRevision(engine: BrainEngine, entry: Approved, revision: string, content: string, embed: boolean): Promise<boolean> {+ return maintenanceTransaction(engine, async tx => {+ await tx.lockPageKeys([{ sourceId: entry.source_id, slug: entry.slug }]);+ if ((await tx.readPageSnapshot(entry.slug, { sourceId: entry.source_id }))?.revision !== revision) return false;+ const result = await withTrustKeep(tx, ['pages'], () => importFromContent(tx, entry.slug, content, { sourceId: entry.source_id, noEmbed: !embed, preserveGateMarkers: true }));+ if (result.status === 'error') throw opError('invalid_params', `${entry.source_id}:${entry.slug} was not written: ${result.error ?? 'the import refused it'}`,+ 'Preview gbrain repair private-labels again; the page is listed with its current state.');+ return true;+ });+}++export const privateLabelsRepair: RepairHandler = {+ kind: 'private-labels',+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const selection: Selection = { source_ids: scope.source_ids, class: selectedClass(opts) };+ const command = previewCommand(scope, selection);+ const ledger = opts?.privateLabelsLedger;+ if (!ledger && (opts?.apply || selection.class === 'restore')) {+ throw opError('invalid_params', 'gbrain repair private-labels needs its undo ledger to apply or restore, and this caller passed none.', `Run it from the CLI on the brain host: ${command}`);+ }+ const toItems = (entries: Approved[], hash: string) => entries.map((entry, index): LabelsItem => ({ cursor: { phase: 0, id: index }, source_id: entry.source_id, slug: entry.slug,+ chars: entry.chars, action: `${entry.mode === 'clear' ? 'remove' : 're-add'} ${describeLabels(entry.labels)}`, entry, ledger: ledger!, hash, last: index === entries.length - 1 }));+ if (opts?.apply) {+ if (!opts.expect) {+ throw opError('invalid_params', 'gbrain repair private-labels --apply changes only the set a preview printed (clearing a label widens remote reads).',+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`);+ }+ const approved = await loadApprovedSet<Approved>(engine, { command: 'private-labels', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(hashParts(scope, selection, [])) });+ if (approved.items.some(entry => (entry.selection.class ?? null) !== selection.class || JSON.stringify(entry.selection.source_ids) !== JSON.stringify(selection.source_ids))) {+ throw previewChangedError(opts.expect, command);+ }+ return { items: toItems(approved.items, opts.expect).filter(item => afterCursor(item.cursor, after)), preview_hash: opts.expect, residuals: {} };+ }+ const size = Math.min(Math.max(1, opts?.limit ?? PRIVATE_LABELS_WINDOW), PRIVATE_LABELS_WINDOW_MAX);+ const restore = selection.class === 'restore';+ const planned = restore ? await planRestore(engine, scope, selection, ledger!)+ : await planClear(engine, scope, selection, selection.class ? [selection.class as ClearClass] : DEFAULT_CLASSES);+ const window = planned.entries.slice(0, size);+ const pastWindow = planned.entries.length - window.length;+ const before = { ...planned.counts };+ const projected = { ...before };+ for (const entry of window) {+ if (entry.class !== 'restore') { projected[entry.class]!--; continue; }+ projected.restorable!--;+ projected.already_restored!++;+ }+ const hash = previewHash(hashParts(scope, selection, window));+ if (window.length) await saveApprovedSet<Approved>(engine, { command: 'private-labels', hash }, window);+ const gitPublish = restore ? 0 : before['git-publish'] ?? 0;+ const warnings = [+ ...(pastWindow ? [`This preview lists one window of ${window.length} item(s); ${pastWindow} more found past it. Apply this window (or decide not to), then preview again for the next one: ${command}`] : []),+ restore ? 'Restoring re-adds each recorded label, so remote callers that are not the brain owner stop reading these pages again.'+ : 'Clearing a label widens what remote callers that are not the brain owner can read: each cleared page becomes readable remotely (readable_by and folder rules still apply). '+ + 'Undo with: gbrain repair private-labels --class restore',+ ...(gitPublish && selection.class === 'git-publish' ? [`${gitPublish} page(s) of class git-publish live in git-canonical sources, where private pages are database-only; `+ + 'clearing commits each listed page into its source\'s Git history for the first time.'] : []),+ ...(gitPublish && selection.class !== 'git-publish' ? [`${gitPublish} page(s) of class git-publish (git-canonical sources) carry the same label and are not in this preview: `+ + 'private pages there are database-only, so clearing commits each into its source\'s Git history for the first time. Preview them by name: gbrain repair private-labels --class git-publish'] : []),+ ...(planned.unreadable ? [`${planned.unreadable} ledger line(s) could not be read and are not planned.`] : []),+ ];+ return { items: toItems(window, hash), preview_hash: hash, residuals: {}, warnings,+ listing: window.map(entry => ({ item: `${entry.source_id}:${entry.slug}`, class: entry.class,+ detail: entry.mode === 'restore' ? `re-add ${describeLabels(entry.labels)}` : entry.labels.visibility ? 'remove access: private, visibility: private' : 'remove access: private' })),+ details: { counts: { before, after: projected }, window: { size, listed: window.length, pending_past_window: pastWindow, next_preview: command },+ ledger: ledger?.path ?? null, class: selection.class } };+ },+ async apply(ctx, raw, opts): Promise<RepairItemOutcome> {+ const item = raw as LabelsItem;+ const { entry } = item;+ try {+ const changed: RepairItemOutcome = { applied: false, outcome: 'changed_since_preview' };+ const snapshot = await ctx.engine.readPageSnapshot(entry.slug, { sourceId: entry.source_id });+ if (!snapshot || Number(snapshot.page.id) !== entry.page_id || snapshot.revision !== entry.revision) return changed;+ if (isSegmentedPage(snapshot.page)) return { applied: false, outcome: 'segmented_page', reason: 'The page body is stored in segments; edit its frontmatter by hand on the brain host.' };+ const frontmatter = snapshot.page.frontmatter ?? {};+ let next: Record<string, unknown>;+ if (entry.mode === 'clear') {+ let decided: Decision = null;+ await scanLabelled(ctx.engine, [entry.source_id], row => { decided = classifyPrivateLabel(row); }, [entry.page_id]);+ const current = decided as Decision;+ if (!current || !('clear' in current) || current.clear !== entry.class || !sameLabels(current.removed, entry.labels)) return changed;+ next = Object.fromEntries(Object.entries(frontmatter).filter(([key]) => !Object.hasOwn(entry.labels, key)));+ } else {+ if (Object.keys(entry.labels).some(key => Object.hasOwn(frontmatter, key))) return changed;+ next = { ...frontmatter, ...entry.labels };+ }+ const requestId = await repairRequestId(ctx, 'private-labels', item, snapshot.revision);+ const line: LedgerLine = { at: new Date().toISOString(), brain_id: entry.brain_id, source_id: entry.source_id, slug: entry.slug, page_id: entry.page_id,+ revision_before: snapshot.revision, request_id: requestId, ...(entry.mode === 'clear' ? { removed: entry.labels } : { restored: entry.labels }) };+ const content = serializePageToMarkdown({ ...snapshot.page, frontmatter: next }, snapshot.tags);+ try {+ const authority = await maintenancePreflight(ctx.engine, entry.source_id);+ if (authority) await publishMaintenancePage(ctx.engine, authority, entry.slug, content, { expectedRevision: snapshot.revision, requestId, keepTrust: true });+ else if (!await importAtRevision(ctx.engine, entry, snapshot.revision, content, opts?.embed === true)) return changed;+ } catch (error) {+ if (acceptedPendingReceipt(error)) item.ledger.record(line);+ throw error;+ }+ item.ledger.record(line);+ return { applied: true, outcome: entry.mode === 'clear' ? 'cleared' : 'restored', detail: { ledger: item.ledger.path } };+ } finally {+ if (item.last && item.hash) await clearApprovedSet(ctx.engine, { command: 'private-labels', hash: item.hash });+ }+ },+ render(details) {+ const counts = details.counts as { before: Record<string, number>; after: Record<string, number> } | undefined;+ const line = (values: Record<string, number>) => Object.entries(values).map(([key, value]) => `${key}=${value}`).join(', ');+ return [...(counts ? [` before: ${line(counts.before)}`, ` after (this window applied): ${line(counts.after)}`] : []), ...(details.ledger ? [` ledger: ${String(details.ledger)}`] : [])];+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 9cedd007ce..44e6bead40 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -92,6 +92,7 @@ import { factClaimDatesRepair } from './fact-claim-dates.ts';import { provenanceRepair } from './provenance.ts';import { secretSpansRepair } from './secret-spans.ts';import { rowsBehindRepair } from './rows-behind.ts';+import { privateLabelsRepair, type PrivateLabelsLedger } from './private-labels.ts';import { generationsRepair, generationsSelectionArgv, type GenerationsSelection } from '../generations/repair.ts';import { restoreDaysHint } from '../generations/config.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';@@ -652,6 +653,16 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'join only with --include-ambiguous; rows with an uncommitted working-tree edit are left out. --apply --expect <hash> applies exactly that set. '+ 'Runs only when named; never on upgrade.',},+ 'private-labels': {+ handler: privateLabelsRepair, embeds: 'effect', checks: [], explicit_only: true, preview_bound: true,+ summary: 'Clear privacy labels writer templates over-stamped on ordinary pages: access: private (and the visibility: private stamped from it) is removed, '+ + 'which widens what remote callers that are not the brain owner can read. Real restrictions are kept and counted: pinned questions, derived pages '+ + '(atoms, synthesized concepts, chronicle events), access restricted or confidential, a confidentiality value, and visibility: private with no alias. '+ + 'The preview lists one window (--limit, default 1000) by class (alias, alias-and-visibility) with every category\'s count before and after; '+ + '--apply --expect <hash> applies exactly that window, one revision-bound page write each; a bare --apply is refused. Pages in git-canonical sources '+ + '(git-publish: clearing commits them into Git) run only with --class git-publish. Each cleared label is recorded in '+ + '<gbrain home>/repair/private-labels/<brain>.jsonl, and --class restore re-adds it. Runs only when named; never on upgrade.',+ },'generations': {handler: generationsRepair, embeds: 'effect', checks: ['generation_retirements', 'generation_held', 'generation_pending'], explicit_only: true, preview_bound: true, consent: 'destructive',consentText: {@@ -754,7 +765,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal; recordDatabaseStops?: boolean;prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; provenance?: string; cursor?: string; progress?: ProgressReporter;keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number; generations?: GenerationsSelection; day?: string; rules?: string[];- cwdPrefixes?: string[]; sessions?: string[]; principal?: string } = {}): Promise<RepairResult> {+ cwdPrefixes?: string[]; sessions?: string[]; principal?: string; privateLabelsLedger?: PrivateLabelsLedger } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;const spec = repairSpec(kind, opts.registry);return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag, spec,@@ -765,7 +776,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, includeCrossEntity: run.includeCrossEntity, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), ...(run.recordDatabaseStops ? { recordDatabaseStops: true } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage, generations: run.generations, day: run.day, rules: run.rules,- cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal });+ cwdPrefixes: run.cwdPrefixes, sessions: run.sessions, principal: run.principal, privateLabelsLedger: run.privateLabelsLedger });},};}diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 4f4bab07de..6400fc9b66 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -1316,7 +1316,7 @@ export function knobsHash(const privateReadable = ctx?.excludePrivate === true ? privateReadableSources() : [];if (privateReadable.length) parts.push(`xpr=${[...privateReadable].sort().join(',')}`);// GBRA-218 (append-only, no bump): a read under the read policy keys on its member identity (sorted at- // record time) and on an operator privacy relaxation; an unbound, unrelaxed read adds no part.+ // record time) and on a privacy relaxation (operator or, GST-2059, owner); an unbound, unrelaxed read adds no part.if (ctx?.excludePrivate === true) {const access = currentCallerAccess();if (access.identity.length) parts.push(`xid=${createHash('sha256').update(access.identity.join(',')).digest('hex').slice(0, 16)}`);diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 25c23bdb98..4343ba74dd 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -30,6 +30,13 @@ import { validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';+/**+ * GST-2059: the member who owns this brain (`gbrain access owner set <member>`). A remote credential or stdio server+ * bound to that live member reads as the owner: its privacy is relaxed in every source its grant reads (CallerAccess.owner).+ * Written only by the trusted local CLI, like mcp.stdio_member; unset, ill-formed or unreadable names no owner.+ */+export const OWNER_MEMBER_KEY = 'access.owner_member';+/*** #5525 — extracted atoms and synthesized concept pages are derived from* other pages or from private transcripts, so a missing `visibility` field on@@ -188,7 +195,14 @@ export function privatePagesFilterFragmentFast(pageAlias: string): string {* no-grant floor, federation, an OAuth client's bound source or a request's* `source_ids`); empty for writes;* - hidePrivate: false only when an operator relaxed privacy for remote reads- * (GBRAIN_REMOTE_PRIVATE_PAGES=1 or search.remote_private_pages=visible);+ * (GBRAIN_REMOTE_PRIVATE_PAGES=1 or search.remote_private_pages=visible),+ * or the caller is the brain owner (owner);+ * - owner: GST-2059, the caller's credential (or stdio server) is bound to the+ * live member config access.owner_member names, and it asserts no audience+ * other than that member; never an attested actor. The owner sees+ * visibility: private pages, privacy aliases, derived and pinned-question+ * pages and private facts in every source its grant reads; member access+ * (readable_by, folder rules) stays mandatory;* - restricted: false only inside a remote request on a brain whose config* access.restrictions_present was unset when the request began. Then no* page named readers at that moment and none predates the migration (v282@@ -225,6 +239,7 @@ export interface CallerAccess {folderCoverage: readonly FolderCoverage[];privateReadableSources: readonly string[];hidePrivate: boolean;+ owner: boolean;applyRemoteReadPolicy: boolean;restricted: boolean;/** The fresh remote policy (readRemotePolicyNow) a remote request read when it started; null outside one. */@@ -235,7 +250,7 @@ const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };+ return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -260,6 +275,7 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):folderCoverage: Object.freeze([...(access.folderCoverage ?? base.folderCoverage)].map(c => Object.freeze({ source_id: c.source_id, prefix: c.prefix }))),privateReadableSources: sources.length && sources.every(isValidSourceId) ? Object.freeze([...new Set(sources)]) : Object.freeze([]),hidePrivate: access.hidePrivate ?? base.hidePrivate,+ owner: access.owner ?? (fresh ? false : base.owner),applyRemoteReadPolicy: access.applyRemoteReadPolicy ?? base.applyRemoteReadPolicy,restricted: access.restricted ?? base.restricted,remotePolicy: access.remotePolicy ?? base.remotePolicy,@@ -281,6 +297,11 @@ export function privateReadableSources(): readonly string[] {return currentCallerAccess().privateReadableSources;}+/** GST-2059: is the current caller the brain owner (CallerAccess.owner)? False outside a remote record or a local --as of the owner. */+export function callerIsOwner(): boolean {+ return currentCallerAccess().owner;+}+/** The current caller's member identity; empty outside a bound remote read or a local --as, and for an audience of several entries (see callerIdentities). */export function callerIdentity(): readonly string[] {return currentCallerAccess().identity;@@ -793,7 +814,7 @@ export async function remotePrivacyRelaxed(engine: BrainEngine): Promise<booleanreturn expose;}-export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean }+export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ownerMember?: string | null }/*** The remote read policy read fresh, for publication: whether an operator@@ -804,10 +825,10 @@ export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean }*/export async function readRemotePolicyNow(engine: Pick<BrainEngine, 'executeRaw'>): Promise<RemotePolicy> {try {- const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[REMOTE_PRIVATE_PAGES_KEY, ACCESS_RESTRICTIONS_KEY]]);+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[REMOTE_PRIVATE_PAGES_KEY, ACCESS_RESTRICTIONS_KEY, OWNER_MEMBER_KEY]]);return remotePolicyFrom(Object.fromEntries(rows.map(r => [r.key, r.value])));} catch {- return { privacyRelaxed: process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1', restricted: true };+ return { privacyRelaxed: process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1', restricted: true, ownerMember: null };}}@@ -823,7 +844,9 @@ export async function requestRemotePolicy(engine: BrainEngine): Promise<RemotePofunction remotePolicyFrom(config: Record<string, string>): RemotePolicy {const hatch = process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1';- return { privacyRelaxed: hatch || ['visible', 'true', '1'].includes(config[REMOTE_PRIVATE_PAGES_KEY] ?? ''), restricted: config[ACCESS_RESTRICTIONS_KEY] === '1' };+ const owner = config[OWNER_MEMBER_KEY]?.trim();+ return { privacyRelaxed: hatch || ['visible', 'true', '1'].includes(config[REMOTE_PRIVATE_PAGES_KEY] ?? ''), restricted: config[ACCESS_RESTRICTIONS_KEY] === '1',+ ownerMember: owner && ACCESS_ID_RE.test(owner) ? owner : null };}/** GBRA-218: does this brain hold member-access restrictions? Read live (the request snapshot answers it inside a read); unreadable counts as yes. */diff --git a/src/core/skills/bundled-skills.generated.ts b/src/core/skills/bundled-skills.generated.tsindex dbf9cea9cb..04c1d49c22 100644--- a/src/core/skills/bundled-skills.generated.ts+++ b/src/core/skills/bundled-skills.generated.ts@@ -31,63 +31,64 @@ import f28 from '../../../skills/conventions/cron-via-minions.md' with { type: 'import f29 from '../../../skills/conventions/cross-modal.yaml' with { type: 'text' };import f30 from '../../../skills/conventions/exec-output.md' with { type: 'text' };import f31 from '../../../skills/conventions/model-routing.md' with { type: 'text' };-import f32 from '../../../skills/conventions/quality.md' with { type: 'text' };-import f33 from '../../../skills/conventions/regex-discipline.md' with { type: 'text' };-import f34 from '../../../skills/conventions/schema-evolution.md' with { type: 'text' };-import f35 from '../../../skills/conventions/subagent-routing.md' with { type: 'text' };-import f36 from '../../../skills/conventions/test-before-bulk.md' with { type: 'text' };-import f37 from '../../../skills/conventions/untrusted-content.md' with { type: 'text' };-import f38 from '../../../skills/conversation-archive/SKILL.md' with { type: 'text' };-import f39 from '../../../skills/correction-pipeline/SKILL.md' with { type: 'text' };-import f40 from '../../../skills/cron-scheduler/SKILL.md' with { type: 'text' };-import f41 from '../../../skills/cross-modal-review/SKILL.md' with { type: 'text' };-import f42 from '../../../skills/daily-task-manager/SKILL.md' with { type: 'text' };-import f43 from '../../../skills/daily-task-prep/SKILL.md' with { type: 'text' };-import f44 from '../../../skills/data-loss-gate/SKILL.md' with { type: 'text' };-import f45 from '../../../skills/data-research/SKILL.md' with { type: 'text' };-import f46 from '../../../skills/db-repair/SKILL.md' with { type: 'text' };-import f47 from '../../../skills/draft-in-voice/SKILL.md' with { type: 'text' };-import f48 from '../../../skills/eiirp/SKILL.md' with { type: 'text' };-import f49 from '../../../skills/enrich/SKILL.md' with { type: 'text' };-import f50 from '../../../skills/fact-check/SKILL.md' with { type: 'text' };-import f51 from '../../../skills/frontmatter-guard/SKILL.md' with { type: 'text' };-import f52 from '../../../skills/functional-area-resolver/SKILL.md' with { type: 'text' };-import f53 from '../../../skills/gbrain-advisor/SKILL.md' with { type: 'text' };-import f54 from '../../../skills/gbrain-upgrade/SKILL.md' with { type: 'text' };-import f55 from '../../../skills/google-loops/SKILL.md' with { type: 'text' };-import f56 from '../../../skills/idea-ingest/SKILL.md' with { type: 'text' };-import f57 from '../../../skills/idea-lineage/SKILL.md' with { type: 'text' };-import f58 from '../../../skills/ingest/SKILL.md' with { type: 'text' };-import f59 from '../../../skills/maintain/SKILL.md' with { type: 'text' };-import f60 from '../../../skills/mcp-access/SKILL.md' with { type: 'text' };-import f61 from '../../../skills/measure-before-you-fix/SKILL.md' with { type: 'text' };-import f62 from '../../../skills/media-ingest/SKILL.md' with { type: 'text' };-import f63 from '../../../skills/meeting-ingestion/SKILL.md' with { type: 'text' };-import f64 from '../../../skills/migrate/SKILL.md' with { type: 'text' };-import f65 from '../../../skills/minion-orchestrator/SKILL.md' with { type: 'text' };-import f66 from '../../../skills/perplexity-research/SKILL.md' with { type: 'text' };-import f67 from '../../../skills/postgres-adopt/SKILL.md' with { type: 'text' };-import f68 from '../../../skills/publish/SKILL.md' with { type: 'text' };-import f69 from '../../../skills/query/SKILL.md' with { type: 'text' };-import f70 from '../../../skills/remote-mcp/SKILL.md' with { type: 'text' };-import f71 from '../../../skills/repo-architecture/SKILL.md' with { type: 'text' };-import f72 from '../../../skills/reports/SKILL.md' with { type: 'text' };-import f73 from '../../../skills/research-compendium/SKILL.md' with { type: 'text' };-import f74 from '../../../skills/resolve-before-asking/SKILL.md' with { type: 'text' };-import f75 from '../../../skills/schema-author/SKILL.md' with { type: 'text' };-import f76 from '../../../skills/schema-unify/SKILL.md' with { type: 'text' };-import f77 from '../../../skills/setup/SKILL.md' with { type: 'text' };-import f78 from '../../../skills/signal-detector/SKILL.md' with { type: 'text' };-import f79 from '../../../skills/skill-creator/SKILL.md' with { type: 'text' };-import f80 from '../../../skills/skill-optimizer/SKILL.md' with { type: 'text' };-import f81 from '../../../skills/skill-optimizer/skillopt-benchmark.jsonl' with { type: 'text' };-import f82 from '../../../skills/skillpack-check/SKILL.md' with { type: 'text' };-import f83 from '../../../skills/smoke-test/SKILL.md' with { type: 'text' };-import f84 from '../../../skills/soul-audit/SKILL.md' with { type: 'text' };-import f85 from '../../../skills/strategic-reading/SKILL.md' with { type: 'text' };-import f86 from '../../../skills/two-tier-extraction/SKILL.md' with { type: 'text' };-import f87 from '../../../skills/voice-note-ingest/SKILL.md' with { type: 'text' };-import f88 from '../../../skills/webhook-transforms/SKILL.md' with { type: 'text' };+import f32 from '../../../skills/conventions/page-privacy.md' with { type: 'text' };+import f33 from '../../../skills/conventions/quality.md' with { type: 'text' };+import f34 from '../../../skills/conventions/regex-discipline.md' with { type: 'text' };+import f35 from '../../../skills/conventions/schema-evolution.md' with { type: 'text' };+import f36 from '../../../skills/conventions/subagent-routing.md' with { type: 'text' };+import f37 from '../../../skills/conventions/test-before-bulk.md' with { type: 'text' };+import f38 from '../../../skills/conventions/untrusted-content.md' with { type: 'text' };+import f39 from '../../../skills/conversation-archive/SKILL.md' with { type: 'text' };+import f40 from '../../../skills/correction-pipeline/SKILL.md' with { type: 'text' };+import f41 from '../../../skills/cron-scheduler/SKILL.md' with { type: 'text' };+import f42 from '../../../skills/cross-modal-review/SKILL.md' with { type: 'text' };+import f43 from '../../../skills/daily-task-manager/SKILL.md' with { type: 'text' };+import f44 from '../../../skills/daily-task-prep/SKILL.md' with { type: 'text' };+import f45 from '../../../skills/data-loss-gate/SKILL.md' with { type: 'text' };+import f46 from '../../../skills/data-research/SKILL.md' with { type: 'text' };+import f47 from '../../../skills/db-repair/SKILL.md' with { type: 'text' };+import f48 from '../../../skills/draft-in-voice/SKILL.md' with { type: 'text' };+import f49 from '../../../skills/eiirp/SKILL.md' with { type: 'text' };+import f50 from '../../../skills/enrich/SKILL.md' with { type: 'text' };+import f51 from '../../../skills/fact-check/SKILL.md' with { type: 'text' };+import f52 from '../../../skills/frontmatter-guard/SKILL.md' with { type: 'text' };+import f53 from '../../../skills/functional-area-resolver/SKILL.md' with { type: 'text' };+import f54 from '../../../skills/gbrain-advisor/SKILL.md' with { type: 'text' };+import f55 from '../../../skills/gbrain-upgrade/SKILL.md' with { type: 'text' };+import f56 from '../../../skills/google-loops/SKILL.md' with { type: 'text' };+import f57 from '../../../skills/idea-ingest/SKILL.md' with { type: 'text' };+import f58 from '../../../skills/idea-lineage/SKILL.md' with { type: 'text' };+import f59 from '../../../skills/ingest/SKILL.md' with { type: 'text' };+import f60 from '../../../skills/maintain/SKILL.md' with { type: 'text' };+import f61 from '../../../skills/mcp-access/SKILL.md' with { type: 'text' };+import f62 from '../../../skills/measure-before-you-fix/SKILL.md' with { type: 'text' };+import f63 from '../../../skills/media-ingest/SKILL.md' with { type: 'text' };+import f64 from '../../../skills/meeting-ingestion/SKILL.md' with { type: 'text' };+import f65 from '../../../skills/migrate/SKILL.md' with { type: 'text' };+import f66 from '../../../skills/minion-orchestrator/SKILL.md' with { type: 'text' };+import f67 from '../../../skills/perplexity-research/SKILL.md' with { type: 'text' };+import f68 from '../../../skills/postgres-adopt/SKILL.md' with { type: 'text' };+import f69 from '../../../skills/publish/SKILL.md' with { type: 'text' };+import f70 from '../../../skills/query/SKILL.md' with { type: 'text' };+import f71 from '../../../skills/remote-mcp/SKILL.md' with { type: 'text' };+import f72 from '../../../skills/repo-architecture/SKILL.md' with { type: 'text' };+import f73 from '../../../skills/reports/SKILL.md' with { type: 'text' };+import f74 from '../../../skills/research-compendium/SKILL.md' with { type: 'text' };+import f75 from '../../../skills/resolve-before-asking/SKILL.md' with { type: 'text' };+import f76 from '../../../skills/schema-author/SKILL.md' with { type: 'text' };+import f77 from '../../../skills/schema-unify/SKILL.md' with { type: 'text' };+import f78 from '../../../skills/setup/SKILL.md' with { type: 'text' };+import f79 from '../../../skills/signal-detector/SKILL.md' with { type: 'text' };+import f80 from '../../../skills/skill-creator/SKILL.md' with { type: 'text' };+import f81 from '../../../skills/skill-optimizer/SKILL.md' with { type: 'text' };+import f82 from '../../../skills/skill-optimizer/skillopt-benchmark.jsonl' with { type: 'text' };+import f83 from '../../../skills/skillpack-check/SKILL.md' with { type: 'text' };+import f84 from '../../../skills/smoke-test/SKILL.md' with { type: 'text' };+import f85 from '../../../skills/soul-audit/SKILL.md' with { type: 'text' };+import f86 from '../../../skills/strategic-reading/SKILL.md' with { type: 'text' };+import f87 from '../../../skills/two-tier-extraction/SKILL.md' with { type: 'text' };+import f88 from '../../../skills/voice-note-ingest/SKILL.md' with { type: 'text' };+import f89 from '../../../skills/webhook-transforms/SKILL.md' with { type: 'text' };export interface BundledSkillMeta { name: string; audience: 'owner' | 'downstream'; assets: string[] }@@ -227,6 +228,7 @@ export const BUNDLED_SKILLS: readonly BundledSkillMeta[] = ["conventions/agent-operator-protocol.md","conventions/brain-first.md","conventions/cron-via-minions.md",+ "conventions/page-privacy.md","conventions/quality.md","conventions/subagent-routing.md","conventions/test-before-bulk.md",@@ -444,6 +446,7 @@ export const BUNDLED_SKILLS: readonly BundledSkillMeta[] = ["audience": "owner","assets": ["conventions/agent-operator-protocol.md",+ "conventions/page-privacy.md","conventions/quality.md"]},@@ -798,61 +801,62 @@ export const BUNDLED_SKILL_FILES: Readonly<Record<string, string>> = {"conventions/cross-modal.yaml": f29,"conventions/exec-output.md": f30,"conventions/model-routing.md": f31,- "conventions/quality.md": f32,- "conventions/regex-discipline.md": f33,- "conventions/schema-evolution.md": f34,- "conventions/subagent-routing.md": f35,- "conventions/test-before-bulk.md": f36,- "conventions/untrusted-content.md": f37,- "conversation-archive/SKILL.md": f38,- "correction-pipeline/SKILL.md": f39,- "cron-scheduler/SKILL.md": f40,- "cross-modal-review/SKILL.md": f41,- "daily-task-manager/SKILL.md": f42,- "daily-task-prep/SKILL.md": f43,- "data-loss-gate/SKILL.md": f44,- "data-research/SKILL.md": f45,- "db-repair/SKILL.md": f46,- "draft-in-voice/SKILL.md": f47,- "eiirp/SKILL.md": f48,- "enrich/SKILL.md": f49,- "fact-check/SKILL.md": f50,- "frontmatter-guard/SKILL.md": f51,- "functional-area-resolver/SKILL.md": f52,- "gbrain-advisor/SKILL.md": f53,- "gbrain-upgrade/SKILL.md": f54,- "google-loops/SKILL.md": f55,- "idea-ingest/SKILL.md": f56,- "idea-lineage/SKILL.md": f57,- "ingest/SKILL.md": f58,- "maintain/SKILL.md": f59,- "mcp-access/SKILL.md": f60,- "measure-before-you-fix/SKILL.md": f61,- "media-ingest/SKILL.md": f62,- "meeting-ingestion/SKILL.md": f63,- "migrate/SKILL.md": f64,- "minion-orchestrator/SKILL.md": f65,- "perplexity-research/SKILL.md": f66,- "postgres-adopt/SKILL.md": f67,- "publish/SKILL.md": f68,- "query/SKILL.md": f69,- "remote-mcp/SKILL.md": f70,- "repo-architecture/SKILL.md": f71,- "reports/SKILL.md": f72,- "research-compendium/SKILL.md": f73,- "resolve-before-asking/SKILL.md": f74,- "schema-author/SKILL.md": f75,- "schema-unify/SKILL.md": f76,- "setup/SKILL.md": f77,- "signal-detector/SKILL.md": f78,- "skill-creator/SKILL.md": f79,- "skill-optimizer/SKILL.md": f80,- "skill-optimizer/skillopt-benchmark.jsonl": f81,- "skillpack-check/SKILL.md": f82,- "smoke-test/SKILL.md": f83,- "soul-audit/SKILL.md": f84,- "strategic-reading/SKILL.md": f85,- "two-tier-extraction/SKILL.md": f86,- "voice-note-ingest/SKILL.md": f87,- "webhook-transforms/SKILL.md": f88,+ "conventions/page-privacy.md": f32,+ "conventions/quality.md": f33,+ "conventions/regex-discipline.md": f34,+ "conventions/schema-evolution.md": f35,+ "conventions/subagent-routing.md": f36,+ "conventions/test-before-bulk.md": f37,+ "conventions/untrusted-content.md": f38,+ "conversation-archive/SKILL.md": f39,+ "correction-pipeline/SKILL.md": f40,+ "cron-scheduler/SKILL.md": f41,+ "cross-modal-review/SKILL.md": f42,+ "daily-task-manager/SKILL.md": f43,+ "daily-task-prep/SKILL.md": f44,+ "data-loss-gate/SKILL.md": f45,+ "data-research/SKILL.md": f46,+ "db-repair/SKILL.md": f47,+ "draft-in-voice/SKILL.md": f48,+ "eiirp/SKILL.md": f49,+ "enrich/SKILL.md": f50,+ "fact-check/SKILL.md": f51,+ "frontmatter-guard/SKILL.md": f52,+ "functional-area-resolver/SKILL.md": f53,+ "gbrain-advisor/SKILL.md": f54,+ "gbrain-upgrade/SKILL.md": f55,+ "google-loops/SKILL.md": f56,+ "idea-ingest/SKILL.md": f57,+ "idea-lineage/SKILL.md": f58,+ "ingest/SKILL.md": f59,+ "maintain/SKILL.md": f60,+ "mcp-access/SKILL.md": f61,+ "measure-before-you-fix/SKILL.md": f62,+ "media-ingest/SKILL.md": f63,+ "meeting-ingestion/SKILL.md": f64,+ "migrate/SKILL.md": f65,+ "minion-orchestrator/SKILL.md": f66,+ "perplexity-research/SKILL.md": f67,+ "postgres-adopt/SKILL.md": f68,+ "publish/SKILL.md": f69,+ "query/SKILL.md": f70,+ "remote-mcp/SKILL.md": f71,+ "repo-architecture/SKILL.md": f72,+ "reports/SKILL.md": f73,+ "research-compendium/SKILL.md": f74,+ "resolve-before-asking/SKILL.md": f75,+ "schema-author/SKILL.md": f76,+ "schema-unify/SKILL.md": f77,+ "setup/SKILL.md": f78,+ "signal-detector/SKILL.md": f79,+ "skill-creator/SKILL.md": f80,+ "skill-optimizer/SKILL.md": f81,+ "skill-optimizer/skillopt-benchmark.jsonl": f82,+ "skillpack-check/SKILL.md": f83,+ "smoke-test/SKILL.md": f84,+ "soul-audit/SKILL.md": f85,+ "strategic-reading/SKILL.md": f86,+ "two-tier-extraction/SKILL.md": f87,+ "voice-note-ingest/SKILL.md": f88,+ "webhook-transforms/SKILL.md": f89,};diff --git a/test/access-owner-reads.test.ts b/test/access-owner-reads.test.tsnew file mode 100644index 0000000000..103ec5c42e--- /dev/null+++ b/test/access-owner-reads.test.ts@@ -0,0 +1,207 @@+/**+ * GST-2059: the brain owner reads the whole personal brain over remote MCP.+ *+ * 1. Protects: a credential bound to the member config access.owner_member names (`gbrain access owner set`),+ * and every delegate credential bound to the same member, reads visibility: private pages, privacy-alias pages+ * (access: private), derived pages that default to private and private facts through get_page, search, query and+ * recall. Every other caller keeps exactly the read policy it had: another member, an unbound token, the owner's+ * credential speaking for a channel audience, and the owner after `gbrain access owner clear`. Member access+ * (readable_by) stays mandatory for the owner too.+ * 2. Fails when: the owner's agent gets not_found for its own private pages, or any non-owner caller sees one.+ * 3. Real seams: tokens minted by the token service and verified by the serve --http verifier, dispatched through MCP+ * dispatch as serve-http-mcp does (remote: true), on a repo-less brain (no git checkout); embeddings stubbed.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { clearOwner, ownerView, setOwner } from '../src/core/access/owner.ts';+import { bindCredential } from '../src/core/access/members.ts';+import { accessCheck } from '../src/commands/access.ts';+import { openAsPreview } from '../src/cli/as-preview.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DIMS = 1536;+function vectorFor(text: string): number[] {+ const v = new Array<number>(DIMS).fill(0);+ for (const w of text.toLowerCase().match(/[a-z]+/g) ?? []) {+ let h = 0;+ for (const ch of w) h = (h * 31 + ch.charCodeAt(0)) >>> 0;+ v[h % DIMS] += 1;+ }+ const n = Math.hypot(...v) || 1;+ return v.map(x => x / n);+}++const SRC = 'own-src';+const OWNER = 'owner-example';+/** Pages the owner reads and no other remote caller does. */+const PRIVATE = {+ flagged: { slug: 'notes/flagged-plan', canary: 'canaryownflag', fm: ['visibility: private'] },+ aliased: { slug: 'notes/aliased-plan', canary: 'canaryownalias', fm: ['access: private'] },+ derived: { slug: 'atoms/derived-plan', canary: 'canaryownatom', fm: ['type: atom', 'source_slug: notes/open-plan'] },+} as const;+type PrivateKey = keyof typeof PRIVATE;+const OPEN = { slug: 'notes/open-plan', canary: 'canaryownopen' };+/** Another person's page: member access keeps it from the owner too. */+const BOBS = { slug: 'notes/bob-plan', canary: 'canaryownbob' };+const PRIVATE_FACT = 'canaryownfact';++const pageText = (title: string, canary: string, fm: readonly string[]) =>+ ['---', ...(fm.some(l => l.startsWith('type:')) ? [] : ['type: note']), `title: ${title}`, ...fm, '---', `# ${title}`, '', `Harbor ledger planning notes ${canary} for the roadmap.`].join('\n');++/** The four read paths the owner must have, each with arguments the page answers. */+function reads(slug: string): Array<[string, string, Record<string, unknown>]> {+ return [+ ['get_page', 'get_page', { slug }],+ ['search', 'search', { query: 'harbor ledger planning notes', fields: 'full', limit: 20 }],+ ['search keyword', 'search', { query: 'planning notes', match: 'keyword', fields: 'full', limit: 20 }],+ ['query', 'query', { query: 'harbor ledger planning notes', expand: false, fields: 'full', limit: 20 }],+ ['recall', 'recall', { query: 'harbor ledger planning notes' }],+ ];+}++for (const kind of testBackends()) {+ describe(`owner reads (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const tokens: Record<string, string> = {};+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });++ async function call(who: string, op: string, params: Record<string, unknown>, header?: string): Promise<{ isError: boolean; text: string; meta: Record<string, unknown> | undefined }> {+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;+ const sourceId = auth.sourceId ?? 'default';+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);+ const out = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: auth.takesHoldersAllowList ?? ['world'],+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), ...(header ? { onBehalfOf: { header } } : {}),+ });+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n'), meta: out._meta as Record<string, unknown> | undefined };+ }++ /** Which private pages `who` sees, per read path (get_page echoes the slug in its not_found, so content decides). */+ async function privateSeenBy(who: string, header?: string): Promise<Record<string, PrivateKey[]>> {+ const out: Record<string, PrivateKey[]> = {};+ for (const key of Object.keys(PRIVATE) as PrivateKey[]) {+ for (const [label, op, params] of reads(PRIVATE[key].slug)) {+ const { text } = await call(who, op, params, header);+ if (text.includes(PRIVATE[key].canary)) (out[label] ??= []).push(key);+ }+ }+ return out;+ }++ const ALL: Record<string, PrivateKey[]> = Object.fromEntries(reads('x').map(([label]) => [label, label === 'get_page' ? ['flagged', 'aliased', 'derived'] : ['flagged', 'aliased', 'derived']]));++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await importFromContent(engine, OPEN.slug, pageText('Open plan', OPEN.canary, []), { sourceId: SRC });+ for (const key of Object.keys(PRIVATE) as PrivateKey[]) {+ await importFromContent(engine, PRIVATE[key].slug, pageText(`${key} plan`, PRIVATE[key].canary, PRIVATE[key].fm), { sourceId: SRC });+ }+ await importFromContent(engine, BOBS.slug, pageText('Bob plan', BOBS.canary, ['readable_by: [bob-example]']), { sourceId: SRC });+ const fact = await dispatchToolCall(engine, 'remember', { fact: `Harbor ledger planning notes ${PRIVATE_FACT}`, provenance: 'fixture', entity: OPEN.slug, visibility: 'private' }, { remote: false, sourceId: SRC });+ if (fact.isError) throw new Error(`fixture remember: ${fact.content.map(c => c.text).join(' ')}`);+ for (const id of [OWNER, 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);+ const mint = async (name: string, member?: string, mayActFor?: string[]) => {+ const minted = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ tokens[name] = minted.token;+ if (member) await bindCredential(engine, { kind: 'token', id: minted.id }, { member, ...(mayActFor ? { mayActFor } : {}) });+ };+ await mint('owner', OWNER, [`member:${OWNER}`, 'member:bob-example']);+ await mint('delegate', OWNER);+ await mint('bob', 'bob-example');+ await mint('unbound');+ await setOwner(engine, OWNER);+ }, 240_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('fixture control: a trusted local caller reads every private page and the private fact', async () => {+ for (const key of Object.keys(PRIVATE) as PrivateKey[]) {+ const out = await dispatchToolCall(engine, 'get_page', { slug: PRIVATE[key].slug }, { remote: false, sourceId: SRC });+ expect({ key, seen: out.content.map(c => c.text).join('\n').includes(PRIVATE[key].canary) }).toEqual({ key, seen: true });+ }+ const recall = await dispatchToolCall(engine, 'recall', { query: 'harbor ledger planning notes' }, { remote: false, sourceId: SRC });+ expect(recall.content.map(c => c.text).join('\n')).toContain(PRIVATE_FACT);+ });++ test('the owner and a delegate bound to the owner read every private page through get_page, search, query and recall', async () => {+ expect(await privateSeenBy('owner')).toEqual(ALL);+ expect(await privateSeenBy('delegate')).toEqual(ALL);+ }, 240_000);++ test('the owner recalls private facts; no other caller does', async () => {+ for (const who of ['owner', 'delegate']) expect({ who, seen: (await call(who, 'recall', { query: 'harbor ledger planning notes' })).text.includes(PRIVATE_FACT) }).toEqual({ who, seen: true });+ for (const who of ['bob', 'unbound']) expect({ who, seen: (await call(who, 'recall', { query: 'harbor ledger planning notes' })).text.includes(PRIVATE_FACT) }).toEqual({ who, seen: false });+ }, 120_000);++ test('another member and an unbound token still see no private page on any path, after the owner read them', async () => {+ expect(await privateSeenBy('bob')).toEqual({});+ expect(await privateSeenBy('unbound')).toEqual({});+ }, 240_000);++ test('member access stays mandatory for the owner: another person\'s readable_by page is not_found', async () => {+ const own = await call('owner', 'get_page', { slug: BOBS.slug });+ expect(own.text).not.toContain(BOBS.canary);+ expect((await call('bob', 'get_page', { slug: BOBS.slug })).text).toContain(BOBS.canary);+ });++ test('the owner speaking for a channel audience reads no private page; for itself alone it keeps the relaxation', async () => {+ expect(await privateSeenBy('owner', `member:${OWNER},member:bob-example`)).toEqual({});+ expect((await call('owner', 'get_page', { slug: PRIVATE.flagged.slug }, `member:${OWNER}`)).text).toContain(PRIVATE.flagged.canary);+ }, 240_000);++ test('_meta.access names the owner relaxation only for owner reads', async () => {+ const relaxation = async (who: string) => ((await call(who, 'get_page', { slug: OPEN.slug })).meta?.access as { relaxation?: string } | undefined)?.relaxation;+ expect(await relaxation('owner')).toBe('owner');+ expect(await relaxation('bob')).toBe('none');+ expect(await relaxation('unbound')).toBe('none');+ });++ test('access check and --as preview report the owner view', async () => {+ expect((await accessCheck(engine, { token: 'owner' })).owner).toBe(true);+ expect((await accessCheck(engine, { token: 'bob' })).owner).toBe(false);+ const asOwner = await openAsPreview(engine, OWNER, 'get');+ const page = await asOwner.run(() => dispatchToolCall(engine, 'get_page', { slug: PRIVATE.aliased.slug }, asOwner.context({ remote: false, sourceId: SRC })));+ expect(page.content.map(c => c.text).join('\n')).toContain(PRIVATE.aliased.canary);+ const asBob = await openAsPreview(engine, 'bob-example', 'get');+ const hidden = await asBob.run(() => dispatchToolCall(engine, 'get_page', { slug: PRIVATE.aliased.slug }, asBob.context({ remote: false, sourceId: SRC })));+ expect(hidden.content.map(c => c.text).join('\n')).not.toContain(PRIVATE.aliased.canary);+ });++ test('with no owner named, the owner\'s credential reads like any member again', async () => {+ expect((await ownerView(engine)).bound_credentials.map(c => c.name).sort()).toEqual(['delegate', 'owner']);+ await clearOwner(engine);+ try {+ expect(await privateSeenBy('owner')).toEqual({});+ } finally {+ await setOwner(engine, OWNER);+ }+ }, 240_000);++ test('setting a disabled or unknown member as owner is refused and leaves the owner unchanged', async () => {+ await expect(setOwner(engine, 'nobody-example')).rejects.toThrow();+ await expect(setOwner(engine, 'Not Valid')).rejects.toThrow();+ expect((await ownerView(engine)).owner).toBe(OWNER);+ });+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 72ad5657dd..9f6b210347 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -21,6 +21,7 @@ test/access-member-facts.test.tstest/access-member-sweep.test.tstest/access-members.test.tstest/access-on-behalf-of.test.ts+test/access-owner-reads.test.tstest/access-page-indexes-online.test.tstest/access-qm-actor.test.tstest/access-writes.test.tsdiff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex 22e15dabbd..1f7d773808 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind'];+const EXPLICIT: RepairKind[] = ['accepted-takes', 'google-file-modes', 'stale-atoms', 'atoms-restore', 'extractor-facts', 'unwithdrawn-facts', 'conversation-labels', 'captured-facts', 'agent-session-facts', 'redacted-facts', 'loop-facts', 'ontology-facts', 'facts-rehome', 'consolidate-ties', 'duplicate-facts', 'orphan-children', 'failed-writes', 'split-facts', 'frontmatter', 'timeline-comments', 'timeline-order', 'contact-rows', 'managed-sync-orphans', 'content-receipt-root', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'ghost-pages', 'origin-twins', 'receipt-compaction', 'aliases', 'rename-identity', 'overwritten-edits', 'legacy-twins', 'missing-tables', 'url-clone-fences', 'segmented-mirror', 'segmented-tiling', 'uncommitted-deletions', 'generations', 'fact-claim-dates', 'provenance', 'secret-spans', 'rows-behind', 'private-labels'];// GBRA-161: the generations preview carries its ledger kind and the restore window, so the printed command runs as is.const PREVIEW = (kind: RepairKind): string => kind === 'generations' ? 'gbrain repair generations --kind atom --since 30d' : `gbrain repair ${kind}`;let engine: PGLiteEngine;diff --git a/test/repair-private-labels.test.ts b/test/repair-private-labels.test.tsnew file mode 100644index 0000000000..5057e5bf60--- /dev/null+++ b/test/repair-private-labels.test.ts@@ -0,0 +1,317 @@+/**+ * gbrain repair private-labels: classify the privacy labels live pages carry+ * into KEEP (a real restriction) and CLEAR (an over-stamped access: private),+ * and clear the CLEAR ones through revision-bound page writes, reversibly.+ *+ * 1. Protects: only alias and alias-and-visibility pages lose their label;+ * restricted, confidential, explicit, pinned-question and derived pages keep+ * theirs byte for byte; a git-canonical source's pages wait for+ * --class git-publish; a bare --apply clears nothing; a page edited since the+ * preview is skipped; --class restore puts back exactly what was removed.+ * 2. Fails when: a keep page changes, the body or another key changes, the+ * ledger misses a line or an original value, or restore re-adds something+ * other than the recorded value.+ * 3. Real seams: repo-less PGLite, the registered handler driven through the+ * gbrain repair command entry (argument parse, runner, runRepair).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import { EXPLICIT_REPAIR_REGISTRY, PREVIEW_BOUND_REPAIR_REGISTRY, repairRunner, repairSpec } from '../src/core/repair/registry.ts';+import { resolveRepairScope } from '../src/core/repair/core.ts';+import { withEnv } from './helpers/with-env.ts';+import { withCoordinatedWrite, withTrustBackfill } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++let engine: PGLiteEngine;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-private-labels-'));+const GIT_SOURCE = 'source-a';+const NL = String.fromCharCode(10);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++async function capture(fn: () => Promise<void>): Promise<string> {+ let printed = '';+ const original = console.log;+ console.log = (...parts: unknown[]) => { printed += parts.map(String).join(' ') + NL; };+ try { await fn(); } finally { console.log = original; }+ return printed;+}++const run = (argv: string[]) => withEnv({ GBRAIN_HOME: dir, GBRAIN_INTERACTIVE: '0', CI: '1' }, () => capture(() => runRepairCommand(engine, argv)));+const json = async (argv: string[]) => { const out = JSON.parse(await run([...argv, '--json'])).results[0]; _resetCliExitVerdictForTests(); return out; };+const ledgerPath = (brainId: string) => join(dir, '.gbrain', 'repair', 'private-labels', brainId + '.jsonl');+const ledgerLines = (brainId: string) => readFileSync(ledgerPath(brainId), 'utf8').trim().split(NL).map(line => JSON.parse(line));++async function refusal(fn: () => Promise<unknown>): Promise<OperationError> {+ try { await fn(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const SEEDS: Array<{ slug: string; type: string; frontmatter: Record<string, unknown>; source?: string }> = [+ { slug: 'notes/alias', type: 'note', frontmatter: { access: 'private', status: 'draft' } },+ { slug: 'notes/readers', type: 'note', frontmatter: { access: 'private', readable_by: ['alice-example'] } },+ { slug: 'notes/alias-vis', type: 'note', frontmatter: { access: 'Private', visibility: 'private', topic: 'research' } },+ { slug: 'notes/restricted', type: 'note', frontmatter: { access: 'restricted' } },+ { slug: 'notes/secret', type: 'note', frontmatter: { access: 'private', confidentiality: 'secret' } },+ { slug: 'notes/explicit', type: 'note', frontmatter: { visibility: 'private' } },+ { slug: 'questions/pinned', type: 'note', frontmatter: { pinned_question: true, access: 'private' } },+ { slug: 'atoms/a', type: 'atom', frontmatter: { access: 'private', source_slug: 'notes/plain' } },+ { slug: 'notes/plain', type: 'note', frontmatter: {} },+ { slug: 'notes/a', type: 'note', frontmatter: { access: 'private' }, source: GIT_SOURCE },+];+const KEEP = ['notes/restricted', 'notes/secret', 'notes/explicit', 'questions/pinned', 'atoms/a', 'notes/plain'];+const ALL_CLEARED = { pinned_question: 1, derived: 1, strong_alias: 2, explicit_visibility: 1, alias: 0, 'alias-and-visibility': 0, 'git-publish': 1 };++interface Row { frontmatter: Record<string, unknown>; compiled_truth: string; revision: string; page_id: number }+async function row(slug: string, source = 'default'): Promise<Row> {+ const [r] = await engine.executeRaw<Row>('SELECT frontmatter, compiled_truth, knowledge_revision::text AS revision, id AS page_id '+ + 'FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [source, slug]);+ return r!;+}++const body = (slug: string) => slug + ' body text.' + NL + NL + 'A second paragraph for ' + slug + '.';+async function seed(slug: string, type: string, frontmatter: Record<string, unknown>, source = 'default', text = body(slug)) {+ const result = await importFromContent(engine, slug, serializeMarkdown(frontmatter, text, '', { type: type as never, title: slug, tags: ['t1'] }),+ { noEmbed: true, forceRechunk: true, sourceId: source });+ expect(['imported', 'skipped']).toContain(result.status);+}++describe('repair private-labels', () => {+ let keepBefore: Record<string, Row> = {};+ let firstHash = '';+ let brainId = '';++ test('registered explicit-only and preview-bound', () => {+ const spec = repairSpec('private-labels');+ expect(spec.explicit_only).toBe(true);+ expect(spec.preview_bound).toBe(true);+ expect(spec.embeds).toBe('effect');+ expect(EXPLICIT_REPAIR_REGISTRY.map(s => s.kind)).toContain('private-labels');+ expect(PREVIEW_BOUND_REPAIR_REGISTRY.map(s => s.kind)).toContain('private-labels');+ });++ test('the preview counts every category over the scope, projects the window, lists the clear items and saves a hash', async () => {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [GIT_SOURCE]);+ for (const s of SEEDS) await seed(s.slug, s.type, s.frontmatter, s.source);+ // A git-canonical source refuses a direct import, so its page is seeded first (as the conversion would have found it).+ await engine.executeRaw('UPDATE sources SET config = $2::jsonb WHERE id = $1', [GIT_SOURCE, JSON.stringify({ canonical: 'git' })]);+ keepBefore = Object.fromEntries(await Promise.all(KEEP.map(async slug => [slug, await row(slug)] as const)));+ const preview = await json(['private-labels']);+ brainId = preview.scope.brain_id;+ expect(preview.mode).toBe('dry_run');+ expect(preview.details.counts.before).toEqual({ pinned_question: 1, derived: 1, strong_alias: 2, explicit_visibility: 1, alias: 2, 'alias-and-visibility': 1, 'git-publish': 1 });+ expect(preview.details.counts.after).toEqual(ALL_CLEARED);+ expect(preview.listing).toEqual([+ { item: 'default:notes/alias', class: 'alias', detail: 'remove access: private' },+ { item: 'default:notes/readers', class: 'alias', detail: 'remove access: private' },+ { item: 'default:notes/alias-vis', class: 'alias-and-visibility', detail: 'remove access: private, visibility: private' },+ ]);+ expect(preview.preview_hash).toMatch(/^[0-9a-f]{64}$/);+ expect(preview.apply_command).toContain('--apply --expect ' + preview.preview_hash);+ expect(preview.warnings.some((w: string) => w.includes('git-publish') && w.includes('1 page'))).toBe(true);+ expect(preview.warnings.some((w: string) => /widens what remote callers/.test(w))).toBe(true);+ expect(preview.details.ledger).toBe(ledgerPath(brainId));+ const again = await json(['private-labels']);+ expect(again.preview_hash).toBe(preview.preview_hash);+ firstHash = preview.preview_hash;+ const text = await run(['private-labels']);+ _resetCliExitVerdictForTests();+ expect(text).toContain('before:');+ expect(text).toContain('ledger:');+ });++ test('--class selects one class; an unknown class is refused', async () => {+ const git = await json(['private-labels', '--class', 'git-publish']);+ expect(git.listing).toEqual([{ item: GIT_SOURCE + ':notes/a', class: 'git-publish', detail: 'remove access: private' }]);+ const alias = await json(['private-labels', '--class', 'alias']);+ expect(alias.listing.map((l: { item: string }) => l.item)).toEqual(['default:notes/alias', 'default:notes/readers']);+ const bogus = await refusal(() => run(['private-labels', '--class', 'everything']));+ expect(bogus.code).toBe('invalid_params');+ });++ test('a caller that passes no undo ledger cannot apply or restore', async () => {+ const scope = await resolveRepairScope(engine);+ const logger = { info() {}, warn() {}, error() {} };+ const apply = await refusal(() => withEnv({ GBRAIN_HOME: dir }, async () => (await repairRunner(engine, { apply: true, logger })).run('private-labels', scope, { explicit: true, expect: firstHash })));+ expect(apply.code).toBe('invalid_params');+ const restore = await refusal(() => withEnv({ GBRAIN_HOME: dir }, async () => (await repairRunner(engine, { apply: false, logger })).run('private-labels', scope, { explicit: true, driftClass: 'restore' })));+ expect(restore.code).toBe('invalid_params');+ });++ test('a bare --apply refuses and changes nothing', async () => {+ const before = await row('notes/alias');+ const refused = await refusal(() => run(['private-labels', '--apply']));+ expect(refused.code).toBe('invalid_params');+ expect(await row('notes/alias')).toEqual(before);+ });++ test('--apply --expect clears exactly the approved alias pages, skips a page edited since the preview, and leaves keep and git pages alone', async () => {+ const preview = await json(['private-labels']);+ expect(preview.preview_hash).toBe(firstHash);+ const aliasBefore = await row('notes/alias');+ const visBefore = await row('notes/alias-vis');+ const gitBefore = await row('notes/a', GIT_SOURCE);+ await seed('notes/readers', 'note', { access: 'private', readable_by: ['alice-example'] }, 'default', body('notes/readers') + NL + NL + 'Edited after the preview.');+ const applied = await json(['private-labels', '--apply', '--expect', firstHash]);+ expect(applied.applied).toBe(2);+ expect(applied.skipped).toBe(1);+ expect(applied.failed).toEqual([]);++ const alias = await row('notes/alias');+ expect('access' in alias.frontmatter).toBe(false);+ expect(alias.frontmatter.status).toBe('draft');+ expect(alias.compiled_truth).toBe(aliasBefore.compiled_truth);+ const { access: _a, ...aliasRest } = aliasBefore.frontmatter;+ expect(alias.frontmatter).toEqual(aliasRest);++ const vis = await row('notes/alias-vis');+ expect('access' in vis.frontmatter).toBe(false);+ expect('visibility' in vis.frontmatter).toBe(false);+ const { access: _b, visibility: _c, ...visRest } = visBefore.frontmatter;+ expect(vis.frontmatter).toEqual(visRest);+ expect(vis.compiled_truth).toBe(visBefore.compiled_truth);++ expect((await row('notes/readers')).frontmatter.access).toBe('private');+ expect(await row('notes/a', GIT_SOURCE)).toEqual(gitBefore);+ for (const slug of KEEP) expect(await row(slug)).toEqual(keepBefore[slug]!);++ const ledger = ledgerPath(brainId);+ expect(statSync(ledger).mode & 0o777).toBe(0o600);+ expect(statSync(dirname(ledger)).mode & 0o777).toBe(0o700);+ const lines = ledgerLines(brainId);+ expect(lines.map(l => [l.slug, l.removed])).toEqual([+ ['notes/alias', { access: 'private' }],+ ['notes/alias-vis', { access: 'Private', visibility: 'private' }],+ ]);+ expect(lines[0]).toMatchObject({ brain_id: brainId, source_id: 'default', page_id: aliasBefore.page_id, revision_before: aliasBefore.revision });+ expect(lines[0].request_id).toMatch(/^[0-9a-f-]{36}$/);+ expect(typeof lines[0].at).toBe('string');+ });++ test('a second preview lists the skipped page; once applied, the clear counts are 0 and readers are kept', async () => {+ const second = await json(['private-labels']);+ expect(second.listing).toEqual([{ item: 'default:notes/readers', class: 'alias', detail: 'remove access: private' }]);+ expect(second.details.counts.before.alias).toBe(1);+ expect(second.details.counts.before['alias-and-visibility']).toBe(0);+ const applied = await json(['private-labels', '--apply', '--expect', second.preview_hash]);+ expect(applied.applied).toBe(1);+ const readers = await row('notes/readers');+ expect('access' in readers.frontmatter).toBe(false);+ expect(readers.frontmatter.readable_by).toEqual(['alice-example']);+ const third = await json(['private-labels']);+ expect(third.listing ?? []).toEqual([]);+ expect(third.details.counts.before).toEqual(ALL_CLEARED);+ expect(third.details.counts.after).toEqual(ALL_CLEARED);+ });++ test('--class restore re-adds exactly the removed keys, and a second restore preview finds them restored', async () => {+ const slugs = ['notes/alias', 'notes/alias-vis', 'notes/readers'];+ const cleared = Object.fromEntries(await Promise.all(slugs.map(async slug => [slug, await row(slug)] as const)));+ const preview = await json(['private-labels', '--class', 'restore']);+ expect(preview.details.counts.before).toEqual({ restorable: 3, already_restored: 0, page_gone: 0 });+ expect(preview.details.counts.after).toEqual({ restorable: 0, already_restored: 3, page_gone: 0 });+ expect(preview.listing).toEqual([+ { item: 'default:notes/alias', class: 'restore', detail: 're-add access: private' },+ { item: 'default:notes/readers', class: 'restore', detail: 're-add access: private' },+ { item: 'default:notes/alias-vis', class: 'restore', detail: 're-add access: Private, visibility: private' },+ ]);+ const applied = await json(['private-labels', '--class', 'restore', '--apply', '--expect', preview.preview_hash]);+ expect(applied.applied).toBe(3);+ expect((await row('notes/alias')).frontmatter).toEqual({ ...cleared['notes/alias']!.frontmatter, access: 'private' });+ expect((await row('notes/alias-vis')).frontmatter).toEqual({ ...cleared['notes/alias-vis']!.frontmatter, access: 'Private', visibility: 'private' });+ expect((await row('notes/readers')).frontmatter).toEqual({ ...cleared['notes/readers']!.frontmatter, access: 'private' });+ for (const slug of slugs) expect((await row(slug)).compiled_truth).toBe(cleared[slug]!.compiled_truth);+ expect(ledgerLines(brainId).filter(l => l.restored).map(l => [l.slug, l.restored])).toEqual([+ ['notes/alias', { access: 'private' }], ['notes/readers', { access: 'private' }], ['notes/alias-vis', { access: 'Private', visibility: 'private' }],+ ]);+ const again = await json(['private-labels', '--class', 'restore']);+ expect(again.details.counts.before).toEqual({ restorable: 0, already_restored: 3, page_gone: 0 });+ const relisted = await json(['private-labels']);+ expect(relisted.details.counts.before.alias).toBe(2);+ expect(relisted.details.counts.before['alias-and-visibility']).toBe(1);+ });+});++/**+ * Clearing or restoring a label is a privacy edit, not a content write: a page stored above agent_written keeps its+ * tier, gets no trust_tier marker and files no lower_page proposal, on an unmanaged brain (the default keyless install)+ * and on a managed one.+ */+describe('repair private-labels keeps the trust tier', () => {+ async function curated(source: string, slug: string, frontmatter: Record<string, unknown>) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);+ await seed(slug, 'note', frontmatter, source);+ await engine.transaction(tx => withCoordinatedWrite(tx, [source], () =>+ withTrustBackfill(tx, () => tx.executeRaw("UPDATE pages SET trust_tier='operator_curated' WHERE source_id=$1 AND slug=$2", [source, slug])), TEST_WRITE_ATTRIBUTION));+ }+ const state = async (source: string, slug: string) => {+ const [r] = await engine.executeRaw<{ tier: string; frontmatter: Record<string, unknown>; compiled_truth: string }>(+ 'SELECT trust_tier::text AS tier, frontmatter, compiled_truth FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [source, slug]);+ return r!;+ };+ const proposals = async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM trust_proposals'))[0]!.n);++ async function clearAndRestore(source: string) {+ const original = await state(source, 'notes/curated');+ expect(original.tier).toBe('operator_curated');+ const before = await proposals();+ const preview = await json(['private-labels', '--source', source]);+ expect(preview.listing).toEqual([{ item: source + ':notes/curated', class: 'alias-and-visibility', detail: 'remove access: private, visibility: private' }]);+ const applied = await json(['private-labels', '--source', source, '--apply', '--expect', preview.preview_hash]);+ expect(applied.failed).toEqual([]);+ expect(applied.applied).toBe(1);+ const cleared = await state(source, 'notes/curated');+ const { access: _a, visibility: _v, ...rest } = original.frontmatter;+ expect(cleared.frontmatter).toEqual(rest);+ expect(cleared.tier).toBe('operator_curated');+ expect(cleared.compiled_truth).toBe(original.compiled_truth);+ expect(await proposals()).toBe(before);++ const restorePreview = await json(['private-labels', '--source', source, '--class', 'restore']);+ expect(restorePreview.details.counts.before.restorable).toBe(1);+ const restored = await json(['private-labels', '--source', source, '--class', 'restore', '--apply', '--expect', restorePreview.preview_hash]);+ expect(restored.applied).toBe(1);+ const back = await state(source, 'notes/curated');+ expect(back.frontmatter).toEqual(original.frontmatter);+ expect(back.tier).toBe('operator_curated');+ expect(await proposals()).toBe(before);+ }++ test('unmanaged brain', async () => {+ await curated('source-b', 'notes/curated', { access: 'private', visibility: 'private', owner_note: 'kept' });+ await clearAndRestore('source-b');+ });++ test('managed brain', async () => {+ await curated('source-c', 'notes/curated', { access: 'private', visibility: 'private', owner_note: 'kept' });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ await withEnv({ GBRAIN_HOME: dir }, () => clearAndRestore('source-c'));+ const published = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id='source-c' AND state='committed' AND intent->>'kind'='managed_maintenance_page' AND intent->>'keep_trust'='true'");+ expect(published[0]!.n).toBe(2);+ }+ finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ });+});