Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(access): per-folder access rules with git and database stores (GBRA-218 A2)
garrytan66cb4b39c9ce
diff --git a/AGENTS.md b/AGENTS.mdindex d6fe7cb511..84bc28ad7e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -175,8 +175,9 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont[cron-schedule.md](docs/guides/cron-schedule.md#calling-gbrain-unattended),[scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout).- **Keep a page to some members of a shared source:** put `readable_by: [alice-example, group:team-a]` in its- frontmatter and bind each member's credential (`gbrain access member add`, `gbrain auth rescope --token <name>- --member <id>`); `gbrain access check --token <name>` and `--as <member>` preview what a member reads. A remote+ frontmatter (a whole folder: `gbrain access rule add --prefix <folder>/ --readers <list> --source <id>`, preview+ then `--yes`; widening waits for `gbrain access apply`) and bind each member's credential (`gbrain access member+ add`, `gbrain auth rescope --token <name> --member <id>`); `gbrain access check --token <name>` and `--as <member>` preview what a member reads. A remote`not_found` may be a restricted page: check `whoami` before telling the user there are no notes([Model C](docs/tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).- **Delete or purge pages:** `gbrain delete --purge` skips the 72-hour softdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea15b1acac..8cd67bd3f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,14 +23,18 @@ identifiers and attribution are available in the pre-removal Git revision| A `visibility: private` page that also names readers | hidden remotely | still hidden from a listed member unless that member's credential also has `--private-pages granted-sources` || Atoms, concepts and chronicle events derived from a restricted page | followed the origin's visibility | readable by no remote caller || Members and groups | | `gbrain access member add\|disable\|enable\|rm\|list`, `gbrain access group add\|rm\|list`, `gbrain access who-can-read <slug>`, `gbrain access check --token\|--client <name>`; `--member` and `--may-act-for` on `auth create`, `auth rescope` and `auth register-client`; config `mcp.stdio_member` for a stdio server; `--as <member>` previews one member's view from the local CLI; `whoami` and `grant_diagnosis` show member and groups |-| Doctor | | `access_readers_malformed`, `access_unknown_readers`, `access_recent_narrowings`, `access_page_readers_backfill` |+| Doctor | | `access_readers_malformed`, `access_unknown_readers`, `access_recent_narrowings`, `access_page_readers_backfill`, `access_policy_pending`, `access_policy_widening_held`, `access_policy_invalid`, `access_policy_store_mismatch` |+| Folder rules | | `gbrain access rule add\|rm\|list\|status\|history\|revert\|export\|import\|migrate`, `gbrain access apply` and `gbrain access resume` keep whole folders of a source to named members; a page under a rule is read remotely only by a member listed on every rule covering it and on its own `readable_by`. Rules live in the database on a repo-less source and in `.gbrain/access.yml` on a git-backed one |+| Changing folder rules | | narrowing applies at once; widening is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it; an unfinished apply reads as nobody remotely until `gbrain access resume --source <id>` |+| `gbrain export` and `gbrain import` | pages only | an export carries each source's applied folder rules under `.gbrain/`, and import installs them before publishing any page (`--access-policy <source>` maps a multi-source export) |### What to watch for after you upgrade- A page that already carried `readable_by` before this release reads as nobody remotely until you run `gbrain repair access` (preview) and then `gbrain repair access --apply`. Doctor's `access_page_readers_backfill` lists them.- On a brain with any restriction, the escape hatches no longer turn the remote read filter off, and secondary surfaces (proactive brief, retrieval reflex, entity resolution, known-as-of) hide restricted pages from every remote caller, listed members included.- A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).-- Works the same on a repo-less brain: members, groups and bindings live in the database.+- Works the same on a repo-less brain: members, groups, bindings and folder rules live in the database. A source records which store holds its folder rules when its first rule is created, and only `gbrain access rule migrate --source <id>` moves them; doctor `access_policy_store_mismatch` names it when the filesystem changes.+- Remote callers can no longer write pages under `.gbrain/`.## [0.60.453.0] - 2026-10-25diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex f77752e30f..cd1dc4d6ed 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -66,7 +66,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` follows the mode's expansion default (off in all modes) unless the call passes `expand`, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. `privateProvenanceFilterFragment` hides a fact whose provenance page (`s... (line truncated to 2000 chars)-- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`.+- `src/core/access/` (GBRA-218) — per-member read access inside one source. `principals.ts` normalizes frontmatter `readable_by` (bare id = `member:<id>`, `group:<g>`, ASCII case fold, space trim; anything malformed is `['!nobody']`); it is the row twin of the SQL `gbrain_access_readers()` (`test/access-principals.test.ts` holds them equal). A BEFORE trigger keeps `pages.page_readers` equal to that function (direct writes to the column are recomputed), and predicates test the array, never the function, which costs ~0.2 ms per row. A page that names readers with no derived value yet (written before the migration) reads as nobody until `gbrain repair access` (`repair/access.ts`). `members.ts` (members, groups, tombstoned ids never reused, bindings), `token-binding.ts` (the verifiers' join; a credential bound to a disabled, tombstoned or missing member is refused with `access_member_disabled`) and `caller.ts` (`remoteCallerAccess`: the identity dispatch puts on the caller-access record; stdio binds through `mcp.stdio_member`; publication re-resolves from the stored principal). In `search/private-visibility.ts` every page fragment is `accessAllowedSql` AND the privacy part: plain fragments use the empty identity (over-hide, never leak), `*ForCaller` fragments the caller's, and `GBRAIN_REMOTE_PRIVATE_PAGES`, `search.remote_private_pages` and `granted_sources` relax only the privacy part (`privacyForCaller`). A derivative of a page that names readers is hidden from every remote caller (`originAllowedSql`, which calls the SQL function `gbrain_access_origin_restricted()` only for atom, question, concept, event or `derived_from` rows, so each read plans one call instead of four subplans). Both parts lead with column tests (`page_readers IS NULL`, `type`) so row estimates follow column statistics; an expression test such as `->'readable_by' IS NULL` estimates almost no rows and sent restricted vector searches into nested-loop sequential scans. The index walk's page probe (`INDEX_WALK_PAGE_COLUMNS`) projects `page_readers`. Config `access.restrictions_present` (set by a trigger, sticky) keeps every pre-A1 path on a brain with no restriction. `check:remote-privacy-reads` keeps the two relaxations read only in `private-visibility.ts`. Tests: `test/member-read-access.test.ts` (remote matrix, both engines), `test/access-*.test.ts`. Folder rules (A2) keep whole folders of a source to named members. `folder-rules.ts` is the grammar (`.gbrain/access.yml`: `rules:` of `id`, `prefix`, `readable_by`), `classifyRulebook` (each change is narrowing or widening; the target installs only the narrowing part) and `matchingRuleIds`. `policy.ts` owns the one applied rulebook for both stores: `access_rules` (source-qualified ids), the append-only `access_policy_revisions` log, `access_pending_coverage` (prefixes that read as nobody while a narrowing restamps, or while a committed file is invalid) and `sources.config.access_store`, persisted at the first rule and changed only by `policy-migrate.ts` (journaled in `access_policy_migrations`). `proposeRevision` installs narrowing at once under a per-source row lock and holds widening for `applyApproved` (`plan_hash`, `preview_changed`); `restampSource` rewrites `pages.folder_rule_ids` in id windows, then clears pending coverage under the lock; re-proposing the same rulebook finishes an interrupted restamp. A trigger stamps `folder_rule_ids` from the SQL function `gbrain_access_folder_rules()` on insert and on slug or source change, never from git on the serve path. `policy-git.ts` is the git store (files committed through the commit door, applied by `syncAccessPolicyAt` from sync preflight and the managed drain, read with `git show` at the synced commit); `policy-transfer.ts` carries the applied rulebook through `gbrain export` and installs it before any page in `gbrain import`; `policy-notice.ts` is the `access_policy_pending` degraded notice. In `private-visibility.ts`, `folderRulesAllowedSql` sits inside `accessAllowedSql` (`folder_rule_ids IS NULL OR folder_rule_ids <@ <satisfied ids>` plus coverage conjuncts), so no hatch, grant or `--as` relaxes it; `caller.ts`'s `folderAccessFor` fails closed to whole-source coverage. CLI: `src/commands/access-rules.ts`; doctor: `src/commands/doctor/checks/folder-access.ts`. Tests: `test/access-folder-rules.test.ts` (database store, both engines), `test/access-folder-rules-git.test.ts`, `test/access-folder-transfer.test.ts`, `test/access-folder-doctor.test.ts`.- `src/core/search/projection-readiness.ts` — one statement probes visible unsealed pages: ready, projection_pending, by_design (protected/archived only) or unknown; LIMIT 1 arms walk the v161 pending index, not pages. Cached per scope by DB generation (page clock, pages filenode, archive flags, no open tx); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 3a3cb3ce51..fc67327ee9 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -105,6 +105,52 @@ Reasons: `ill_formed`, `unknown`, `disabled`, `removed`, `exists`, `unknown_grouMore: [docs/guides/write-refusals.md#access_member_invalid](../../docs/guides/write-refusals.md#access_member_invalid)+### access_policy_invalid++<a id="access_policy_invalid"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read). | A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed. | Show each problem with its line (gbrain access rule list --source <id>), fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull). Run: gbrain access rule list --source '{source_id}' --json | user | `gbrain doctor --json` | 1 | no |++More: [docs/guides/write-refusals.md#access_policy_invalid](../../docs/guides/write-refusals.md#access_policy_invalid)++### access_policy_pending++<a id="access_policy_pending"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A narrowing change to a source's folder rules is still being applied to its pages, so the prefixes it touches read as nobody until it finishes; pages under other prefixes keep the last applied rules. | Pages under a newly restricted folder are restamped in batches; until the last batch and its re-check pass land, they read as nobody instead of under the old rules. | Retry shortly. If it stays pending, the apply was interrupted: the brain host finishes it with gbrain access resume --source <id> (database store) or gbrain sync --source <id> --no-pull (git store). Run: gbrain access rule status --source '{source_id}' --json | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/write-refusals.md#access_policy_pending](../../docs/guides/write-refusals.md#access_policy_pending)++### access_policy_store_mismatch++<a id="access_policy_store_mismatch"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own. | Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens. | On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes. Run: gbrain access rule status --source '{source_id}' --json | user | `gbrain doctor --json` | 1 | no |++### access_policy_widening_held++<a id="access_policy_widening_held"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A change to a source's folder rules widens who may read (a rule removed, readers added, a prefix moved), so it is recorded but held: the previous rules stay in force until an operator previews it with gbrain access apply --source <id> and approves the printed plan with --yes --expect <plan_hash> on the brain host. | Write access to the policy (a git commit or a rule edit) must not be enough to open a folder; widening needs a host-side preview and an explicit approval. | Ask the user whether to approve the widening; the brain host previews it with gbrain access apply --source <id>. Run: gbrain access apply --source '{source_id}' --json | user | `repeat the read that failed` | 1 | no |++### access_rule_invalid++<a id="access_rule_invalid"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written. | Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none. | Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/write-refusals.md#access_rule_invalid](../../docs/guides/write-refusals.md#access_rule_invalid)+### acknowledgment_unavailable<a id="acknowledgment_unavailable"></a>diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.mdindex b35a1ce085..fcd35d559f 100644--- a/docs/guides/multi-source-brains.md+++ b/docs/guides/multi-source-brains.md@@ -188,8 +188,9 @@ per-member tokens for that, and `source_ids` to narrow further.Source grants are the coarse boundary: without page readers, two pages in onesource are readable by exactly the same tokens. Inside one source, a page thatnames readers in frontmatter `readable_by` is read only by credentials bound to-a listed member ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape));-it only narrows a grant, never widens it. Either way, put content in sources by+a listed member, and a folder rule (`gbrain access rule add`) does the same for+a whole prefix ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape));+both only narrow a grant, never widen it. Either way, put content in sources bywho may read it, before any member's bot connects:- **One source per channel, team or member.** Give a channel's pages a sourcediff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 616fc77791..f913dfc7c2 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -913,6 +913,9 @@ same on a repo-less brain and on a git-backed one.| <a id="access_member_invalid"></a>`access_member_invalid` | A member or group id given to `gbrain access`, to `--member` on `gbrain auth create`, `rescope` or `register-client`, or to a local `--as <member>` is ill-formed (`ill_formed`) or names no usable member (`unknown`, `disabled`, `removed`, `unknown_group`), or `member add` named an existing member (`exists`). Nothing was read or changed: an unknown `--as` is refused before the command runs instead of reading as unbound. | Check the id with `gbrain access member list --all`; add the member with `gbrain access member add <id>` or enable it with `gbrain access member enable <id>`. Ids are 1-64 characters: lower-case letters, digits, `.`, `_` or `-`. || <a id="access_member_id_retired"></a>`access_member_id_retired` | `gbrain access member add` or `enable` named an id that `gbrain access member rm --yes` removed. Member ids are never reused, because pages and audit history may still name the removed id. Nothing was created. | Choose a new member id. `gbrain access member disable` is the reversible way to pause a member. || <a id="access_member_disabled"></a>`access_member_disabled` | The access token or OAuth client is bound to a member who is disabled, removed or missing, so it was refused at verification (HTTP 401, `invalid_token` with this code in the description). A credential bound to a member reads as that member, so it is refused rather than silently treated as unbound. | Ask the brain operator to run `gbrain access member enable <id>`, or to rebind the credential with `gbrain auth rescope --token <name> --member <id>` (`--member none` unbinds it; an unbound credential sees no page that names readers). |+| <a id="access_rule_invalid"></a>`access_rule_invalid` | `gbrain access rule add` was given a rule whose prefix is not a literal lower-case slug folder ending in `/` (or holds `..` or `*`), whose readers are not member ids or `group:<id>`, or whose prefix another rule already covers; nothing was written. Prefixes match slugs literally, so a pattern or typo would restrict the wrong pages. | Write the prefix as a folder such as `partners/alice-example/` and the readers as `alice-example,group:team-a`; to change who reads a folder that already has a rule, pass that rule's `--id`. |+| <a id="access_policy_invalid"></a>`access_policy_invalid` | A source's committed `.gbrain/access.yml` (or a file given to `gbrain access rule import`) does not validate. The last applied rules stay in force and every prefix the file names reads as nobody for remote callers (the whole source when the file does not parse), so a typo never opens a folder. | `gbrain access rule list --source <id>` shows each problem with its line. Fix the file, commit it with `gbrain git commit-push`, and run `gbrain sync --source <id> --no-pull`. |+| <a id="access_policy_pending"></a>`access_policy_pending` | A narrowing change to a source's folder rules is still being stamped onto its pages, so pages under the folders it touches read as nobody for remote callers until it finishes (other folders keep the last applied rules). Remote reads carry this as a notice: an empty answer there is not proof of no notes. | Wait and retry. If it stays pending the apply was interrupted: on the brain host run `gbrain access resume --source <id>` (database store) or `gbrain sync --source <id> --no-pull` (git store); `gbrain access rule status --source <id>` shows the pending folders. |## Relateddiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 350c01f6c7..82fae2643f 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -237,7 +237,9 @@ Grants are per source, so lay sources out by who may read them([guide](../guides/multi-source-brains.md#lay-out-sources-by-who-may-read-them)).Inside one source, bind each member's credential with `gbrain auth rescope--token <name> --member <id>` (or `--client`) and put `readable_by` on the pages-only some members may read; `gbrain access check --token <name>` shows the+only some members may read, or keep a whole folder to them with `gbrain access+rule add --prefix <folder>/ --readers <members> --source <id>`;+`gbrain access check --token <name>` shows theresult ([Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).New `memory-reader`, `memory-writer` and `coding-agent` grants are callable anddiff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.mdindex 709eb2f96a..6975e3c1c8 100644--- a/docs/tutorials/company-brain.md+++ b/docs/tutorials/company-brain.md@@ -132,6 +132,18 @@ gbrain access who-can-read notes/renewal-notes # the members and groups a pagA 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.+**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:++```bash+gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source team-a # preview+gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source team-a --yes+gbrain access rule list --source team-a # store, revisions, applied rules, anything held or pending+```++A remote read of a page under a rule needs the caller's member to be on every rule covering it and on the page's own `readable_by`; hatches, grants and `--as` never relax it. Narrowing applies at once. A change that widens (removing a rule or a reader) is held until `gbrain access apply --source team-a` previews who would gain access and `gbrain access apply --source team-a --yes --expect <plan_hash>` approves it. If an apply stops halfway, its prefixes read as nobody until `gbrain access resume --source team-a`. `gbrain access rule history` and `rule revert --to <revision>` work over the revision log, and `gbrain export` carries the applied rules so `gbrain import` installs them before any page.++On a git-backed source the same rules live in `.gbrain/access.yml`: `rule add|rm` commit it through `gbrain git commit-push`, a hand edit takes effect when you commit it and run `gbrain sync`, and a widening commit stays held until `gbrain access apply` approves it (recorded in `.gbrain/access.approved`). A source keeps the store it had when its first rule was created; `gbrain access rule migrate --source <id>` (preview, then `--yes`) moves the rules when you attach or remove a repo. Remote callers cannot write `.gbrain/`.+For most company-brain installs (10+ teammates each with their own AI client), Model A is the right starting point. If you're running the fat-agent-serves-everyone pattern from the personal-brain tutorial, Model B is genuinely simpler. You can also mix: separate sources for the obviously-different ones (customer notes vs internal-only) AND a `partners/<slug>/` convention inside the shared source for per-person workspace.### Per-person folder structure inside each sourcediff --git a/llms-full.txt b/llms-full.txtindex 2f9ed195bb..4d74e3427d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1934,8 +1934,9 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont[cron-schedule.md](docs/guides/cron-schedule.md#calling-gbrain-unattended),[scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout).- **Keep a page to some members of a shared source:** put `readable_by: [alice-example, group:team-a]` in its- frontmatter and bind each member's credential (`gbrain access member add`, `gbrain auth rescope --token <name>- --member <id>`); `gbrain access check --token <name>` and `--as <member>` preview what a member reads. A remote+ frontmatter (a whole folder: `gbrain access rule add --prefix <folder>/ --readers <list> --source <id>`, preview+ then `--yes`; widening waits for `gbrain access apply`) and bind each member's credential (`gbrain access member+ add`, `gbrain auth rescope --token <name> --member <id>`); `gbrain access check --token <name>` and `--as <member>` preview what a member reads. A remote`not_found` may be a restricted page: check `whoami` before telling the user there are no notes([Model C](docs/tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).- **Delete or purge pages:** `gbrain delete --purge` skips the 72-hour softdiff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.mdindex d2cd67ebf2..1486acc966 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-routing.md@@ -26,7 +26,7 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.-A remote `not_found` or a short result may be a page whose `readable_by` excludes+A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential: check `whoami` (member, groups) before telling the user there are no notes.## When to switch braindiff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.mdindex d2cd67ebf2..1486acc966 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-routing.md@@ -26,7 +26,7 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.-A remote `not_found` or a short result may be a page whose `readable_by` excludes+A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential: check `whoami` (member, groups) before telling the user there are no notes.## When to switch braindiff --git a/plugin/skills/conventions/brain-routing.md b/plugin/skills/conventions/brain-routing.mdindex d2cd67ebf2..1486acc966 100644--- a/plugin/skills/conventions/brain-routing.md+++ b/plugin/skills/conventions/brain-routing.md@@ -26,7 +26,7 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.-A remote `not_found` or a short result may be a page whose `readable_by` excludes+A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential: check `whoami` (member, groups) before telling the user there are no notes.## When to switch braindiff --git a/scripts/bench-member-access.ts b/scripts/bench-member-access.tsindex 168e7d1813..88cd1d4cd0 100644--- a/scripts/bench-member-access.ts+++ b/scripts/bench-member-access.ts@@ -8,9 +8,11 @@* the member may read that contain every query word, known by construction* (the synthetic corpus gives each page distinct words; capped at 10). PGLite is in-process, so* runs on two revisions are directly comparable; on a revision without member- * tables only the 0% cell runs.+ * tables only the 0% cell runs. --rules adds that many folder rules (A2) on+ * prefixes no page lives under, so the cell measures what the folder layer+ * costs a brain whose pages it does not restrict.*- * Usage: bun scripts/bench-member-access.ts [--pages 5000] [--queries 60] [--json]+ * Usage: bun scripts/bench-member-access.ts [--pages 5000] [--queries 60] [--shares 0,0.2,0.8] [--rules 0] [--json]*/import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { importFromContent } from '../src/core/import-file.ts';@@ -27,6 +29,7 @@ const PAGES = arg('--pages', 5000);const QUERIES = arg('--queries', 60);const JSON_MODE = process.argv.includes('--json');const SHARES = (process.argv.includes('--shares') ? process.argv[process.argv.indexOf('--shares') + 1] : '0,0.2,0.8').split(',').map(Number);+const RULES = (process.argv.includes('--rules') ? process.argv[process.argv.indexOf('--rules') + 1] : '0').split(',').map(Number);const DIMS = 1536;const SRC = 'bench-src';const SYLLABLES = 'ba ce di fo gu ha je ki lo mu na pe qi ro su ta ve wi xo yu za'.split(' ');@@ -69,11 +72,16 @@ async function seed(engine: PGLiteEngine, share: number): Promise<void> {}}-async function runCell(share: number) {+async function runCell(share: number, rules: number) {const engine = await newEngine();const hasMembers = (await engine.executeRaw<{ t: string | null }>("SELECT to_regclass('access_members')::text AS t"))[0]?.t != null;- if (share > 0 && !hasMembers) { await engine.disconnect(); return null; }+ const hasRules = (await engine.executeRaw<{ t: string | null }>("SELECT to_regclass('access_rules')::text AS t"))[0]?.t != null;+ if ((share > 0 && !hasMembers) || (rules > 0 && !hasRules)) { await engine.disconnect(); return null; }await seed(engine, share);+ if (rules > 0) {+ const { proposeRevision } = await import('../src/core/access/policy.ts');+ await proposeRevision(engine, SRC, Array.from({ length: rules }, (_, k) => ({ id: `r-${k}`, prefix: `restricted/r-${k}/`, readable_by: ['member:alice-example'] })), { origin: 'cli', store: 'database' });+ }if (hasMembers) await engine.executeRaw("INSERT INTO access_members (id) VALUES ('alice-example') ON CONFLICT DO NOTHING");const mint = async (name: string) => mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });@@ -119,7 +127,7 @@ async function runCell(share: number) {}}for (const who of ['unbound', 'member'] as const) {- cells.push({ share, who, match, p50: +pct(times[who], 0.5).toFixed(2), p95: +pct(times[who], 0.95).toFixed(2),+ cells.push({ share, rules, who, match, p50: +pct(times[who], 0.5).toFixed(2), p95: +pct(times[who], 0.95).toFixed(2),...(who === 'member' && possible ? { hit_at_10: +(hits / possible).toFixed(3) } : {}) });}}@@ -131,8 +139,10 @@ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_d__setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(vectorFor) })) as never);const all: Record<string, unknown>[] = [];for (const share of SHARES) {- const cells = await runCell(share);- if (cells) all.push(...cells);+ for (const rules of RULES) {+ const cells = await runCell(share, rules);+ if (cells) all.push(...cells);+ }}if (JSON_MODE) console.log(JSON.stringify({ pages: PAGES, queries: QUERIES, cells: all }));else console.table(all);diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.tsindex 5e0c50df33..f16b25aec3 100644--- a/scripts/check-agent-contract.ts+++ b/scripts/check-agent-contract.ts@@ -270,6 +270,8 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st'sources writer failures', 'sync status',// GBRA-218: the member listing only reads the members table (the verify step of access_member_* refusals).'access member list',+ // GBRA-218 A2: folder-rule status and listing only read the policy tables and the committed file.+ 'access rule status', 'access rule list',// GBRA-130 A-25: `--failed` lists held propose_takes pages from the failure ledger; it never extracts or writes.'takes propose --failed',// #6466: `--list` returns before the orchestration lock and never runs an orchestrator or writes the ledger.diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 6b4286b92b..11fbb6f4d1 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -18,7 +18,7 @@ src/commands/embed.ts runEmbedCore 381 seed: W5 baseline, refactor wave 1 (decomsrc/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts); lowered to 355 at the wave-9 follow-ups merge (zero result via emptyExtractConversationFactsResult)src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/import.ts runImport 973 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +1 Wave B lane 1d (TODO wave-b PR 1): reads the segmented-storage policy once per run for the streamed import of files over the single-string ceiling+src/commands/import.ts runImport 974 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +1 Wave B lane 1d (TODO wave-b PR 1): reads the segmented-storage policy once per run for the streamed import of files over the single-string ceiling; +1 GBRA-218 A2: the import barrier installs the tree's folder rules before any page (logic in access/policy-transfer.ts)src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/serve.ts installStdioLifecycle 323 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff)diff --git a/skills/conventions/brain-routing.md b/skills/conventions/brain-routing.mdindex d2cd67ebf2..1486acc966 100644--- a/skills/conventions/brain-routing.md+++ b/skills/conventions/brain-routing.md@@ -26,7 +26,7 @@ Bare `gbrain query "X"` routes to the default brain's default source. Thatis the right answer 90% of the time. Don't cross the boundary without areason.-A remote `not_found` or a short result may be a page whose `readable_by` excludes+A remote `not_found` or a short result may be a page whose `readable_by` or folder rule excludesthis credential: check `whoami` (member, groups) before telling the user there are no notes.## When to switch braindiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 237b9054c5..ff8202496a 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -46,7 +46,7 @@"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/agent-operator-protocol.md": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235","conventions/brain-first.md": "e0e4d7c4b760213325dffd286baf934720816a0b6aac5338538a0463e8fe77d2",- "conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",+ "conventions/brain-routing.md": "418cb37cfa5b297290f58104df167de727812f921b82f218f55b0a9295c505db","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933","conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",diff --git a/src/cli/as-preview.ts b/src/cli/as-preview.tsindex 6fc21c2107..fc97c34bb5 100644--- a/src/cli/as-preview.ts+++ b/src/cli/as-preview.ts@@ -40,7 +40,8 @@ export async function openAsPreview(engine: BrainEngine, member: string | undefiexitCliError(e, command);}const { withCallerAccess } = await import('../core/search/private-visibility.ts');- const access = { identity, applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] };+ const folder = await (await import('../core/access/caller.ts')).folderAccessFor(engine, identity);+ const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] };return {run: fn => withCallerAccess(access, fn),context: ctx => ({ ...ctx, accessIdentity: identity, applyRemoteReadPolicy: true }),diff --git a/src/commands/access-rules.ts b/src/commands/access-rules.tsnew file mode 100644index 0000000000..3faef12b7a--- /dev/null+++ b/src/commands/access-rules.ts@@ -0,0 +1,366 @@+/**+ * GBRA-218 (PR A2): `gbrain access rule|apply|resume`, the operator surface for folder rules.+ *+ * gbrain access rule add --prefix <folder/> --readers a,group:b [--id <rule>] [--source <id>] [--yes] [--expect <rev>] [--operation <id>]+ * gbrain access rule rm <rule> [--source <id>] [--yes] [--expect <rev>] [--operation <id>]+ * gbrain access rule list|status|history [--source <id>] [--operation <id>] [--limit <n>]+ * gbrain access rule revert --to <revision> [--source <id>] [--yes]+ * gbrain access rule export [--source <id>] [--approved]+ * gbrain access rule import --file <access.yml> [--source <id>] [--yes]+ * gbrain access rule migrate [--source <id>] [--yes]+ * gbrain access apply [--source <id>] [--revision <n>] [--yes --expect <plan_hash>]+ * gbrain access resume [--source <id>]+ *+ * The source's persisted store decides where an edit lands: the database+ * revision log (repo-less sources, the default keyless install) or+ * `.gbrain/access.yml` committed through the git door (git-backed sources). Every+ * edit previews first; narrowing applies at once, widening waits for+ * `gbrain access apply`. Trusted local CLI only.+ */+import { readFileSync } from 'node:fs';+import type { BrainEngine } from '../core/engine.ts';+import { usageError } from '../cli/cli-error.ts';+import { opError } from '../core/ops/contract.ts';+import { classifyRulebook, folderRulesAllow, normalizeRule, parsePolicyYaml, serializePolicyYaml, sortRules, type FolderRule, type RuleChange } from '../core/access/folder-rules.ts';+import { identityFor } from '../core/access/principals.ts';+import { boundCredentials, listGroups, listMembers } from '../core/access/members.ts';+import {+ appliedRules, applyApproved, getRevision, listRevisions, newOperationId, policyStatus, previewApply, proposeRevision, readAccessStore, resumePolicy,+ writeAccessStore, ensurePolicyState, type AccessStore, type ProposalResult, type RestampProgress,+} from '../core/access/policy.ts';+import {+ APPROVED_FILE, isGitWorkTree, POLICY_FILE, sourcePolicyRoot, syncGitPolicy, workingTreeRules, writeApprovedFile, writeGitRules, type GitPolicyReceipt,+} from '../core/access/policy-git.ts';++const VALUE_FLAGS = new Set(['--source', '--prefix', '--readers', '--id', '--expect', '--operation', '--to', '--revision', '--file', '--limit']);++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ if (i < 0) return args.find(a => a.startsWith(`${name}=`))?.slice(name.length + 1);+ const v = args[i + 1];+ if (v === undefined || v.startsWith('--')) throw usageError(`${name} requires a value.`, `Put the value right after the flag, as in ${name} VALUE.`);+ return v;+}++function positionals(args: string[]): string[] {+ const out: string[] = [];+ for (let i = 0; i < args.length; i++) {+ if (VALUE_FLAGS.has(args[i]!)) { i++; continue; }+ if (!args[i]!.startsWith('--')) out.push(args[i]!);+ }+ return out;+}++function intFlag(args: string[], name: string): number | undefined {+ const raw = flag(args, name);+ if (raw === undefined) return undefined;+ if (!/^\d+$/.test(raw)) throw usageError(`${name} takes a whole number.`, `For example ${name} 3.`);+ return Number(raw);+}++function print(json: boolean, value: unknown, human: () => string[]): void {+ console.log(json ? JSON.stringify(value, null, 2) : human().join('\n'));+}++function progressLogger(json: boolean): (p: RestampProgress) => void {+ let last = 0;+ return p => {+ if (Date.now() - last < 1000) return;+ last = Date.now();+ process.stderr.write(`[access] restamping: ${p.pages_scanned} pages scanned, ${p.pages_restamped} restamped` + '\n');+ void json;+ };+}++const reader = (p: string) => (p.startsWith('member:') ? p.slice(7) : p);+const ruleLine = (r: FolderRule) => ` ${r.id} ${r.prefix} readable by ${r.readable_by.map(reader).join(', ') || 'nobody'}`;++function changeLine(c: RuleChange): string {+ const what = c.kind === 'added' ? 'add rule' : c.kind === 'removed' ? 'remove rule' : c.kind === 'prefix_moved' ? `move rule to ${c.prefix}`+ : c.kind === 'readers_removed' ? `remove readers ${(c.readers ?? []).map(reader).join(', ')} from` : `add readers ${(c.readers ?? []).map(reader).join(', ')} to`;+ return ` ${what} ${c.rule} (${c.prefix}): ${c.narrowing ? 'narrowing, applies at once' : 'widening, held until gbrain access apply'}`;+}++/** The store an edit lands in: the persisted one, else git when the source root is a git work tree, else the database. */+async function resolveStore(engine: BrainEngine, sourceId: string): Promise<{ store: AccessStore; persisted: boolean; root: string | null }> {+ const persisted = await readAccessStore(engine, sourceId);+ const root = await sourcePolicyRoot(engine, sourceId);+ const gitRoot = root && isGitWorkTree(root) ? root : null;+ if (persisted === 'git' && !gitRoot) {+ throw opError('access_policy_store_mismatch', `Source ${sourceId} keeps its folder rules in git, but this host sees no git work tree at its root (${root ?? 'no local path'}); nothing was written.`,+ `Run gbrain access rule migrate --source ${sourceId} to move the rules into the database (preview first), or run this on the host that holds the checkout.`,+ { fix: { argv: ['gbrain', 'access', 'rule', 'migrate', '--source', sourceId], consent: [], actor: 'user', requires_exclusive: false, why: 'Previews moving the applied rulebook into the database store; writes nothing without --yes.',+ verify: { argv: ['gbrain', 'access', 'rule', 'status', '--source', sourceId, '--json'] } } });+ }+ if (persisted) return { store: persisted, persisted: true, root: gitRoot };+ return { store: gitRoot ? 'git' : 'database', persisted: false, root: gitRoot };+}++/** The desired rulebook an edit starts from: the working tree's access.yml on git, the latest revision (else the applied rules) on the database. */+async function baseRules(engine: BrainEngine, sourceId: string, store: AccessStore, root: string | null): Promise<FolderRule[]> {+ if (store === 'git') return workingTreeRules(root!, sourceId);+ return (await getRevision(engine, sourceId))?.rules ?? await appliedRules(engine, sourceId);+}++export interface RulePreview {+ source_id: string;+ store: AccessStore;+ store_persisted: boolean;+ expect: number;+ desired: FolderRule[];+ changes: RuleChange[];+ held: RuleChange[];+ matched_pages: Record<string, number>;+ unknown_readers: string[];+ members_losing: string[];+ credentials_losing: Array<{ member: string; kind: string; name: string }>;+}++async function previewRules(engine: BrainEngine, sourceId: string, store: AccessStore, persisted: boolean, desired: FolderRule[]): Promise<RulePreview> {+ const current = await appliedRules(engine, sourceId);+ const cls = classifyRulebook(current, desired);+ const expect = (await getRevision(engine, sourceId))?.revision ?? 0;+ const prefixes = [...new Set(cls.changes.map(c => c.prefix).concat(cls.changes.map(c => current.find(r => r.id === c.rule)?.prefix ?? c.prefix)))];+ const matched: Record<string, number> = {};+ for (const prefix of prefixes) {+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND starts_with(slug, $2)', [sourceId, prefix]);+ matched[prefix] = Number(row?.n ?? 0);+ }+ const members = await listMembers(engine, { includeRemoved: true });+ const groups = new Set((await listGroups(engine)).map(g => g.id));+ const known = (p: string) => p.startsWith('group:') ? groups.has(p.slice(6)) : members.some(m => m.id === p.slice(7) && m.status !== 'removed');+ const unknown = [...new Set(desired.flatMap(r => r.readable_by))].filter(p => !known(p)).map(reader).sort();+ const slugs = prefixes.length ? (await engine.executeRaw<{ slug: string }>(+ 'SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND EXISTS (SELECT 1 FROM unnest($2::text[]) AS pfx WHERE starts_with(slug, pfx))', [sourceId, prefixes])).map(r => r.slug) : [];+ const losing: string[] = [];+ for (const m of members.filter(x => x.status === 'enabled')) {+ const identity = identityFor(m.id, m.groups);+ if (slugs.some(s => folderRulesAllow(s, current, identity) && !folderRulesAllow(s, cls.target, identity))) losing.push(m.id);+ }+ const credentials: RulePreview['credentials_losing'] = [];+ for (const m of losing) for (const c of await boundCredentials(engine, m)) credentials.push({ member: m, kind: c.kind, name: c.name });+ return { source_id: sourceId, store, store_persisted: persisted, expect, desired, changes: cls.changes, held: cls.held, matched_pages: matched,+ unknown_readers: unknown, members_losing: losing, credentials_losing: credentials };+}++function previewLines(p: RulePreview, rerun: string): string[] {+ return [+ `Source ${p.source_id} (${p.store} store${p.store_persisted ? '' : ', chosen now: set with the first rule'}), desired revision ${p.expect}`,+ ...(p.changes.length ? p.changes.map(changeLine) : [' no change']),+ ...Object.entries(p.matched_pages).map(([prefix, n]) => ` ${prefix}: ${n} page(s) match`),+ ...(p.unknown_readers.length ? [` Unknown readers (no such member or group; they match nobody): ${p.unknown_readers.join(', ')}`] : []),+ ...(p.members_losing.length ? [` Members losing access: ${p.members_losing.join(', ')}`] : []),+ ...(p.credentials_losing.length ? [` Credentials losing access: ${p.credentials_losing.map(c => `${c.kind} ${c.name} (${c.member})`).join(', ')}`] : []),+ 'Pages under no rule are unchanged; unbound credentials and stdio read no page under a rule.',+ `Nothing written. To approve, add --yes --expect ${p.expect} (${rerun}).`,+ ];+}++interface EditResult {+ source_id: string;+ store: AccessStore;+ operation_id: string;+ applied: boolean;+ state: ProposalResult['state'] | 'invalid';+ revision: number | null;+ change_kind: string;+ changes: RuleChange[];+ held: RuleChange[];+ pages_restamped: number;+ git?: GitPolicyReceipt;+ note?: string;+}++/** Writes a desired rulebook through the source's store (after the caller's preview) and reports the result. */+async function writeRules(engine: BrainEngine, sourceId: string, desired: FolderRule[], opts: { expect?: number; operation?: string; message: string; json: boolean }): Promise<EditResult> {+ const { store, root } = await resolveStore(engine, sourceId);+ const operationId = opts.operation ?? newOperationId();+ if (!opts.json) process.stderr.write(`[access] operation ${operationId} (if this reply is lost: gbrain access rule status --source ${sourceId} --operation ${operationId})` + '\n');+ if (store === 'database') {+ const r = await proposeRevision(engine, sourceId, desired, { origin: 'cli', operationId, expectDesired: opts.expect, store: 'database', onProgress: progressLogger(opts.json) });+ return { source_id: sourceId, store, operation_id: operationId, applied: r.state === 'applied' || r.state === 'unchanged', state: r.state, revision: r.revision,+ change_kind: r.change_kind, changes: r.changes, held: r.held, pages_restamped: r.pages_restamped, ...(r.reconciled ? { note: 'This operation was already recorded; nothing new was written.' } : {}) };+ }+ if (opts.expect !== undefined) {+ const latest = (await getRevision(engine, sourceId))?.revision ?? 0;+ if (latest !== opts.expect) throw opError('preview_changed', `Source ${sourceId}'s folder rules changed since the preview (previewed revision ${opts.expect}, now ${latest}); nothing was written.`, 'Preview again and rerun with the new --expect value.');+ }+ await ensurePolicyState(engine, sourceId);+ if (!(await readAccessStore(engine, sourceId))) await writeAccessStore(engine, sourceId, 'git');+ const { receipt, sync } = await writeGitRules(engine, sourceId, root!, desired, opts.message, progressLogger(opts.json));+ const p = sync.proposal;+ return { source_id: sourceId, store, operation_id: operationId, applied: sync.state === 'applied' || sync.state === 'unchanged', state: sync.state === 'skipped' ? 'unchanged' : sync.state,+ revision: p?.revision ?? null, change_kind: p?.change_kind ?? 'unchanged', changes: p?.changes ?? [], held: p?.held ?? [], pages_restamped: p?.pages_restamped ?? 0, git: receipt,+ ...(receipt.note ? { note: receipt.note } : {}) };+}++function editLines(r: EditResult): string[] {+ return [+ `Source ${r.source_id} (${r.store} store): revision ${r.revision ?? '-'} ${r.state}`,+ ...r.changes.map(changeLine),+ ...(r.git ? [` ${r.git.path} committed ${r.git.commit?.slice(0, 12) ?? '(nothing to commit)'} (${r.git.outcome})`] : []),+ ...(r.pages_restamped ? [` ${r.pages_restamped} page(s) restamped`] : []),+ ...(r.held.length ? [`Held: preview with gbrain access apply --source ${r.source_id}`] : []),+ ...(r.state === 'pending' ? [`Still pending: finish with gbrain access resume --source ${r.source_id}`] : []),+ ...(r.note ? [r.note] : []),+ ];+}++async function ruleCmd(engine: BrainEngine, sub: string | undefined, args: string[], json: boolean): Promise<void> {+ const sourceId = flag(args, '--source') ?? 'default';+ const yes = args.includes('--yes');+ const expect = intFlag(args, '--expect');+ const operation = flag(args, '--operation');+ switch (sub) {+ case 'add':+ case 'rm':+ case 'revert':+ case 'import': {+ const { store, persisted, root } = await resolveStore(engine, sourceId);+ const base = await baseRules(engine, sourceId, store, root);+ let desired: FolderRule[];+ let message: string;+ if (sub === 'add') {+ const readers = flag(args, '--readers');+ const r = normalizeRule({ prefix: flag(args, '--prefix'), readable_by: readers === undefined ? undefined : readers.split(',').map(s => s.trim()).filter(Boolean), ...(flag(args, '--id') ? { id: flag(args, '--id') } : {}) });+ if ('problem' in r) {+ throw opError('access_rule_invalid', `The rule is invalid: ${r.problem}.`, 'Nothing was written. Example: gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a');+ }+ const clash = base.find(b => b.prefix === r.rule.prefix && b.id !== r.rule.id);+ if (clash) throw opError('access_rule_invalid', `Rule "${clash.id}" already covers ${r.rule.prefix}.`, `Nothing was written. Change that rule's readers instead: gbrain access rule add --id ${clash.id} --prefix ${r.rule.prefix} --readers <list>.`);+ desired = sortRules([...base.filter(b => b.id !== r.rule.id), r.rule]);+ message = `access: rule ${r.rule.id} on ${r.rule.prefix} readable by ${r.rule.readable_by.map(reader).join(', ')}`;+ } else if (sub === 'rm') {+ const id = positionals(args)[0];+ if (!id) throw usageError('rule rm needs a rule id.', 'gbrain access rule rm <rule> --source <id> (gbrain access rule list shows the ids)');+ if (!base.some(b => b.id === id)) throw opError('not_found', `Source ${sourceId} has no rule "${id}".`, `List rules with gbrain access rule list --source ${sourceId}.`);+ desired = base.filter(b => b.id !== id);+ message = `access: remove rule ${id}`;+ } else if (sub === 'revert') {+ const to = intFlag(args, '--to');+ if (to === undefined) throw usageError('rule revert needs --to <revision>.', `gbrain access rule history --source ${sourceId} lists revisions.`);+ const rev = await getRevision(engine, sourceId, to);+ if (!rev) throw opError('not_found', `Source ${sourceId} has no folder-rule revision ${to}.`, `List revisions with gbrain access rule history --source ${sourceId}.`);+ desired = rev.rules;+ message = `access: revert folder rules to revision ${to}`;+ } else {+ const file = flag(args, '--file');+ if (!file) throw usageError('rule import needs --file <access.yml>.', 'gbrain access rule import --file access.yml --source <id>');+ const parsed = parsePolicyYaml(readFileSync(file, 'utf8'));+ if (!parsed.ok) throw opError('access_policy_invalid', `${file} does not validate: ${parsed.problems.map(p => `${p.line ? `line ${p.line}: ` : ''}${p.message}`).join('; ')}.`, 'Nothing was written. Fix the file and run the import again.');+ desired = parsed.rules;+ message = `access: import folder rules`;+ }+ const preview = await previewRules(engine, sourceId, store, persisted, desired);+ if (!yes) {+ return print(json, { ...preview, applied: false }, () => previewLines(preview, `gbrain access rule ${[sub, ...args.filter(a => a !== '--json')].join(' ')} --yes`));+ }+ const r = await writeRules(engine, sourceId, desired, { expect, operation, message, json });+ return print(json, r, () => editLines(r));+ }+ case 'list':+ case 'status': {+ const s = await policyStatus(engine, sourceId, operation);+ const { root } = await resolveStore(engine, sourceId).catch(() => ({ root: null }));+ const mismatch = s.store === 'database' && !!root ? 'This source now has a git work tree but keeps its rules in the database; gbrain access rule migrate moves them into .gbrain/access.yml.' : undefined;+ return print(json, { ...s, ...(mismatch ? { store_mismatch: mismatch } : {}) }, () => [+ `Source ${sourceId}: ${s.store ?? 'no folder rules yet'}${s.store === 'git' ? ` (${POLICY_FILE})` : s.store === 'database' ? ' (revision log)' : ''}`,+ ` Revisions: desired ${s.desired?.revision ?? '-'}, applied ${s.applied_revision ?? '-'}, approved ${s.approved_revision ?? '-'}`,+ ...(s.rules.length ? ['Applied rules:', ...s.rules.map(ruleLine)] : [' No applied rule: no folder restricts reads.']),+ ...(s.held.length ? ['Held widening (gbrain access apply previews it):', ...s.held.map(changeLine)] : []),+ ...(s.pending.length ? [`Pending (reads as nobody until stamped; gbrain access resume --source ${sourceId}): ${s.pending.map(c => c.prefix || '(whole source)').join(', ')}`] : []),+ ...s.invalid.flatMap(c => {+ const detail = c.detail as { problems?: Array<{ line: number | null; message: string }>; commit?: string } | null;+ return [`Invalid policy file${detail?.commit ? ` at ${detail.commit}` : ''} (reads as nobody: ${c.prefix || 'the whole source'}):`,+ ...(detail?.problems ?? []).map(p => ` ${p.line ? `line ${p.line}: ` : ''}${p.message}`)];+ }),+ ...(s.operation ? [`Operation ${s.operation.operation_id}: ${s.operation.state}${s.operation.revision ? ` (revision ${s.operation.revision})` : ''}`] : []),+ ...(mismatch ? [mismatch] : []),+ ]);+ }+ case 'history': {+ const revisions = await listRevisions(engine, sourceId, intFlag(args, '--limit') ?? 50);+ return print(json, { source_id: sourceId, revisions }, () => revisions.length ? revisions.map(r =>+ ` ${r.revision} ${r.created_at} ${r.change_kind} ${r.origin} by ${r.proposed_by ?? '?'}${r.approved_at ? ` approved by ${r.approved_by}` : ' held'}${r.applied_at ? '' : ' (not yet applied)'} ${r.rules.length} rule(s)`)+ : ['No folder-rule revisions.']);+ }+ case 'export': {+ const s = await policyStatus(engine, sourceId);+ const rules = args.includes('--approved') ? (await listRevisions(engine, sourceId, 500)).find(r => r.approved_at)?.rules ?? s.rules : s.desired?.rules ?? s.rules;+ if (json) return print(true, { source_id: sourceId, rules }, () => []);+ console.log(serializePolicyYaml(rules).trimEnd());+ return;+ }+ case 'migrate':+ return migrateCmd(engine, sourceId, yes, json);+ default:+ throw usageError(`Unknown access rule subcommand: ${sub ?? '(none)'}.`, 'Use add, rm, list, status, history, revert, export, import or migrate (gbrain access --help).');+ }+}++async function migrateCmd(engine: BrainEngine, sourceId: string, yes: boolean, json: boolean): Promise<void> {+ const { migrateAccessStore, previewMigrate } = await import('../core/access/policy-migrate.ts');+ if (!yes) {+ const p = await previewMigrate(engine, sourceId);+ return print(json, { ...p, applied: false }, () => [+ `Source ${sourceId}: move folder rules from the ${p.from ?? 'unset'} store to the ${p.to} store`,+ ...(p.to === 'git' ? [` Writes ${POLICY_FILE} (desired, ${p.desired.length} rule(s)) and ${APPROVED_FILE} (approved, ${p.approved.length} rule(s)) under ${p.root} and commits them through gbrain git commit-push.`]+ : [' The applied rulebook, pending coverage and held widenings stay in the database, which becomes the record.']),+ ' The applied rules stay in force throughout; no rule is missing at any point.',+ ...(p.resume ? [` Resumes migration ${p.resume.id} (phase ${p.resume.phase}).`] : []),+ 'Nothing written. To apply, add --yes.',+ ]);+ }+ const r = await migrateAccessStore(engine, sourceId);+ return print(json, r, () => [`Source ${sourceId}: folder rules now in the ${r.to} store (migration ${r.id}, phase ${r.phase})`,+ ...Object.entries(r.receipts).map(([k, v]) => ` ${k}: ${typeof v === 'object' && v ? (v as { commit?: string }).commit ?? JSON.stringify(v) : String(v)}`)]);+}++async function applyCmd(engine: BrainEngine, args: string[], json: boolean): Promise<void> {+ const sourceId = flag(args, '--source') ?? 'default';+ const revision = intFlag(args, '--revision');+ if (!args.includes('--yes')) {+ const p = await previewApply(engine, sourceId, revision);+ return print(json, { ...p, applied: false }, () => [+ `Source ${sourceId}: ${p.desired ? `desired revision ${p.desired.revision} (${p.desired.origin}, by ${p.desired.proposed_by ?? '?'}, ${p.desired.created_at})` : 'no folder-rule revision'}`,+ ...(p.proposals.length ? [` Proposals not yet approved: ${p.proposals.map(x => `${x.revision} (${x.change_kind})`).join(', ')}`] : []),+ ...(p.widening.length ? p.widening.flatMap(w => [changeLine(w.change),+ ` ${w.pages} page(s) gain readers${w.sample.length ? `: ${w.sample.slice(0, 5).join(', ')}${w.pages > 5 ? ', ...' : ''}` : ''}`,+ ` Gaining access: ${w.gains === 'every_source_reader' ? 'every caller entitled to the source, unbound credentials included' : w.gains.join(', ') || 'no enabled member'}`])+ : [' Nothing is held: the applied rules already match.']),+ ...(p.plan_hash ? [`Nothing written; approve with gbrain access apply --source ${sourceId}${revision ? ` --revision ${revision}` : ''} --yes --expect ${p.plan_hash}`] : []),+ ]);+ }+ const expect = flag(args, '--expect');+ if (!expect) throw usageError('access apply --yes needs --expect <plan_hash> from the preview.', `Preview first: gbrain access apply --source ${sourceId}`);+ const r = await applyApproved(engine, sourceId, { revision, expect, onProgress: progressLogger(json) });+ let git: GitPolicyReceipt | undefined;+ if ((await readAccessStore(engine, sourceId)) === 'git') {+ const root = await sourcePolicyRoot(engine, sourceId);+ const approved = (await getRevision(engine, sourceId, r.revision ?? undefined))?.rules ?? [];+ if (!root || !isGitWorkTree(root)) {+ throw opError('access_policy_store_mismatch', `The widening is applied in the database, but ${APPROVED_FILE} could not be committed: this host sees no git work tree for source ${sourceId}.`,+ `Run gbrain access apply --source ${sourceId} on the host that holds the checkout, or gbrain access rule migrate --source ${sourceId} to keep the rules in the database.`);+ }+ git = await writeApprovedFile(root, approved, `access: approve folder rules revision ${r.revision}`);+ await syncGitPolicy(engine, sourceId, root);+ }+ return print(json, { ...r, ...(git ? { git } : {}) }, () => [`Source ${sourceId}: revision ${r.revision} approved and applied (${r.pages_restamped} page(s) restamped)`,+ ...(git ? [` ${git.path} committed ${git.commit?.slice(0, 12) ?? '(unchanged)'} (${git.outcome})`] : []),+ ...(r.held.length ? [`A later revision still holds ${r.held.length} widening change(s); preview with gbrain access apply --source ${sourceId}`] : [])]);+}++/** Dispatches `gbrain access rule|apply|resume`; false when `cmd` is not one of them. */+export async function runAccessRules(engine: BrainEngine, cmd: string, rest: string[], json: boolean): Promise<boolean> {+ switch (cmd) {+ case 'rule': await ruleCmd(engine, rest[0], rest.slice(1), json); return true;+ case 'apply': await applyCmd(engine, rest, json); return true;+ case 'resume': {+ const sourceId = flag(rest, '--source') ?? 'default';+ const r = await resumePolicy(engine, sourceId, progressLogger(json));+ print(json, { source_id: sourceId, ...r }, () => [`Source ${sourceId}: ${r.pages_restamped} page(s) restamped${r.pending_before.length ? `; pending prefixes cleared: ${r.pending_before.map(p => p || '(whole source)').join(', ')}` : '; nothing was pending'}`]);+ return true;+ }+ default: return false;+ }+}diff --git a/src/commands/access.ts b/src/commands/access.tsindex ead9113a85..311c039bbb 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -12,6 +12,7 @@*/import type { BrainEngine } from '../core/engine.ts';import { exitCliError, usageError } from '../cli/cli-error.ts';+import { runAccessRules } from './access-rules.ts';import { opError } from '../core/ops/contract.ts';import { sqlQueryForEngine } from '../core/sql-query.ts';import { grantFromClient, type PrincipalGrant } from '../core/grants/model.ts';@@ -38,6 +39,20 @@ Members and groups:removing the group (--yes applies)gbrain access group list [<group>]+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+ gbrain access rule rm <rule> [--source <id>] [--yes]+ A widening: recorded and held until gbrain access apply+ gbrain access rule list|status|history [--source <id>] [--operation <id>]+ gbrain access rule revert --to <revision> [--source <id>] [--yes]+ gbrain access rule export|import [--file <access.yml>] [--source <id>] [--yes]+ gbrain access rule migrate [--source <id>] [--yes]+ Move the rules between the database and git stores+ gbrain access apply [--source <id>] [--revision <n>] [--yes --expect <plan_hash>]+ Preview held widenings; --yes approves the previewed plan+ gbrain access resume [--source <id>] Finish a narrowing that was interrupted while stamping pages+Checks (read-only):gbrain access who-can-read <slug> [--source <id>]The page's readers, its privacy, and which members may read it@@ -245,6 +260,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<voif (cmd !== 'check' && rest.some(a => a === '--as' || a.startsWith('--as='))) {throw usageError(`--as is not an option of gbrain access ${cmd}.`, 'gbrain access check --token <name> --as a,b evaluates an audience; operations take --as <member> to preview a member view.');}+ if (await runAccessRules(engine, cmd!, rest, json)) return;switch (cmd) {case 'member': return await memberCmd(engine, rest[0], rest.slice(1), json);case 'group': return await groupCmd(engine, rest[0], rest.slice(1), json);@@ -272,7 +288,7 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<vo` ${r.explanation}`]);}default:- throw usageError(`Unknown access subcommand: ${cmd}.`, 'Use member, group, who-can-read or check (gbrain access --help).', { code: 'unknown_command' });+ throw usageError(`Unknown access subcommand: ${cmd}.`, 'Use member, 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/doctor/checks/folder-access.ts b/src/commands/doctor/checks/folder-access.tsnew file mode 100644index 0000000000..25062339c3--- /dev/null+++ b/src/commands/doctor/checks/folder-access.ts@@ -0,0 +1,124 @@+/**+ * GBRA-218 (A2) folder-rule doctor checks. Each reads the policy tables once,+ * names the source, and fixes with a read-only, preview-first or+ * narrowing-only command whose `verify` is the check itself.+ *+ * - access_policy_pending: prefixes still reading as nobody because a+ * narrowing was not finished, or pages whose stamp drifted from the+ * applied rulebook; `gbrain access resume` restamps toward the applied rules.+ * - access_policy_widening_held: a desired revision widens the applied rules+ * and waits for `gbrain access apply` (preview, then the user's approval).+ * - access_policy_invalid: a committed policy file that does not validate;+ * the prefixes it names read as nobody.+ * - access_policy_store_mismatch: the persisted store disagrees with this+ * host's filesystem (a git store without a visible work tree, a database+ * store whose root became a repository); `gbrain access rule migrate`.+ *+ * Not applicable on a brain where no source has ever had a folder rule.+ */+import type { Check } from '../../doctor.ts';+import type { BrainEngine } from '../../../core/engine.ts';+import { agentFix, checkError, doctorVerify, infoCheck } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { classifyRulebook } from '../../../core/access/folder-rules.ts';+import { appliedRules, coverageRows, getRevision, readAccessStore } from '../../../core/access/policy.ts';+import { isGitWorkTree, sourcePolicyRoot } from '../../../core/access/policy-git.ts';++const DOCS = 'docs/guides/write-refusals.md#access_policy_pending';++async function policySources(engine: BrainEngine): Promise<string[]> {+ return (await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM access_policy_state ORDER BY source_id')).map(r => r.source_id);+}++async function pending(engine: BrainEngine, sources: string[]): Promise<Check> {+ const name = 'access_policy_pending';+ const found: Array<{ source: string; prefixes: string[]; drifted: number }> = [];+ for (const source of sources) {+ const prefixes = (await coverageRows(engine, source)).filter(c => c.reason === 'pending').map(c => c.prefix || '(whole source)');+ const [row] = await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND folder_rule_ids IS DISTINCT FROM gbrain_access_folder_rules(source_id, slug)', [source]);+ if (prefixes.length || row?.n) found.push({ source, prefixes, drifted: Number(row?.n ?? 0) });+ }+ if (!found.length) return { name, status: 'ok', details: { sources: [] }, message: 'Every folder rule is fully applied: no prefix is pending and every page is stamped from the applied rules.' };+ const first = found[0]!;+ return { name, status: 'warn', details: { sources: found },+ message: `Folder rules are not fully applied in ${found.map(f => `${f.source} (${f.prefixes.length ? `pending: ${f.prefixes.join(', ')}` : ''}${f.prefixes.length && f.drifted ? '; ' : ''}${f.drifted ? `${f.drifted} page(s) stamped from other rules` : ''})`).join('; ')}. `+ + 'Pending prefixes read as nobody for remote callers until the apply finishes; resume restamps toward the applied rules and never widens.',+ fix: agentFix(['gbrain', 'access', 'resume', '--source', first.source], 'Restamps pages toward the applied folder rules and clears the pending prefixes; narrowing only, idempotent.', name, { docs: DOCS }) };+}++async function held(engine: BrainEngine, sources: string[]): Promise<Check> {+ const name = 'access_policy_widening_held';+ const found: Array<{ source: string; revision: number; proposed_by: string | null; at: string; changes: string[] }> = [];+ for (const source of sources) {+ const desired = await getRevision(engine, source);+ if (!desired) continue;+ const h = classifyRulebook(await appliedRules(engine, source), desired.rules).held;+ if (h.length) found.push({ source, revision: desired.revision, proposed_by: desired.proposed_by, at: desired.created_at, changes: h.map(c => `${c.kind} ${c.rule} (${c.prefix})`) });+ }+ if (!found.length) return { name, status: 'ok', details: { sources: [] }, message: 'No folder-rule widening is waiting for approval.' };+ const first = found[0]!;+ return { name, status: 'warn', details: { sources: found },+ message: `Widening changes to folder rules are held: ${found.map(f => `${f.source} revision ${f.revision} by ${f.proposed_by ?? 'an unrecorded actor'} at ${f.at}: ${f.changes.join(', ')}`).join('; ')}. `+ + 'The previous rules stay in force until the user approves the previewed plan.',+ fix: agentFix(['gbrain', 'access', 'apply', '--source', first.source, '--json'], 'Previews the pages and members that would gain access and prints the plan hash an approval binds; changes nothing. Ask the user before approving.', name,+ { ask_user: true, docs: 'docs/guides/error-codes.md#access_policy_widening_held' }) };+}++async function invalid(engine: BrainEngine, sources: string[]): Promise<Check> {+ const name = 'access_policy_invalid';+ const found: Array<{ source: string; prefixes: string[]; problems: unknown }> = [];+ for (const source of sources) {+ const rows = (await coverageRows(engine, source)).filter(c => c.reason === 'invalid');+ if (rows.length) found.push({ source, prefixes: rows.map(r => r.prefix || '(whole source)'), problems: (rows[0]!.detail as { problems?: unknown } | null)?.problems ?? null });+ }+ if (!found.length) return { name, status: 'ok', details: { sources: [] }, message: 'Every committed folder-rule file validates.' };+ const first = found[0]!;+ return { name, status: 'fail', details: { sources: found },+ message: `The folder-rule file of ${found.map(f => `${f.source} does not validate (reads as nobody: ${f.prefixes.join(', ')})`).join('; ')}. The last applied rules stay in force. Fix .gbrain/access.yml, commit it and sync the source.`,+ fix: { ...agentFix(['gbrain', 'access', 'rule', 'list', '--source', first.source, '--json'], 'Lists each problem in the file with its line, read-only; fix the file, commit it with gbrain git commit-push and run gbrain sync --source <id> --no-pull.', name,+ { docs: 'docs/guides/write-refusals.md#access_policy_invalid' }), verify: doctorVerify(name) } };+}++async function storeMismatch(engine: BrainEngine, sources: string[]): Promise<Check> {+ const name = 'access_policy_store_mismatch';+ const found: Array<{ source: string; store: string; root: string | null; git: boolean }> = [];+ for (const source of sources) {+ const store = await readAccessStore(engine, source);+ if (!store) continue;+ const root = await sourcePolicyRoot(engine, source);+ const git = !!root && isGitWorkTree(root);+ if ((store === 'git') !== git) found.push({ source, store, root, git });+ }+ if (!found.length) return { name, status: 'ok', details: { sources: [] }, message: 'Every source keeps its folder rules in the store its filesystem matches.' };+ const first = found[0]!;+ return { name, status: 'warn', details: { sources: found },+ message: `${found.map(f => f.store === 'git' ? `${f.source} keeps its folder rules in git, but this host sees no git work tree at ${f.root ?? 'its root'}` : `${f.source} keeps its folder rules in the database, but its root is now a git work tree`).join('; ')}. `+ + 'The persisted store and its applied rules stay in force; only gbrain access rule migrate moves them, and neither direction widens.',+ fix: { argv: ['gbrain', 'access', 'rule', 'migrate', '--source', first.source, '--json'], consent: [], actor: 'user', ask_user: true, requires_exclusive: false,+ why: 'Previews moving the folder rules to the store this host sees; writes nothing without --yes.', verify: doctorVerify(name), docs: 'docs/guides/error-codes.md#access_policy_store_mismatch' } };+}++async function guarded(name: string, run: (engine: BrainEngine, sources: string[]) => Promise<Check>, engine: BrainEngine, sources: string[] | null): Promise<Omit<Check, 'name'>> {+ const { name: _name, ...check } = sources === null || sources.length+ ? await run(engine, sources ?? []).catch(error => checkError(name, `run ${name}`, error))+ : infoCheck(name, 'Not applicable: no source has a folder rule.', 'not_applicable');+ return check;+}++async function runFolderAccess(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const sources = await policySources(engine).catch(() => null);+ const checks: Check[] = [];+ checks.push({ name: 'access_policy_pending', ...await guarded('access_policy_pending', pending, engine, sources) });+ checks.push({ name: 'access_policy_widening_held', ...await guarded('access_policy_widening_held', held, engine, sources) });+ checks.push({ name: 'access_policy_invalid', ...await guarded('access_policy_invalid', invalid, engine, sources) });+ checks.push({ name: 'access_policy_store_mismatch', ...await guarded('access_policy_store_mismatch', storeMismatch, engine, sources) });+ return checks;+}++export const folderAccessEntry: DoctorEntry = {+ name: 'access_policy_pending',+ emits: ['access_policy_pending', 'access_policy_widening_held', 'access_policy_invalid', 'access_policy_store_mismatch'],+ run: runFolderAccess,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 071ee6f68b..62b6185948 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -127,6 +127,7 @@ import { gitIndexLagEntry } from './checks/git-index-lag.ts';import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { memberAccessEntry } from './checks/member-access.ts';+import { folderAccessEntry } from './checks/folder-access.ts';import { originTwinsEntry } from './checks/origin-twins.ts';import { slugPathMismatchEntry } from './checks/slug-path-mismatch.ts';import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';@@ -206,6 +207,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [// #7276: the privacy check next, with its own entry budget, before any full scan.derivedVisibilityEntry,memberAccessEntry,+ folderAccessEntry,rlsEntry,schemaVersionEntry,rlsEventTriggerEntry,diff --git a/src/commands/export.ts b/src/commands/export.tsindex f2f85ba7c0..42856f33fa 100644--- a/src/commands/export.ts+++ b/src/commands/export.ts@@ -13,6 +13,7 @@ import { publishExport } from '../core/export-publish.ts';import { nativeFileTarget } from '../core/persistence/native-file-target.ts';import { exportBodyLedger, inlineExportMarkdown, readExportPage, readExportWithdrawals, segmentedExportHead, segmentedExportMarkdown } from '../core/export-snapshot.ts';import { segmentedPageCeiling } from '../core/page-body/limits.ts';+import { exportPolicyFiles } from '../core/access/policy-transfer.ts';import { isSegmentedPage } from '../core/page-body/page-shape.ts';function option(args: string[], name: string): string | undefined {@@ -177,6 +178,7 @@ a fresh directory. See docs/storage-tiering.md#safe-export.`);}checkDeadline();if (collisions.length) throw collisionRefusal(collisions, owners, outDir);+ if (!restoreOnly) for (const file of await exportPolicyFiles(tx, source && source !== ALL_SOURCES ? source : null)) staged.add(file.path, 'file', file.content);});console.log(`${restoreOnly ? 'Restoring' : 'Exporting'} ${stage.pages}${restoreOnly ? ' db_only' : ''} pages to ${outDir}/`);const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));diff --git a/src/commands/import.ts b/src/commands/import.tsindex e7f6b27757..3c55e34cf9 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -499,10 +499,10 @@ export async function runImport(if (workersIdx !== -1) flagValues.add(workersIdx + 1);if (sourceIdIdx !== -1) flagValues.add(sourceIdIdx + 1);if (sourceIdx !== -1) flagValues.add(sourceIdx + 1);- const dirArg = args.find((a, i) => !a.startsWith('--') && !flagValues.has(i));+ const dirArg = args.find((a, i) => !a.startsWith('--') && !flagValues.has(i) && args[i - 1] !== '--access-policy');if (!dirArg) {- console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source <id> | --source-id <id>] [--include-gitignored] [--allow-noncanonical-root] [--json]');+ console.error('Usage: gbrain import <dir> [--no-embed] [--workers N] [--fresh] [--source <id> | --source-id <id>] [--access-policy <exported-source>|none] [--include-gitignored] [--allow-noncanonical-root] [--json]');throw new ImportAbortError('no import directory given');}// #1728: capture the import target ONCE as an absolute real path. Every@@ -568,6 +568,7 @@ export async function runImport(}}+ if (!opts.commit && !singleFile && !currentCompanyBrainSync(sourceId)) await (await import('../core/access/policy-transfer.ts')).importPolicyBarrier(engine, sourceId ?? 'default', dir, args, info).catch(e => { throw new ImportAbortError('folder rules not installed', 1, undefined, e); });// v0.31.2: collect under the right strategy. Pre-fix this called// collectMarkdownFiles unconditionally — code-strategy first sync// silently no-op'd because no code file ever made it through walkerdiff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex ce7c1716b4..df4c6ec418 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -133,6 +133,10 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promiconst opts: SyncOpts = leaseSignal ? { ...outer, signal: outer.signal ? AbortSignal.any([outer.signal, leaseSignal]) : leaseSignal } : outer;// #7167: a dry run reads and previews once; the drain's stall governor (no commit in 5 min) would abandon a long read// of a large source as a writer stall, and nothing it does is a write the drain needs to watch.+ // GBRA-218 (A2): the committed folder rules apply before and after the drain (managed sync moves the checkout).+ const policy = opts.dryRun ? null : await import('../../core/access/policy-git.ts');+ const policyRoot = policy ? opts.repoPath ?? await policy.sourcePolicyRoot(engine, sourceId) : null;+ if (policy) await policy.syncAccessPolicyAt(engine, sourceId, policyRoot, 'HEAD', serr);let result = opts.drain && !opts.dryRun? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true): await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);@@ -154,6 +158,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi...(n ? { drain: { ...n, passes: d.passes + n.passes, processed: d.processed + n.processed, written: d.written + n.written, waived: d.waived + n.waived } } : {}) };if (!next.staged) serr(`[sync] staged catch-up reached HEAD after ${stages} stages.`);}+ if (policy) await policy.syncAccessPolicyAt(engine, sourceId, policyRoot, 'HEAD', serr);printInheritedOptions(result);if (opts.dryRun) return result;skips = (await import('../../core/persistence/sync-idle-skips.ts')).idleSkips(sourceId);diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.tsindex f4f915baad..bf6b809382 100644--- a/src/commands/sync/preflight.ts+++ b/src/commands/sync/preflight.ts@@ -57,6 +57,7 @@ import { sweepOrphanedRenameSentinels } from './rename-reconcile.ts';import type { SyncPlan, SyncActivePack } from './sync-run.ts';import { holdUnsupportedPaths, NO_BYTE_PATHS, selectBytePaths, type BytePaths } from './unsupported-paths.ts';import { formatUrlClonePullBlock, urlClonePullBlock } from '../../core/url-clone.ts';+import { syncAccessPolicyAt } from '../../core/access/policy-git.ts';import { formatUpstreamNotice, recordUpstreamBeforeFetch, settleUpstreamAfterPull } from '../../core/sync-upstream-rewrite.ts';export type PreflightOutcome = { readonly done: SyncResult } | { readonly plan: SyncPlan };@@ -70,6 +71,9 @@ export async function preflightIncrementalSync(engine: BrainEngine, opts: SyncOpconst head = await pullAndResolveHead(engine, opts, company, repoPath, gitContextRoot);if ('done' in head) return head;const { detachedHead, lastCommit, pullFailed, headCommit } = head;+ // GBRA-218 (A2): the source's folder rules at the synced commit apply before any page of it is imported, including+ // when .gbrain/access.yml is the only changed path (the delta below skips dot paths).+ if (!opts.dryRun) await syncAccessPolicyAt(engine, opts.sourceId ?? DEFAULT_SOURCE_ID, repoPath, headCommit, serr);opts = await applyPersistedScopeConfig(engine, opts);diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex 045bb2c70c..541c7a74d0 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 { accessRestrictionsPresent, remotePrivacyRelaxed, type CallerAccess } from '../search/private-visibility.ts';+import { accessRestrictionsPresent, remotePrivacyRelaxed, type CallerAccess, type FolderCoverage } from '../search/private-visibility.ts';import { ACCESS_ID_RE, identityFor, normalizePrincipal } from './principals.ts';/** Config key binding a local stdio MCP server to one member. */@@ -65,6 +65,23 @@ export async function stdioMemberIdentity(engine: BrainEngine): Promise<string[]return member ? liveIdentity(engine, '$1', member) : [];}+/**+ * GBRA-218 (A2): the folder-rule part of a caller's record, read live from the applied rulebook: the+ * source-qualified ids of the rules `identity` satisfies, and every prefix that reads as nobody (a narrowing being+ * stamped, an invalid policy file). An unreadable rulebook satisfies nothing and covers everything (fail closed).+ */+export async function folderAccessFor(engine: Pick<BrainEngine, 'executeRaw'>, identity: readonly string[]): Promise<{ satisfiedRuleIds: string[]; folderCoverage: FolderCoverage[] }> {+ try {+ const rules = identity.length+ ? await engine.executeRaw<{ source_id: string; rule_id: string }>('SELECT source_id, rule_id FROM access_rules WHERE readable_by && $1::text[]', [[...identity]])+ : [];+ const coverage = await engine.executeRaw<{ source_id: string; prefix: string }>('SELECT DISTINCT source_id, prefix FROM access_pending_coverage ORDER BY source_id, prefix');+ return { satisfiedRuleIds: rules.map(r => `${r.source_id}:${r.rule_id}`).sort(), folderCoverage: coverage.map(c => ({ source_id: c.source_id, prefix: c.prefix })) };+ } catch {+ return { satisfiedRuleIds: [], folderCoverage: [{ source_id: '!unreadable', prefix: '' }] };+ }+}+/** The CallerAccess fields for a remote operation (identity, privacy relaxation and the GBRA-156 private-readable set). */export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string): Promise<Partial<CallerAccess>> {const [relaxed, restricted] = await Promise.all([remotePrivacyRelaxed(engine), accessRestrictionsPresent(engine)]);@@ -73,6 +90,7 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | u: await memberIdentityFor(engine, auth);return {identity,+ ...(restricted ? await folderAccessFor(engine, identity) : { satisfiedRuleIds: [], folderCoverage: [] }),privateReadableSources: privateSources ?? [],hidePrivate: !relaxed,applyRemoteReadPolicy: false,diff --git a/src/core/access/folder-rules.ts b/src/core/access/folder-rules.tsnew file mode 100644index 0000000000..9c06410966--- /dev/null+++ b/src/core/access/folder-rules.ts@@ -0,0 +1,273 @@+/**+ * GBRA-218 (PR A2): the folder-rule grammar, shared by the git policy file+ * (`<source root>/.gbrain/access.yml`), `gbrain access rule export|import|migrate`+ * and `gbrain export` / `import`. One parser, so every path accepts and refuses+ * exactly the same rules.+ *+ * version: 1+ * rules:+ * - id: alice-notes # optional; derived from the prefix+ * prefix: partners/alice-example/ # literal slug prefix, lower case, ends in '/'+ * readable_by: [alice-example, group:team-a]+ *+ * A prefix is matched literally against the source's slugs (never LIKE): it is+ * lower case, built of segments that start with a letter or digit, ends in+ * '/', and holds no '..' or '*'. Rule ids are stable: an omitted id is derived+ * deterministically from the normalized prefix. Duplicate ids or prefixes make+ * the file invalid. Readers use the page grammar (principals.ts).+ *+ * classifyRulebook() compares the applied rulebook with a desired one rule by+ * rule: an added rule and removed readers narrow and apply at once; a removed+ * rule, added readers and a moved prefix widen and wait for an operator's+ * `gbrain access apply --yes`. Its target (what is applied now) is never wider+ * than the applied rulebook: a rule whose readers both lose and gain entries+ * applies the intersection.+ */+import { createHash } from 'node:crypto';+import { load, JSON_SCHEMA } from 'js-yaml';+import { ACCESS_ID_RE, normalizePrincipal } from './principals.ts';++export interface FolderRule {+ id: string;+ prefix: string;+ /** Sorted, distinct normalized principals; empty means readable by nobody (an applied intersection only). */+ readable_by: string[];+}++export interface PolicyProblem {+ /** 1-based line in the YAML text, when known. */+ line: number | null;+ message: string;+}++export type ParsedPolicy =+ | { ok: true; rules: FolderRule[] }+ | { ok: false; problems: PolicyProblem[]; /** Valid prefixes the text names; null when they cannot all be read (cover the whole source). */ prefixes: string[] | null };++export const POLICY_VERSION = 1;+export const MAX_RULES = 256;+const MAX_READERS = 256;+const PREFIX_RE = /^(?:[a-z0-9][a-z0-9._-]*\/)+$/;+const RULE_KEYS = new Set(['id', 'prefix', 'readable_by']);++/** A prefix the grammar accepts (also safe to embed as an SQL literal: no quote or backslash). */+export function validPrefix(prefix: string): boolean {+ return prefix.length <= 512 && PREFIX_RE.test(prefix) && !prefix.includes('..');+}++/** A source-qualified rule id (`<source>:<rule>`) safe to embed as an SQL literal. */+export function validQualifiedRuleId(id: string): boolean {+ const i = id.indexOf(':');+ return i > 0 && /^[a-z0-9][a-z0-9_-]{0,31}$/.test(id.slice(0, i)) && ACCESS_ID_RE.test(id.slice(i + 1));+}++/** The id a rule gets when the file omits one: its prefix with '/' as '-', hashed when longer than an id may be. */+export function ruleIdForPrefix(prefix: string): string {+ const base = prefix.slice(0, -1).replace(/\//g, '-');+ if (base.length <= 64) return base;+ return `${base.slice(0, 55).replace(/[._-]+$/, '')}-${createHash('sha256').update(prefix).digest('hex').slice(0, 8)}`;+}++/** Why a prefix is refused, with the corrected form when there is an obvious one. */+function prefixProblem(raw: unknown): string | null {+ if (typeof raw !== 'string' || raw === '') return 'prefix must be a non-empty string such as partners/alice-example/';+ if (raw.includes('*')) return `prefix "${raw}" holds '*': prefixes are literal; name the folder itself, as in ${raw.split('*')[0]!.replace(/[^/]*$/, '') || 'partners/'}`;+ if (raw.includes('..')) return `prefix "${raw}" holds '..'`;+ if (raw.startsWith('/')) return `prefix "${raw}" starts with '/': prefixes are relative to the source's slugs, as in ${raw.replace(/^\/+/, '')}`;+ if (raw !== raw.toLowerCase()) return `prefix "${raw}" is not lower case; slugs are lower case, so write ${raw.toLowerCase()}`;+ if (!raw.endsWith('/')) return `prefix "${raw}" does not end in '/'; write ${raw}/ so it names a folder`;+ if (!validPrefix(raw)) return `prefix "${raw}" is not a slug folder: each segment starts with a letter or digit and holds only a-z, 0-9, '.', '_' and '-'`;+ return null;+}++/** One readers list normalized, or a problem. */+function readersOf(raw: unknown): { readers: string[] } | { problem: string } {+ const list = typeof raw === 'string' ? [raw]+ : Array.isArray(raw) && raw.length >= 1 && raw.length <= MAX_READERS && raw.every(v => typeof v === 'string') ? raw as string[] : null;+ if (!list) return { problem: 'readable_by must be a member id, group:<id>, or a list of 1-256 of them' };+ const out = new Set<string>();+ for (const entry of list) {+ const p = normalizePrincipal(entry);+ if (!p) return { problem: `readable_by entry ${JSON.stringify(entry)} is not a member id or group:<id> (lower-case letters, digits, '.', '_' and '-', 1-64 characters)` };+ out.add(p);+ }+ return { readers: [...out].sort() };+}++/** One rule from untrusted input (a YAML entry or CLI flags), normalized, or the problem with it. */+export function normalizeRule(raw: unknown): { rule: FolderRule } | { problem: string; prefix?: string } {+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return { problem: 'each rule is a mapping with prefix, readable_by and an optional id' };+ const entry = raw as Record<string, unknown>;+ const unknown = Object.keys(entry).filter(k => !RULE_KEYS.has(k));+ const prefixError = prefixProblem(entry.prefix);+ const prefix = prefixError ? undefined : entry.prefix as string;+ if (unknown.length) return { problem: `unknown key ${unknown.map(k => JSON.stringify(k)).join(', ')}; a rule has id, prefix and readable_by`, prefix };+ if (prefixError) return { problem: prefixError };+ const readers = readersOf(entry.readable_by);+ if ('problem' in readers) return { problem: readers.problem, prefix };+ const id = entry.id === undefined ? ruleIdForPrefix(prefix!) : entry.id;+ if (typeof id !== 'string' || !ACCESS_ID_RE.test(id)) return { problem: `id ${JSON.stringify(id)} is not a rule id (lower-case letters, digits, '.', '_' and '-', 1-64 characters)`, prefix };+ return { rule: { id, prefix: prefix!, readable_by: readers.readers } };+}++/** Rules sorted by id with duplicate ids or prefixes reported. */+function checkUnique(rules: Array<{ rule: FolderRule; line: number | null }>): PolicyProblem[] {+ const problems: PolicyProblem[] = [];+ const ids = new Map<string, number | null>();+ const prefixes = new Map<string, string>();+ for (const { rule, line } of rules) {+ if (ids.has(rule.id)) problems.push({ line, message: `rule id "${rule.id}" appears twice; ids are unique within a source` });+ else ids.set(rule.id, line);+ const other = prefixes.get(rule.prefix);+ if (other !== undefined) problems.push({ line, message: `prefix ${rule.prefix} appears in rules "${other}" and "${rule.id}"; merge their readers into one rule` });+ else prefixes.set(rule.prefix, rule.id);+ }+ return problems;+}++/** The 1-based line of each top-level entry of the `rules:` list, by position (null when not found). */+function ruleLines(text: string): Array<number> {+ const lines = text.split('\n');+ const start = lines.findIndex(l => /^rules\s*:/.test(l));+ if (start < 0) return [];+ let indent: number | null = null;+ const out: number[] = [];+ for (let i = start + 1; i < lines.length; i++) {+ const l = lines[i]!;+ if (/^\S/.test(l) && !l.startsWith('-') && !l.startsWith('#')) break;+ const m = /^(\s*)-\s/.exec(l) ?? /^(\s*)-$/.exec(l);+ if (!m) continue;+ if (indent === null) indent = m[1]!.length;+ if (m[1]!.length === indent) out.push(i + 1);+ }+ return out;+}++/** Parses a policy file's text (YAML, JSON schema only: no tags, anchors resolve to plain data). */+export function parsePolicyYaml(text: string): ParsedPolicy {+ let doc: unknown;+ try {+ doc = load(text, { schema: JSON_SCHEMA, json: false });+ } catch (e) {+ const mark = (e as { mark?: { line?: number } }).mark;+ return { ok: false, problems: [{ line: typeof mark?.line === 'number' ? mark.line + 1 : null, message: `not valid YAML: ${(e as Error).message.split('\n')[0]}` }], prefixes: null };+ }+ if (doc === undefined || doc === null) return { ok: true, rules: [] };+ if (typeof doc !== 'object' || Array.isArray(doc)) return { ok: false, problems: [{ line: 1, message: 'the file must be a mapping with version: 1 and rules: [...]' }], prefixes: null };+ const top = doc as Record<string, unknown>;+ const problems: PolicyProblem[] = [];+ for (const key of Object.keys(top)) if (key !== 'version' && key !== 'rules') problems.push({ line: null, message: `unknown top-level key ${JSON.stringify(key)}; the file has version and rules` });+ if (top.version !== POLICY_VERSION) problems.push({ line: null, message: `version must be ${POLICY_VERSION} (found ${JSON.stringify(top.version ?? null)})` });+ const rawRules = top.rules ?? [];+ if (!Array.isArray(rawRules)) return { ok: false, problems: [...problems, { line: null, message: 'rules must be a list' }], prefixes: null };+ if (rawRules.length > MAX_RULES) problems.push({ line: null, message: `${rawRules.length} rules; a source holds at most ${MAX_RULES}` });+ const lines = ruleLines(text);+ const parsed: Array<{ rule: FolderRule; line: number | null }> = [];+ const prefixes = new Set<string>();+ let allPrefixesKnown = true;+ rawRules.forEach((raw, i) => {+ const line = lines[i] ?? null;+ const r = normalizeRule(raw);+ if ('rule' in r) { parsed.push({ rule: r.rule, line }); prefixes.add(r.rule.prefix); return; }+ if (r.prefix) prefixes.add(r.prefix); else allPrefixesKnown = false;+ problems.push({ line, message: `rule ${i + 1}: ${r.problem}` });+ });+ problems.push(...checkUnique(parsed));+ if (problems.length) return { ok: false, problems, prefixes: allPrefixesKnown ? [...prefixes].sort() : null };+ return { ok: true, rules: sortRules(parsed.map(p => p.rule)) };+}++export function sortRules(rules: readonly FolderRule[]): FolderRule[] {+ return [...rules].map(r => ({ id: r.id, prefix: r.prefix, readable_by: [...new Set(r.readable_by)].sort() })).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+}++/** The file text for a rulebook: the same grammar parsePolicyYaml reads, members written bare. */+export function serializePolicyYaml(rules: readonly FolderRule[], comment?: string): string {+ const reader = (p: string) => p.startsWith('member:') ? p.slice(7) : p;+ const lines = [...(comment ? comment.split('\n').map(l => `# ${l}`) : []), `version: ${POLICY_VERSION}`];+ const sorted = sortRules(rules);+ if (!sorted.length) return [...lines, 'rules: []', ''].join('\n');+ lines.push('rules:');+ for (const r of sorted) {+ lines.push(` - id: ${r.id}`, ` prefix: ${r.prefix}`, ` readable_by: [${r.readable_by.map(reader).join(', ')}]`);+ }+ return [...lines, ''].join('\n');+}++/** A content digest of a rulebook (sha256 over its canonical JSON); equal rulebooks have equal digests. */+export function rulebookDigest(rules: readonly FolderRule[]): string {+ return createHash('sha256').update(JSON.stringify(sortRules(rules).map(r => [r.id, r.prefix, r.readable_by]))).digest('hex');+}++/** Rules read back from a stored JSON value (revisions, exports); anything malformed is refused, never repaired. */+export function rulesFromJson(value: unknown): FolderRule[] {+ const raw = typeof value === 'string' ? JSON.parse(value) : value;+ if (!Array.isArray(raw)) throw new Error('stored rulebook is not a list');+ return sortRules(raw.map(r => {+ const rule = r as FolderRule;+ if (!rule || typeof rule.id !== 'string' || !ACCESS_ID_RE.test(rule.id) || typeof rule.prefix !== 'string' || !validPrefix(rule.prefix)+ || !Array.isArray(rule.readable_by) || !rule.readable_by.every(p => typeof p === 'string' && normalizePrincipal(p) === p)) {+ throw new Error('stored rulebook holds a malformed rule');+ }+ return rule;+ }));+}++export type ChangeKind = 'added' | 'removed' | 'readers_removed' | 'readers_added' | 'prefix_moved';++export interface RuleChange {+ rule: string;+ kind: ChangeKind;+ narrowing: boolean;+ prefix: string;+ /** For reader changes: the principals removed or added. */+ readers?: string[];+}++export interface Classification {+ /** What to apply now: the applied rulebook with every narrowing change and none of the widening ones. */+ target: FolderRule[];+ changes: RuleChange[];+ /** The widening changes the target leaves out (held for gbrain access apply). */+ held: RuleChange[];+ kind: 'narrowing' | 'widening' | 'mixed' | 'unchanged';+}++/** Classifies the move from the applied rulebook to a desired one, rule by rule (see the module comment). */+export function classifyRulebook(applied: readonly FolderRule[], desired: readonly FolderRule[]): Classification {+ const before = new Map(sortRules(applied).map(r => [r.id, r]));+ const after = new Map(sortRules(desired).map(r => [r.id, r]));+ const target: FolderRule[] = [];+ const changes: RuleChange[] = [];+ for (const [id, a] of after) {+ const b = before.get(id);+ if (!b) { target.push(a); changes.push({ rule: id, kind: 'added', narrowing: true, prefix: a.prefix }); continue; }+ if (b.prefix !== a.prefix) { target.push(b); changes.push({ rule: id, kind: 'prefix_moved', narrowing: false, prefix: a.prefix }); continue; }+ const removed = b.readable_by.filter(p => !a.readable_by.includes(p));+ const added = a.readable_by.filter(p => !b.readable_by.includes(p));+ target.push({ id, prefix: b.prefix, readable_by: b.readable_by.filter(p => a.readable_by.includes(p)) });+ if (removed.length) changes.push({ rule: id, kind: 'readers_removed', narrowing: true, prefix: b.prefix, readers: removed });+ if (added.length) changes.push({ rule: id, kind: 'readers_added', narrowing: false, prefix: b.prefix, readers: added });+ }+ for (const [id, b] of before) {+ if (after.has(id)) continue;+ target.push(b);+ changes.push({ rule: id, kind: 'removed', narrowing: false, prefix: b.prefix });+ }+ // A desired rule that takes the prefix of a rule the target still holds (an id renamed) leaves two rules on one prefix+ // until the removal is approved; both have to pass, which is never wider than either.+ const held = changes.filter(c => !c.narrowing);+ const kind = !changes.length ? 'unchanged' : !held.length ? 'narrowing' : held.length === changes.length ? 'widening' : 'mixed';+ return { target: sortRules(target), changes, held, kind };+}++/** The rule ids (unqualified) whose prefix `slug` starts with, sorted; null when none (the row twin of gbrain_access_folder_rules). */+export function matchingRuleIds(slug: string, rules: readonly FolderRule[]): string[] | null {+ const ids = rules.filter(r => slug.startsWith(r.prefix)).map(r => r.id).sort();+ return ids.length ? ids : null;+}++/** Whether a caller with `identity` passes every rule matching `slug` (the row twin of the folder part of the predicate). */+export function folderRulesAllow(slug: string, rules: readonly FolderRule[], identity: readonly string[]): boolean {+ return rules.filter(r => slug.startsWith(r.prefix)).every(r => r.readable_by.some(p => identity.includes(p)));+}diff --git a/src/core/access/policy-git.ts b/src/core/access/policy-git.tsnew file mode 100644index 0000000000..296638a33c--- /dev/null+++ b/src/core/access/policy-git.ts@@ -0,0 +1,185 @@+/**+ * GBRA-218 (PR A2): the git store of folder rules. On a git-backed source the+ * desired rules are `<source root>/.gbrain/access.yml` and the approved baseline is+ * `<source root>/.gbrain/access.approved` (the approved rulebook in the same grammar),+ * both committed through the one door (`gbrain git commit-push`, the checkout's+ * commit lock). Sync reads both explicitly from the synced commit (it skips dot+ * paths otherwise) and hands the desired rulebook to the shared lifecycle in+ * policy.ts, which applies narrowing at once and holds widening. The serve+ * path never calls git: page writes stamp from the applied rulebook in the+ * database.+ *+ * An approved file is trusted as the baseline only when the database has no+ * revision for the source yet (a rebuild or a second database, which then+ * reaches the same applied rules from git alone) or when it matches the+ * database's approved revision. An access.approved changed by a plain commit+ * is reported and ignored, so git write access alone never widens.+ */+import { spawnSync } from '../spawn.ts';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readSyncAnchor } from '../sync-anchor.ts';+import { acquireCommitLock, checkoutRoot, commitAndPush, COMMIT_LOCK_ENV, type CommitPushResult } from '../git/commit-push.ts';+import { parsePolicyYaml, rulebookDigest, serializePolicyYaml, type FolderRule, type PolicyProblem } from './folder-rules.ts';+import { clearPolicyInvalid, getRevision, listRevisions, markPolicyInvalid, proposeRevision, readAccessStore, writeAccessStore, type ProposalResult, type RestampProgress } from './policy.ts';++export const POLICY_DIR = '.gbrain';+export const POLICY_FILE = '.gbrain/access.yml';+export const APPROVED_FILE = '.gbrain/access.approved';+const POLICY_HEADER = 'Folder read rules for this source (gbrain access rule add|rm). Narrowing changes apply at the next sync;\nwidening changes wait for gbrain access apply --source <id> on the brain host.';+const APPROVED_HEADER = 'The folder rules an operator approved with gbrain access apply. Written by gbrain; do not edit.';++/** The filesystem root of a source (its local path, or sync.repo_path for the default source), or null. */+export async function sourcePolicyRoot(engine: BrainEngine, sourceId: string): Promise<string | null> {+ const root = await readSyncAnchor(engine, sourceId, 'repo_path');+ return root && existsSync(root) ? root : null;+}++/** Whether `root` is inside a git work tree. */+export function isGitWorkTree(root: string): boolean {+ const r = spawnSync('git', ['-C', root, 'rev-parse', '--is-inside-work-tree'], { encoding: 'utf8' });+ return r.status === 0 && r.stdout.trim() === 'true';+}++function gitShow(root: string, rev: string, path: string): string | null {+ const r = spawnSync('git', ['show', `${rev}:./${path}`], { cwd: root, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 });+ return r.status === 0 ? r.stdout : null;+}++export interface CommittedPolicy { yml: string | null; approved: string | null; commit: string | null }++/** The policy files as committed at `rev` (never the working tree), and the last commit that touched access.yml. */+export function readCommittedPolicy(root: string, rev = 'HEAD'): CommittedPolicy {+ const log = spawnSync('git', ['log', '-1', '--format=%h %an', rev, '--', POLICY_FILE], { cwd: root, encoding: 'utf8' });+ return { yml: gitShow(root, rev, POLICY_FILE), approved: gitShow(root, rev, APPROVED_FILE), commit: log.status === 0 && log.stdout.trim() ? log.stdout.trim() : null };+}++export interface GitPolicySyncResult {+ source_id: string;+ state: 'skipped' | 'invalid' | ProposalResult['state'];+ reason?: 'database_store' | 'no_policy';+ proposal?: ProposalResult;+ problems?: PolicyProblem[];+ commit?: string | null;+ /** access.approved differs from the database's approved revision and was ignored (approve with gbrain access apply). */+ approved_file?: 'matches' | 'absent' | 'untrusted' | 'invalid' | 'loaded';+}++/** Reads the committed policy of a git-store source at `rev` and applies it through the shared lifecycle. */+export async function syncGitPolicy(engine: BrainEngine, sourceId: string, root: string, opts: { rev?: string; onProgress?: (p: RestampProgress) => void } = {}): Promise<GitPolicySyncResult> {+ const store = await readAccessStore(engine, sourceId);+ if (store === 'database') return { source_id: sourceId, state: 'skipped', reason: 'database_store' };+ const files = readCommittedPolicy(root, opts.rev ?? 'HEAD');+ if (files.yml === null && files.approved === null && store !== 'git') return { source_id: sourceId, state: 'skipped', reason: 'no_policy' };+ let approvedFile: GitPolicySyncResult['approved_file'] = 'absent';+ if (files.approved !== null) {+ const approved = parsePolicyYaml(files.approved);+ if (!approved.ok) approvedFile = 'invalid';+ else if (!(await getRevision(engine, sourceId))) {+ await proposeRevision(engine, sourceId, approved.rules, { origin: 'git-approved', approved: true, store: 'git', proposedBy: 'git:access.approved', onProgress: opts.onProgress });+ approvedFile = 'loaded';+ } else {+ const lastApproved = (await listRevisions(engine, sourceId, 500)).find(r => r.approved_at);+ approvedFile = lastApproved?.digest === rulebookDigest(approved.rules) ? 'matches' : 'untrusted';+ }+ }+ const desired = files.yml === null ? { ok: true as const, rules: [] as FolderRule[] } : parsePolicyYaml(files.yml);+ if (!desired.ok) {+ await markPolicyInvalid(engine, sourceId, desired.prefixes, { problems: desired.problems, commit: files.commit, file: POLICY_FILE });+ if (store !== 'git') await writeAccessStore(engine, sourceId, 'git');+ return { source_id: sourceId, state: 'invalid', problems: desired.problems, commit: files.commit, approved_file: approvedFile };+ }+ await clearPolicyInvalid(engine, sourceId);+ const proposal = await proposeRevision(engine, sourceId, desired.rules, { origin: 'git', store: 'git', proposedBy: files.commit ? `git:${files.commit}` : 'git', onProgress: opts.onProgress });+ return { source_id: sourceId, state: proposal.state, proposal, commit: files.commit, approved_file: approvedFile };+}++export interface GitPolicyReceipt {+ outcome: CommitPushResult['outcome'] | 'committed_not_pushed';+ commit: string | null;+ path: string;+ note?: string;+}++/**+ * Writes one policy file under the checkout's commit lock (held across the read, the edit and the commit) and commits it+ * through the door. commit_lock_busy is retried once; integrate_conflict and writer_coordinator_required propagate (the+ * first needs the user's choice, the second a managed write on the brain host); a commit whose push is unconfirmed is a+ * success with a note.+ */+export async function commitPolicyFile(root: string, relPath: string, edit: (current: string | null) => string, message: string): Promise<GitPolicyReceipt> {+ const file = join(root, relPath);+ const attempt = (): GitPolicyReceipt => {+ const lock = acquireCommitLock(checkoutRoot(root));+ const prior = process.env[COMMIT_LOCK_ENV];+ process.env[COMMIT_LOCK_ENV] = lock.lockPath;+ try {+ const current = existsSync(file) ? readFileSync(file, 'utf8') : null;+ mkdirSync(join(root, POLICY_DIR), { recursive: true });+ const next = edit(current);+ writeFileSync(file, next);+ try {+ const r = commitAndPush({ repo: root, cwd: root, paths: [file], message });+ return { outcome: r.outcome, commit: r.committed ?? r.sha, path: relPath,+ ...(r.outcome === 'committed_local' ? { note: 'Committed locally; this checkout has no remote or is managed, so nothing was pushed.' } : {}) };+ } catch (e) {+ if (e instanceof OperationError && (e.code === 'push_unconfirmed' || (e as { canonical?: string }).canonical === 'push_unconfirmed') && e.detail) {+ return { outcome: 'committed_not_pushed', commit: String(e.detail), path: relPath, note: 'Committed locally; the push is unconfirmed. Rerun gbrain git commit-push --push-only to publish it.' };+ }+ if (gitShow(root, 'HEAD', relPath) !== next) {+ if (current === null) rmSync(file, { force: true }); else writeFileSync(file, current);+ }+ throw e;+ }+ } finally {+ if (prior === undefined) delete process.env[COMMIT_LOCK_ENV]; else process.env[COMMIT_LOCK_ENV] = prior;+ lock.release();+ }+ };+ try {+ return attempt();+ } catch (e) {+ if ((e as { code?: string }).code === 'commit_lock_busy') return attempt();+ throw e;+ }+}++/** The desired rules in the working tree's access.yml (what a rule edit starts from); a file that does not validate refuses. */+export function workingTreeRules(root: string, sourceId: string): FolderRule[] {+ const file = join(root, POLICY_FILE);+ if (!existsSync(file)) return [];+ const parsed = parsePolicyYaml(readFileSync(file, 'utf8'));+ if (parsed.ok) return parsed.rules;+ throw opError('access_policy_invalid', `${POLICY_FILE} of source ${sourceId} does not validate: ${parsed.problems.map(p => `${p.line ? `line ${p.line}: ` : ''}${p.message}`).join('; ')}.`,+ `Fix the file (gbrain access rule list --source ${sourceId} shows each problem and line) and commit it with gbrain git commit-push, then retry.`);+}++/** Writes the desired rules to access.yml through the door and applies them at once (as sync would). */+export async function writeGitRules(engine: BrainEngine, sourceId: string, root: string, rules: FolderRule[], message: string, onProgress?: (p: RestampProgress) => void): Promise<{ receipt: GitPolicyReceipt; sync: GitPolicySyncResult }> {+ const receipt = await commitPolicyFile(root, POLICY_FILE, () => serializePolicyYaml(rules, POLICY_HEADER), message);+ const sync = await syncGitPolicy(engine, sourceId, root, { onProgress });+ return { receipt, sync };+}++/** Commits access.approved (the rulebook an operator approved) through the door. */+export async function writeApprovedFile(root: string, rules: FolderRule[], message: string): Promise<GitPolicyReceipt> {+ return commitPolicyFile(root, APPROVED_FILE, () => serializePolicyYaml(rules, APPROVED_HEADER), message);+}++/** Sync's hook: apply the committed policy of a source when its store is git (or unset and the commit holds a policy file). */+export async function syncAccessPolicyAt(engine: BrainEngine, sourceId: string, root: string | null | undefined, rev = 'HEAD', log?: (line: string) => void): Promise<GitPolicySyncResult | null> {+ if (!root || !existsSync(root) || !isGitWorkTree(root)) return null;+ const result = await syncGitPolicy(engine, sourceId, root, { rev });+ if (result.state === 'skipped') return result;+ if (result.state === 'invalid') {+ log?.(`[access] ${POLICY_FILE} of source ${sourceId} does not validate (access_policy_invalid); the last applied rules stay and the prefixes it names read as nobody. Run gbrain access rule list --source ${sourceId}.`);+ } else if (result.proposal?.held.length) {+ log?.(`[access] ${result.proposal.held.length} widening change(s) to source ${sourceId}'s folder rules are held (access_policy_widening_held). Preview with gbrain access apply --source ${sourceId}.`);+ }+ if (result.approved_file === 'untrusted') {+ log?.(`[access] ${APPROVED_FILE} of source ${sourceId} does not match the approved revision in the database and was ignored; approve changes with gbrain access apply.`);+ }+ return result;+}diff --git a/src/core/access/policy-migrate.ts b/src/core/access/policy-migrate.tsnew file mode 100644index 0000000000..df946e881d--- /dev/null+++ b/src/core/access/policy-migrate.ts@@ -0,0 +1,94 @@+/**+ * GBRA-218 (PR A2): `gbrain access rule migrate`, moving a source's folder rules+ * between the database store and the git store without a moment where a rule+ * is missing. The applied rulebook in the database stays in force throughout;+ * only the store (`sources.config.access_store`) changes, last.+ *+ * - database → git (a repo-less source gained a repo): write+ * `.gbrain/access.approved` (the latest approved revision) and `.gbrain/access.yml`+ * (the desired revision) through the git door, then switch the store; the+ * next sync reads the same rules back, so nothing changes.+ * - git → database (the repo is gone or this host cannot see it): switch the+ * store; the database copy already holds the effective applied rulebook+ * (automatic narrowings and pending coverage included) and the held+ * widenings stay held.+ *+ * Each phase is journaled (access_policy_migrations) under a durable id, so an+ * interrupted migrate resumes where it stopped and a repeat is idempotent.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import type { FolderRule } from './folder-rules.ts';+import { appliedRules, ensurePolicyState, getRevision, listRevisions, readAccessStore, writeAccessStore, type AccessStore } from './policy.ts';+import { APPROVED_FILE, commitPolicyFile, isGitWorkTree, POLICY_FILE, sourcePolicyRoot, syncGitPolicy } from './policy-git.ts';+import { serializePolicyYaml } from './folder-rules.ts';++export interface MigratePreview {+ source_id: string;+ from: AccessStore | null;+ to: AccessStore;+ root: string | null;+ desired: FolderRule[];+ approved: FolderRule[];+ resume: { id: string; phase: string } | null;+}++async function unfinished(engine: BrainEngine, sourceId: string): Promise<{ id: string; phase: string; direction: string; receipts: Record<string, unknown> } | null> {+ const [row] = await engine.executeRaw<{ id: string; phase: string; direction: string; receipts: unknown }>(+ `SELECT id, phase, direction, receipts FROM access_policy_migrations WHERE source_id = $1 AND phase <> 'switched' ORDER BY created_at DESC LIMIT 1`, [sourceId]);+ if (!row) return null;+ return { ...row, receipts: (typeof row.receipts === 'string' ? JSON.parse(row.receipts) : row.receipts) as Record<string, unknown> ?? {} };+}++export async function previewMigrate(engine: BrainEngine, sourceId: string): Promise<MigratePreview> {+ const from = await readAccessStore(engine, sourceId);+ const root = await sourcePolicyRoot(engine, sourceId);+ const gitRoot = root && isGitWorkTree(root) ? root : null;+ const pending = await unfinished(engine, sourceId).catch(() => null);+ const to: AccessStore = pending ? (pending.direction === 'to_git' ? 'git' : 'database') : from === 'git' ? 'database' : 'git';+ if (to === 'git' && !gitRoot) {+ throw opError('invalid_params', `Source ${sourceId} has no git work tree at its root (${root ?? 'no local path'}), so its folder rules stay in the database store.`,+ 'Initialize or clone the repository at the source root first, then run gbrain access rule migrate again.');+ }+ const applied = await appliedRules(engine, sourceId);+ const desired = (await getRevision(engine, sourceId))?.rules ?? applied;+ const approved = (await listRevisions(engine, sourceId, 500)).find(r => r.approved_at)?.rules ?? applied;+ return { source_id: sourceId, from, to, root: gitRoot, desired, approved, resume: pending ? { id: pending.id, phase: pending.phase } : null };+}++export async function migrateAccessStore(engine: BrainEngine, sourceId: string): Promise<{ id: string; from: AccessStore | null; to: AccessStore; phase: string; receipts: Record<string, unknown> }> {+ const p = await previewMigrate(engine, sourceId);+ await ensurePolicyState(engine, sourceId);+ let job = await unfinished(engine, sourceId);+ if (!job) {+ const id = `mig_${randomUUID()}`;+ await engine.executeRaw(`INSERT INTO access_policy_migrations (id, source_id, direction, phase) VALUES ($1, $2, $3, 'started')`, [id, sourceId, p.to === 'git' ? 'to_git' : 'to_database']);+ job = { id, phase: 'started', direction: p.to === 'git' ? 'to_git' : 'to_database', receipts: {} };+ }+ const receipts = { ...job.receipts };+ const record = async (phase: string) => {+ await engine.executeRaw('UPDATE access_policy_migrations SET phase = $2, receipts = $3::text::jsonb, updated_at = now() WHERE id = $1', [job!.id, phase, JSON.stringify(receipts)]);+ job!.phase = phase;+ };+ if (p.to === 'git') {+ if (job.phase === 'started') {+ receipts.approved = await commitPolicyFile(p.root!, APPROVED_FILE, () => serializePolicyYaml(p.approved, 'The folder rules an operator approved with gbrain access apply. Written by gbrain; do not edit.'), `access: move folder rules of ${sourceId} to git (approved)`);+ await record('exported');+ }+ if (job.phase === 'exported') {+ receipts.desired = await commitPolicyFile(p.root!, POLICY_FILE, () => serializePolicyYaml(p.desired, 'Folder read rules for this source (gbrain access rule add|rm). Narrowing changes apply at the next sync;\nwidening changes wait for gbrain access apply --source <id> on the brain host.'), `access: move folder rules of ${sourceId} to git`);+ await record('committed');+ }+ } else if (job.phase === 'started') {+ await record('committed');+ }+ await engine.transaction(async tx => {+ await tx.executeRaw('SELECT 1 FROM access_policy_state WHERE source_id = $1 FOR UPDATE', [sourceId]);+ await writeAccessStore(tx, sourceId, p.to);+ await tx.executeRaw(`UPDATE access_policy_migrations SET phase = 'switched', receipts = $2::text::jsonb, updated_at = now() WHERE id = $1`, [job!.id, JSON.stringify(receipts)]);+ });+ job.phase = 'switched';+ if (p.to === 'git') receipts.sync = (await syncGitPolicy(engine, sourceId, p.root!)).state;+ return { id: job.id, from: p.from, to: p.to, phase: job.phase, receipts };+}diff --git a/src/core/access/policy-notice.ts b/src/core/access/policy-notice.tsnew file mode 100644index 0000000000..bc0168fe32--- /dev/null+++ b/src/core/access/policy-notice.ts@@ -0,0 +1,42 @@+/**+ * GBRA-218 (A2): `access_policy_pending`, the notice on a remote read while some+ * source this connection reads has folder prefixes that read as nobody (a+ * narrowing still being stamped, or a policy file that does not validate).+ * The empty or short answer is then not proof the brain holds nothing there.+ * Names only sources inside the caller's read scope; the first step is to wait+ * and check again, then the brain host finishes or fixes it.+ */+import type { Notice } from '../agent-output.ts';+import type { OperationContext } from '../ops/contract.ts';+import { federatedSearchScope } from '../ops/context.ts';+import { hostFix } from '../ops/op-fix.ts';+import { currentCallerAccess } from '../search/private-visibility.ts';++const READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages', 'get_page', 'fetch', 'get_links', 'get_backlinks', 'traverse_graph', 'resolve_slugs', 'get_timeline']);++export function accessPolicyNotices(op: string, ctx: OperationContext): Notice[] {+ if (ctx.remote === false || !READ_OPS.has(op)) return [];+ const coverage = currentCallerAccess().folderCoverage;+ if (!coverage.length) return [];+ try {+ const scope = federatedSearchScope(ctx);+ const readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : []);+ const sources = [...new Set(coverage.map(c => c.source_id))].filter(s => readable.includes(s)).sort();+ if (!sources.length) return [];+ const source = sources[0]!;+ return [{+ code: 'access_policy_pending',+ kind: 'degraded',+ why: `Folder rules of source ${sources.join(', ')} are being applied (or its policy file does not validate), so pages under the affected folders read as nobody for now. `+ + 'A missing page there is not proof the brain has nothing on it. Retry in a minute; if it stays this way, the brain host finishes it (command in fix).',+ fix: {+ argv: ['gbrain', 'access', 'rule', 'status', '--source', source, '--json'], consent: [], actor: 'provider', requires_exclusive: false,+ why: 'The apply finishes on its own; check again shortly.',+ then: hostFix(ctx, ['gbrain', 'access', 'resume', '--source', source],+ `Finishes an interrupted narrowing (database store); on a git store run gbrain sync --source ${source} --no-pull, and for an invalid file fix .gbrain/access.yml.`),+ },+ }];+ } catch {+ return [];+ }+}diff --git a/src/core/access/policy-transfer.ts b/src/core/access/policy-transfer.tsnew file mode 100644index 0000000000..348f37ca58--- /dev/null+++ b/src/core/access/policy-transfer.ts@@ -0,0 +1,105 @@+/**+ * GBRA-218 (A2) folder rules across export and import (plan §15 "Backups and+ * moves", §16 "Import barrier").+ *+ * Export writes each source's applied rulebook (never a held widening): a+ * one-source export as .gbrain/access.yml plus .gbrain/access.approved, the+ * files a git-backed source keeps; an export of several sources as+ * .gbrain/access/<source>.yml, including sources with no exported page. A+ * source whose committed policy file is invalid has prefixes reading as+ * nobody that no rulebook can express, so its export refuses instead of+ * carrying a wider rulebook.+ *+ * Import installs the chosen rulebook before it publishes any page, through+ * proposeRevision: narrowing applies at once (with durable pending coverage+ * until restamped), widening is held for gbrain access apply. Source-qualified+ * files are mapped explicitly with --access-policy <exported-source> (a lone+ * one is taken as is); with several and no choice, the import refuses before+ * writing anything.+ */+import { existsSync, readdirSync, readFileSync } from 'fs';+import { join } from 'path';+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { parsePolicyYaml, serializePolicyYaml, type FolderRule } from './folder-rules.ts';+import { appliedRules, coverageRows, proposeRevision, readAccessStore, type ProposalResult } from './policy.ts';+import { APPROVED_FILE, POLICY_FILE, isGitWorkTree, sourcePolicyRoot } from './policy-git.ts';++const EXPORT_HEADER = 'Folder rules exported by gbrain export (the applied rulebook).';+export const SOURCE_POLICY_DIR = '.gbrain/access';++/** The policy files an export carries for one source, or for every source with folder rules when sourceId is null. */+export async function exportPolicyFiles(engine: BrainEngine, sourceId: string | null): Promise<Array<{ path: string; content: string }>> {+ const sources = sourceId ? [sourceId]+ : (await engine.executeRaw<{ source_id: string }>('SELECT source_id FROM access_policy_state ORDER BY source_id')).map(r => r.source_id);+ const files: Array<{ path: string; content: string }> = [];+ for (const source of sources) {+ const invalid = (await coverageRows(engine, source)).filter(c => c.reason === 'invalid');+ if (invalid.length) {+ throw opError('access_policy_invalid', `Source ${source}'s committed folder-rule file does not validate, so ${invalid.map(c => c.prefix || 'the whole source').join(', ')} read as nobody and no exported rulebook can carry that; nothing was exported.`,+ `See the problems with gbrain access rule list --source ${source}, fix .gbrain/access.yml, commit it and sync, then export again; other sources export one at a time with gbrain export --source.`);+ }+ const rules = await appliedRules(engine, source);+ if (!rules.length) continue;+ const text = serializePolicyYaml(rules, EXPORT_HEADER);+ if (sourceId) files.push({ path: POLICY_FILE, content: text }, { path: APPROVED_FILE, content: text });+ else files.push({ path: `${SOURCE_POLICY_DIR}/${source}.yml`, content: text });+ }+ return files;+}++/** The rulebook an import tree carries for its destination, or null when it carries none (or the caller chose none). */+export function importPolicyChoice(dir: string, choice: string | undefined): { file: string; rules: FolderRule[] } | null {+ const single = join(dir, POLICY_FILE);+ const qualifiedDir = join(dir, SOURCE_POLICY_DIR);+ const qualified = existsSync(qualifiedDir) ? readdirSync(qualifiedDir).filter(f => f.endsWith('.yml')).map(f => f.slice(0, -4)).sort() : [];+ if (choice === 'none') return null;+ let file: string;+ if (choice !== undefined) {+ if (!qualified.includes(choice)) {+ throw opError('access_policy_invalid', `The import tree has no folder-rule file for source "${choice}" (${qualified.length ? `it has ${qualified.join(', ')}` : 'it has no source-qualified rule file'}); nothing was imported.`,+ `Pass --access-policy with one of the listed sources, or --access-policy none to import without folder rules.`);+ }+ file = join(qualifiedDir, choice + '.yml');+ } else if (existsSync(single)) {+ file = single;+ } else if (qualified.length === 1) {+ file = join(qualifiedDir, qualified[0] + '.yml');+ } else if (qualified.length) {+ throw opError('access_policy_invalid', `The import tree carries folder rules for several sources (${qualified.join(', ')}) and none was chosen for the destination; nothing was imported.`,+ `Run the import again with --access-policy ${qualified[0]} (or another of ${qualified.join(', ')}) naming the exported source whose rules this destination takes, or --access-policy none to import without folder rules.`);+ } else return null;+ const parsed = parsePolicyYaml(readFileSync(file, 'utf8'));+ if (!parsed.ok) {+ throw opError('access_policy_invalid', `${file} does not validate: ${parsed.problems.map(p => `${p.line ? `line ${p.line}: ` : ''}${p.message}`).join('; ')}; nothing was imported.`,+ 'Fix the file and run the import again.');+ }+ return { file, rules: parsed.rules };+}++/** gbrain import's barrier: reads --access-policy from the import argv, installs the rulebook and reports it; a refusal is printed before it is rethrown. */+export async function importPolicyBarrier(engine: BrainEngine, sourceId: string, dir: string, args: readonly string[], log: (line: string) => void): Promise<void> {+ const flag = args.indexOf('--access-policy');+ try {+ const policy = await installImportedPolicy(engine, sourceId, dir, flag === -1 ? undefined : args[flag + 1]);+ if (!policy) return;+ log(`Folder rules from ${policy.file}: revision ${policy.revision} ${policy.state}${policy.held.length ? ` (widening held: preview with gbrain access apply --source ${sourceId})` : ''}`);+ } catch (error) {+ const e = error as Error & { suggestion?: string };+ console.error(`${e.message}${e.suggestion ? ` ${e.suggestion}` : ''}`);+ throw error;+ }+}++/** The import barrier: installs the tree's rulebook for the destination before any page is published. */+export async function installImportedPolicy(engine: BrainEngine, sourceId: string, dir: string, choice: string | undefined): Promise<(ProposalResult & { file: string }) | null> {+ const picked = importPolicyChoice(dir, choice);+ if (!picked) return null;+ let store = await readAccessStore(engine, sourceId);+ if (!store) {+ const root = await sourcePolicyRoot(engine, sourceId);+ store = root && isGitWorkTree(root) ? 'git' : 'database';+ }+ const result = await proposeRevision(engine, sourceId, picked.rules, { origin: 'import', store });+ return { ...result, file: picked.file };+}diff --git a/src/core/access/policy.ts b/src/core/access/policy.tsnew file mode 100644index 0000000000..1ef4642236--- /dev/null+++ b/src/core/access/policy.ts@@ -0,0 +1,430 @@+/**+ * GBRA-218 (PR A2): the folder-rule policy lifecycle, one engine for both stores.+ *+ * Every source with a policy has one access_policy_state row (its lock), an+ * append-only access_policy_revisions log of desired rulebooks, and the+ * applied rulebook in access_rules, which page writes stamp folder_rule_ids+ * from (migration v275). The store (`sources.config.access_store`, git or+ * database) only decides where desired revisions come from: `gbrain access rule`+ * on a database store, the committed `.gbrain/access.yml` on a git store+ * (policy-git.ts). From there the lifecycle is the same:+ *+ * - proposeRevision records the desired rulebook and installs the narrowing+ * part of the change at once (classifyRulebook): new prefixes are marked+ * pending (they read as nobody), pages are restamped in batches, a final+ * pass under the source lock restamps anything written meanwhile, and only+ * then does the pending coverage go and the revision count as applied.+ * - the widening part is held: the applied rules stay until+ * applyApproved (`gbrain access apply --yes --expect <plan_hash>`) installs a+ * previewed revision; a plan hash over the desired and applied digests+ * refuses `preview_changed` when either moved.+ * - resume finishes an interrupted narrowing; it is idempotent and only ever+ * restamps toward the applied rulebook.+ */+import { createHash, randomUUID } from 'node:crypto';+import { userInfo } from 'node:os';+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { classifyRulebook, folderRulesAllow, rulebookDigest, rulesFromJson, sortRules, type Classification, type FolderRule, type RuleChange } from './folder-rules.ts';+import { identityFor } from './principals.ts';+import { listMembers } from './members.ts';++export type AccessStore = 'git' | 'database';+type Exec = Pick<BrainEngine, 'executeRaw'>;++export const RESTAMP_BATCH = 2000;++/** Test seam: runs after a narrowing is installed (rules and pending coverage committed) and before its restamp. */+export const policySeams: { afterInstall?: (sourceId: string) => Promise<void> | void } = {};++export interface RevisionRow {+ revision: number;+ rules: FolderRule[];+ digest: string;+ change_kind: Classification['kind'];+ origin: string;+ operation_id: string | null;+ proposed_by: string | null;+ approved_by: string | null;+ created_at: string;+ applied_at: string | null;+ approved_at: string | null;+}++export interface CoverageRow { prefix: string; reason: 'pending' | 'invalid'; revision: number | null; detail: unknown }++export type ProposalState = 'applied' | 'pending' | 'recorded' | 'unchanged';++export interface ProposalResult {+ source_id: string;+ operation_id: string | null;+ revision: number | null;+ /** applied: everything in force; recorded: the narrowing part is in force and a widening waits for gbrain access apply; pending: a narrowing is still being stamped (gbrain access resume finishes it); unchanged: the desired rulebook already matched. */+ state: ProposalState;+ change_kind: Classification['kind'];+ changes: RuleChange[];+ held: RuleChange[];+ pages_restamped: number;+ reconciled?: boolean;+}++/** The local operator recorded on revisions this process writes. */+export function localActor(): string {+ try { return `local:${userInfo().username}`; } catch { return 'local'; }+}++function iso(v: unknown): string | null {+ if (v === null || v === undefined) return null;+ return v instanceof Date ? v.toISOString() : String(v);+}++function toRevision(row: Record<string, unknown>): RevisionRow {+ return {+ revision: Number(row.revision), rules: rulesFromJson(row.rules), digest: String(row.digest),+ change_kind: row.change_kind as RevisionRow['change_kind'], origin: String(row.origin),+ operation_id: (row.operation_id as string | null) ?? null, proposed_by: (row.proposed_by as string | null) ?? null,+ approved_by: (row.approved_by as string | null) ?? null, created_at: iso(row.created_at)!, applied_at: iso(row.applied_at), approved_at: iso(row.approved_at),+ };+}++/** The persisted store of a source, or null when it has never had a rule. Refuses an unknown source. */+export async function readAccessStore(engine: Exec, sourceId: string): Promise<AccessStore | null> {+ const [row] = await engine.executeRaw<{ store: string | null }>(`SELECT config->>'access_store' AS store FROM sources WHERE id = $1`, [sourceId]);+ if (!row) throw opError('unknown_source', `No source "${sourceId}".`, 'List sources with gbrain sources list.');+ return row.store === 'git' || row.store === 'database' ? row.store : null;+}++/** Persists the store (set with the first rule, changed only by gbrain access rule migrate). */+export async function writeAccessStore(engine: Exec, sourceId: string, store: AccessStore): Promise<void> {+ await engine.executeRaw(`UPDATE sources SET config = jsonb_set(COALESCE(config, '{}'::jsonb), '{access_store}', to_jsonb($2::text)) WHERE id = $1`, [sourceId, store]);+}++/** Creates the source's lock row in its own committed statement, so concurrent page writes start taking it before any rule exists. */+export async function ensurePolicyState(engine: Exec, sourceId: string): Promise<void> {+ await engine.executeRaw('INSERT INTO access_policy_state (source_id) VALUES ($1) ON CONFLICT (source_id) DO NOTHING', [sourceId]);+}++async function lockSource(tx: Exec, sourceId: string): Promise<void> {+ await tx.executeRaw('SELECT 1 FROM access_policy_state WHERE source_id = $1 FOR UPDATE', [sourceId]);+}++export async function appliedRules(engine: Exec, sourceId: string): Promise<FolderRule[]> {+ const rows = await engine.executeRaw<{ rule_id: string; prefix: string; readable_by: string[] }>(+ 'SELECT rule_id, prefix, readable_by FROM access_rules WHERE source_id = $1 ORDER BY rule_id', [sourceId]);+ return sortRules(rows.map(r => ({ id: r.rule_id, prefix: r.prefix, readable_by: [...(r.readable_by ?? [])] })));+}++export async function listRevisions(engine: Exec, sourceId: string, limit = 50): Promise<RevisionRow[]> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT * FROM access_policy_revisions WHERE source_id = $1 ORDER BY revision DESC LIMIT $2', [sourceId, limit]);+ return rows.map(toRevision);+}++export async function getRevision(engine: Exec, sourceId: string, revision?: number): Promise<RevisionRow | null> {+ const rows = revision === undefined+ ? await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_policy_revisions WHERE source_id = $1 ORDER BY revision DESC LIMIT 1', [sourceId])+ : await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_policy_revisions WHERE source_id = $1 AND revision = $2', [sourceId, revision]);+ return rows[0] ? toRevision(rows[0]) : null;+}++export async function coverageRows(engine: Exec, sourceId: string): Promise<CoverageRow[]> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ 'SELECT prefix, reason, revision, detail FROM access_pending_coverage WHERE source_id = $1 ORDER BY reason, prefix', [sourceId]);+ return rows.map(r => ({ prefix: String(r.prefix), reason: r.reason as CoverageRow['reason'], revision: r.revision === null ? null : Number(r.revision),+ detail: typeof r.detail === 'string' ? JSON.parse(r.detail) : r.detail ?? null }));+}++const key = (r: FolderRule) => `${r.id}\u0000${r.prefix}`;++/**+ * Makes `target` the applied rulebook inside the caller's locked transaction. Rules whose (id, prefix) pair is new get+ * pending coverage until the restamp finishes. Returns whether pages need restamping.+ */+async function installRulebook(tx: Exec, sourceId: string, target: readonly FolderRule[], revision: number, actor: string): Promise<boolean> {+ const current = await appliedRules(tx, sourceId);+ const before = new Map(current.map(r => [r.id, r]));+ const after = new Map(target.map(r => [r.id, r]));+ const currentKeys = new Set(current.map(key));+ const targetKeys = new Set(target.map(key));+ for (const r of current) {+ const next = after.get(r.id);+ if (!next || next.prefix !== r.prefix || next.readable_by.join('\u0000') !== r.readable_by.join('\u0000')) {+ await tx.executeRaw('DELETE FROM access_rules WHERE source_id = $1 AND rule_id = $2', [sourceId, r.id]);+ }+ }+ for (const r of target) {+ const prior = before.get(r.id);+ if (prior && prior.prefix === r.prefix && prior.readable_by.join('\u0000') === r.readable_by.join('\u0000')) continue;+ await tx.executeRaw('INSERT INTO access_rules (source_id, rule_id, prefix, readable_by, revision, created_by) VALUES ($1, $2, $3, $4::text[], $5, $6)',+ [sourceId, r.id, r.prefix, r.readable_by, revision, actor]);+ }+ const added = target.filter(r => !currentKeys.has(key(r)));+ for (const r of added) {+ await tx.executeRaw(`INSERT INTO access_pending_coverage (source_id, prefix, reason, revision) VALUES ($1, $2, 'pending', $3)+ ON CONFLICT (source_id, prefix, reason) DO UPDATE SET revision = EXCLUDED.revision`, [sourceId, r.prefix, revision]);+ }+ return added.length > 0 || current.some(r => !targetKeys.has(key(r)));+}++export interface RestampProgress { pages_scanned: number; pages_restamped: number }++/**+ * Restamps folder_rule_ids toward the applied rulebook in id-ordered windows (each its own statement, so page writes+ * are never blocked for long), then finishes under the source lock: one more pass over the whole source catches pages+ * written meanwhile, the pending coverage goes, and pending revisions count as applied, atomically.+ */+export async function restampSource(engine: BrainEngine, sourceId: string, opts: { batch?: number; onProgress?: (p: RestampProgress) => void } = {}): Promise<RestampProgress> {+ const batch = opts.batch ?? RESTAMP_BATCH;+ const progress: RestampProgress = { pages_scanned: 0, pages_restamped: 0 };+ let after = 0;+ for (;;) {+ const [row] = await engine.executeRaw<{ last: number | null; scanned: number; changed: number }>(+ `WITH w AS (SELECT id FROM pages WHERE source_id = $1 AND id > $2 ORDER BY id LIMIT $3),+ u AS (UPDATE pages p SET folder_rule_ids = gbrain_access_folder_rules(p.source_id, p.slug) FROM w+ WHERE p.id = w.id AND p.folder_rule_ids IS DISTINCT FROM gbrain_access_folder_rules(p.source_id, p.slug) RETURNING p.id)+ SELECT (SELECT max(id) FROM w) AS last, (SELECT count(*) FROM w)::int AS scanned, (SELECT count(*) FROM u)::int AS changed`,+ [sourceId, after, batch]);+ if (!row || row.last === null || row.last === undefined) break;+ after = Number(row.last);+ progress.pages_scanned += Number(row.scanned);+ progress.pages_restamped += Number(row.changed);+ opts.onProgress?.({ ...progress });+ }+ await engine.transaction(async tx => {+ await lockSource(tx, sourceId);+ const changed = await tx.executeRaw<{ id: number }>(+ `UPDATE pages SET folder_rule_ids = gbrain_access_folder_rules(source_id, slug)+ WHERE source_id = $1 AND folder_rule_ids IS DISTINCT FROM gbrain_access_folder_rules(source_id, slug) RETURNING id`, [sourceId]);+ progress.pages_restamped += changed.length;+ await tx.executeRaw(`DELETE FROM access_pending_coverage WHERE source_id = $1 AND reason = 'pending'`, [sourceId]);+ await tx.executeRaw('UPDATE access_policy_revisions SET applied_at = now() WHERE source_id = $1 AND applied_at IS NULL', [sourceId]);+ });+ return progress;+}++export interface ProposeMeta {+ origin: 'cli' | 'git' | 'git-approved' | 'import' | 'revert' | 'migrate';+ proposedBy?: string;+ /** Idempotency key: a retry with the same id returns the recorded revision instead of writing a second one. */+ operationId?: string;+ /** The desired revision the caller previewed; a different one refuses preview_changed. */+ expectDesired?: number;+ /** Persist this store when the source has none (the first rule). */+ store?: AccessStore;+ /** Record the revision as approved whatever it classifies as (a git source's committed access.approved on a rebuild). */+ approved?: boolean;+ onProgress?: (p: RestampProgress) => void;+}++/** Records a desired rulebook and installs its narrowing part (see the module comment). */+export async function proposeRevision(engine: BrainEngine, sourceId: string, desired: readonly FolderRule[], meta: ProposeMeta): Promise<ProposalResult> {+ await readAccessStore(engine, sourceId);+ await ensurePolicyState(engine, sourceId);+ const rules = sortRules(desired);+ const digest = rulebookDigest(rules);+ const actor = meta.proposedBy ?? localActor();+ const step = await engine.transaction(async tx => {+ await lockSource(tx, sourceId);+ if (meta.operationId) {+ const [prior] = await tx.executeRaw<Record<string, unknown>>('SELECT * FROM access_policy_revisions WHERE operation_id = $1', [meta.operationId]);+ if (prior) return { reconciled: toRevision(prior) };+ }+ const latest = await getRevision(tx as BrainEngine, sourceId);+ if (meta.expectDesired !== undefined && (latest?.revision ?? 0) !== meta.expectDesired) {+ throw opError('preview_changed', `Source ${sourceId}'s folder rules changed since the preview (previewed revision ${meta.expectDesired}, now ${latest?.revision ?? 0}); nothing was written.`,+ `Preview again (gbrain access rule list --source ${sourceId}) and rerun with the new --expect value.`);+ }+ const current = await appliedRules(tx, sourceId);+ const cls = meta.approved ? { ...classifyRulebook(current, rules), target: rules, held: [] } : classifyRulebook(current, rules);+ if (meta.store && !(await readAccessStore(tx, sourceId))) await writeAccessStore(tx, sourceId, meta.store);+ if (latest && latest.digest === digest && !meta.approved) {+ const needs = rulebookDigest(cls.target) !== rulebookDigest(current) && await installRulebook(tx, sourceId, cls.target, latest.revision, actor);+ return { unchanged: latest, cls, needs };+ }+ const revision = (latest?.revision ?? 0) + 1;+ const approved = cls.held.length === 0;+ await tx.executeRaw(`INSERT INTO access_policy_revisions (source_id, revision, rules, digest, change_kind, origin, operation_id, proposed_by, approved_by, approved_at)+ VALUES ($1, $2, $3::text::jsonb, $4, $5, $6, $7, $8, $9, CASE WHEN $10::boolean THEN now() END)`,+ [sourceId, revision, JSON.stringify(rules), digest, cls.kind, meta.origin, meta.operationId ?? null, actor,+ approved ? (meta.approved ? actor : 'auto:narrowing') : null, approved]);+ const needs = await installRulebook(tx, sourceId, cls.target, revision, actor);+ if (!needs) await tx.executeRaw('UPDATE access_policy_revisions SET applied_at = now() WHERE source_id = $1 AND applied_at IS NULL', [sourceId]);+ return { revision, cls, needs };+ });+ if ('reconciled' in step && step.reconciled) {+ const rev = step.reconciled;+ const status = await policyStatus(engine, sourceId);+ return { source_id: sourceId, operation_id: rev.operation_id, revision: rev.revision, reconciled: true,+ state: status.pending.length ? 'pending' : status.held.length && status.desired?.revision === rev.revision ? 'recorded' : 'applied',+ change_kind: rev.change_kind, changes: [], held: status.desired?.revision === rev.revision ? status.held : [], pages_restamped: 0 };+ }+ if ('unchanged' in step && step.unchanged) {+ const resume = step.needs || (await coverageRows(engine, sourceId)).some(c => c.reason === 'pending');+ const restamped = resume ? (await restampSource(engine, sourceId, { onProgress: meta.onProgress })).pages_restamped : 0;+ return { source_id: sourceId, operation_id: step.unchanged.operation_id, revision: step.unchanged.revision, state: step.cls.held.length ? 'recorded' : 'unchanged',+ change_kind: 'unchanged', changes: [], held: step.cls.held, pages_restamped: restamped };+ }+ const { revision, cls, needs } = step as { revision: number; cls: Classification; needs: boolean };+ if (needs) await policySeams.afterInstall?.(sourceId);+ const restamp = needs ? await restampSource(engine, sourceId, { onProgress: meta.onProgress }) : { pages_restamped: 0 };+ return { source_id: sourceId, operation_id: meta.operationId ?? null, revision, state: cls.held.length ? 'recorded' : 'applied',+ change_kind: cls.kind, changes: cls.changes, held: cls.held, pages_restamped: restamp.pages_restamped };+}++/** Finishes an interrupted narrowing (pending coverage or stamps that drifted from the applied rulebook). Idempotent. */+export async function resumePolicy(engine: BrainEngine, sourceId: string, onProgress?: (p: RestampProgress) => void): Promise<RestampProgress & { pending_before: string[] }> {+ await readAccessStore(engine, sourceId);+ const pending = (await coverageRows(engine, sourceId)).filter(c => c.reason === 'pending').map(c => c.prefix);+ const [state] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_policy_state WHERE source_id = $1', [sourceId]);+ if (!state?.n) return { pages_scanned: 0, pages_restamped: 0, pending_before: [] };+ const progress = await restampSource(engine, sourceId, { onProgress });+ return { ...progress, pending_before: pending };+}++export interface WideningImpact {+ change: RuleChange;+ pages: number;+ sample: string[];+ /** Members who read at least one page after the change that they cannot read now; 'every_source_reader' when unbound callers gain too. */+ gains: string[] | 'every_source_reader';+}++export interface ApplyPreview {+ source_id: string;+ store: AccessStore | null;+ applied_digest: string;+ desired: { revision: number; digest: string; proposed_by: string | null; created_at: string; origin: string } | null;+ proposals: Array<{ revision: number; change_kind: string; proposed_by: string | null; created_at: string }>;+ widening: WideningImpact[];+ plan_hash: string | null;+}++function planHash(sourceId: string, revision: number, desiredDigest: string, appliedDigest: string): string {+ return createHash('sha256').update(JSON.stringify({ sourceId, revision, desiredDigest, appliedDigest })).digest('hex').slice(0, 16);+}++/** What `gbrain access apply` would install: each held widening with the pages and members gaining access, and the plan hash binding it. */+export async function previewApply(engine: BrainEngine, sourceId: string, revision?: number): Promise<ApplyPreview> {+ const store = await readAccessStore(engine, sourceId);+ const current = await appliedRules(engine, sourceId);+ const appliedDigest = rulebookDigest(current);+ const desired = await getRevision(engine, sourceId, revision);+ if (revision !== undefined && !desired) throw opError('not_found', `Source ${sourceId} has no folder-rule revision ${revision}.`, `List revisions with gbrain access rule history --source ${sourceId}.`);+ const proposals = (await listRevisions(engine, sourceId, 200)).filter(r => !r.approved_at).reverse()+ .map(r => ({ revision: r.revision, change_kind: r.change_kind, proposed_by: r.proposed_by, created_at: r.created_at }));+ const base = { source_id: sourceId, store, applied_digest: appliedDigest, proposals };+ if (!desired) return { ...base, desired: null, widening: [], plan_hash: null };+ const cls = classifyRulebook(current, desired.rules);+ const desiredView = { revision: desired.revision, digest: desired.digest, proposed_by: desired.proposed_by, created_at: desired.created_at, origin: desired.origin };+ if (!cls.held.length && rulebookDigest(cls.target) === appliedDigest) return { ...base, desired: desiredView, widening: [], plan_hash: null };+ const members = (await listMembers(engine)).filter(m => m.status === 'enabled');+ const widening: WideningImpact[] = [];+ for (const change of cls.held) {+ const old = current.find(r => r.id === change.rule);+ const prefixes = [...new Set([old?.prefix, change.prefix].filter((p): p is string => !!p))];+ const slugs = (await engine.executeRaw<{ slug: string }>(+ 'SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND EXISTS (SELECT 1 FROM unnest($2::text[]) AS pfx WHERE starts_with(slug, pfx)) ORDER BY slug',+ [sourceId, prefixes])).map(r => r.slug);+ const gaining = (identity: string[]) => slugs.filter(s => !folderRulesAllow(s, current, identity) && folderRulesAllow(s, desired.rules, identity));+ const unbound = gaining([]);+ const pages = new Set(unbound);+ const gainers: string[] = [];+ for (const m of members) {+ const g = gaining(identityFor(m.id, m.groups));+ if (g.length) gainers.push(m.id);+ for (const s of g) pages.add(s);+ }+ widening.push({ change, pages: pages.size, sample: [...pages].sort().slice(0, 20), gains: unbound.length ? 'every_source_reader' : gainers });+ }+ return { ...base, desired: desiredView, widening, plan_hash: planHash(sourceId, desired.revision, desired.digest, appliedDigest) };+}++/** Installs a previewed revision in full (its widening included) when `expect` still matches its plan hash. */+export async function applyApproved(engine: BrainEngine, sourceId: string, opts: { revision?: number; expect: string; approvedBy?: string; onProgress?: (p: RestampProgress) => void }): Promise<ProposalResult & { plan_hash: string }> {+ await readAccessStore(engine, sourceId);+ await ensurePolicyState(engine, sourceId);+ const actor = opts.approvedBy ?? localActor();+ const installed = await engine.transaction(async tx => {+ await lockSource(tx, sourceId);+ const current = await appliedRules(tx, sourceId);+ const desired = await getRevision(tx as BrainEngine, sourceId, opts.revision);+ const hash = desired ? planHash(sourceId, desired.revision, desired.digest, rulebookDigest(current)) : null;+ if (!desired || hash !== opts.expect) {+ throw opError('preview_changed', `Source ${sourceId}'s folder rules changed since the preview (approved plan ${opts.expect}, current plan ${hash ?? 'none'}); nothing was applied.`,+ `Preview again with gbrain access apply --source ${sourceId}${opts.revision ? ` --revision ${opts.revision}` : ''} and approve the new plan_hash.`);+ }+ const cls = classifyRulebook(current, desired.rules);+ const needs = await installRulebook(tx, sourceId, desired.rules, desired.revision, actor);+ await tx.executeRaw('UPDATE access_policy_revisions SET approved_by = $3, approved_at = now() WHERE source_id = $1 AND revision = $2', [sourceId, desired.revision, actor]);+ if (!needs) await tx.executeRaw('UPDATE access_policy_revisions SET applied_at = now() WHERE source_id = $1 AND applied_at IS NULL AND revision <= $2', [sourceId, desired.revision]);+ return { desired, cls, needs, hash: hash! };+ });+ const restamp = installed.needs ? await restampSource(engine, sourceId, { onProgress: opts.onProgress }) : { pages_restamped: 0 };+ const latest = await getRevision(engine, sourceId);+ let held: RuleChange[] = [];+ if (latest && latest.revision > installed.desired.revision) {+ held = (await proposeRevision(engine, sourceId, latest.rules, { origin: latest.origin as ProposeMeta['origin'], proposedBy: actor, onProgress: opts.onProgress })).held;+ }+ return { source_id: sourceId, operation_id: installed.desired.operation_id, revision: installed.desired.revision, state: held.length ? 'recorded' : 'applied',+ change_kind: installed.cls.kind, changes: installed.cls.changes, held, pages_restamped: restamp.pages_restamped, plan_hash: installed.hash };+}++export interface PolicyStatus {+ source_id: string;+ store: AccessStore | null;+ rules: FolderRule[];+ applied_digest: string;+ desired: RevisionRow | null;+ applied_revision: number | null;+ approved_revision: number | null;+ held: RuleChange[];+ pending: CoverageRow[];+ invalid: CoverageRow[];+ operation?: { operation_id: string; revision: number | null; state: ProposalState | 'not_found' };+}++/** Where a source's folder policy stands: store, applied rules, desired, applied and approved revisions, held and pending work. */+export async function policyStatus(engine: BrainEngine, sourceId: string, operationId?: string): Promise<PolicyStatus> {+ const store = await readAccessStore(engine, sourceId);+ const rules = await appliedRules(engine, sourceId);+ const desired = await getRevision(engine, sourceId);+ const [marks] = await engine.executeRaw<{ applied: number | null; approved: number | null }>(+ 'SELECT max(revision) FILTER (WHERE applied_at IS NOT NULL) AS applied, max(revision) FILTER (WHERE approved_at IS NOT NULL) AS approved FROM access_policy_revisions WHERE source_id = $1', [sourceId]);+ const coverage = await coverageRows(engine, sourceId);+ const held = desired ? classifyRulebook(rules, desired.rules).held : [];+ const status: PolicyStatus = {+ source_id: sourceId, store, rules, applied_digest: rulebookDigest(rules), desired,+ applied_revision: marks?.applied === null || marks?.applied === undefined ? null : Number(marks.applied),+ approved_revision: marks?.approved === null || marks?.approved === undefined ? null : Number(marks.approved),+ held, pending: coverage.filter(c => c.reason === 'pending'), invalid: coverage.filter(c => c.reason === 'invalid'),+ };+ if (operationId !== undefined) {+ const [row] = await engine.executeRaw<{ revision: number; applied_at: unknown; approved_at: unknown }>(+ 'SELECT revision, applied_at, approved_at FROM access_policy_revisions WHERE source_id = $1 AND operation_id = $2', [sourceId, operationId]);+ status.operation = !row ? { operation_id: operationId, revision: null, state: 'not_found' }+ : { operation_id: operationId, revision: Number(row.revision),+ state: !row.applied_at ? 'pending' : held.length && desired?.revision === Number(row.revision) ? 'recorded' : 'applied' };+ }+ return status;+}++/** A new idempotency key for one rule edit (printed so a lost reply can be reconciled with gbrain access rule status --operation). */+export function newOperationId(): string {+ return `acc_${randomUUID()}`;+}++/** Installs `invalid` coverage for prefixes a policy file that does not validate touches ('' for the whole source), replacing any earlier. */+export async function markPolicyInvalid(engine: BrainEngine, sourceId: string, prefixes: string[] | null, detail: unknown): Promise<void> {+ await ensurePolicyState(engine, sourceId);+ await engine.transaction(async tx => {+ await lockSource(tx, sourceId);+ await tx.executeRaw(`DELETE FROM access_pending_coverage WHERE source_id = $1 AND reason = 'invalid'`, [sourceId]);+ for (const prefix of prefixes ?? ['']) {+ await tx.executeRaw(`INSERT INTO access_pending_coverage (source_id, prefix, reason, detail) VALUES ($1, $2, 'invalid', $3::text::jsonb)`, [sourceId, prefix, JSON.stringify(detail)]);+ }+ });+}++export async function clearPolicyInvalid(engine: Exec, sourceId: string): Promise<void> {+ await engine.executeRaw(`DELETE FROM access_pending_coverage WHERE source_id = $1 AND reason = 'invalid'`, [sourceId]);+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 74e10b4942..7947285449 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1271,6 +1271,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', id: 'private_pages_granted_sources_gbra156', text: 'Access tokens and OAuth clients have a new private-pages grant, `none` for every existing and new token and client, so remote reads still hide `visibility: private` pages until the brain host opts a connection in: `gbrain auth rescope --token <name> --private-pages granted-sources` (or `--client <id>`) lets it read private pages in the sources its grant names, and only those. A token with no source grant, federated sources the grant does not name and a request\'s `source_ids` never add one; `context_pack`, `delta` and writes keep hiding private pages. `--private-pages none` turns it off on the next request.' },{ since: 'TBD', id: 'member_read_access_gbra218', text: 'A page whose frontmatter names readers (`readable_by: [alice-example, group:team-a]`) is now read remotely only by a token, OAuth client or stdio server bound to a listed member (`gbrain access member add`, `gbrain auth rescope --token <name> --member <id>`, config `mcp.stdio_member`). Every other remote caller gets the same `not_found` as for a missing page, including unbound credentials, a `--private-pages granted-sources` bot and both escape hatches (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), which relax only `visibility: private`. A malformed `readable_by` reads as nobody, and a page derived from a restricted page reads as nobody remotely. Pages that already named `readable_by` before this upgrade read as nobody remotely until `gbrain repair access` (preview, then `--apply`). The local CLI is unchanged; `--as <member>` previews one member\'s view.' },{ since: 'TBD', id: 'member_access_hatch_scope_gbra218', text: 'On a brain where any page names readers or any member exists, the escape hatches no longer turn the remote read filter off: remote reads still hide pages the caller\'s member is not listed on, and secondary surfaces that use the identity-free filter (proactive brief, retrieval reflex, entity resolution, known-as-of) hide every restricted page and keep hiding `visibility: private` pages under a hatch. A brain with no restriction keeps the old hatch behaviour exactly. A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).' },+ { since: 'TBD', id: 'folder_access_rules_gbra218', text: 'A source can now keep whole folders to named members with folder rules (`gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source <id>`, preview then `--yes`). On a repo-less source the rules live in the database; on a git-backed source they live in `.gbrain/access.yml`, committed through `gbrain git commit-push` and applied on sync. A remote read of a page under a rule needs the caller\'s member to be listed on every rule covering it, on top of the page\'s own `readable_by`; no hatch, grant or `--as` relaxes it. Narrowing applies at once; a change that widens (removing a rule or a reader) is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it. While an apply is unfinished its prefixes read as nobody remotely (`access_policy_pending`, fixed by `gbrain access resume --source <id>`). `gbrain export` carries each source\'s applied rules under `.gbrain/`, and `gbrain import` installs them before any page (`--access-policy <source>` picks one source\'s rules from a multi-source export). Remote callers cannot write `.gbrain/` pages. Nothing changes on a source with no folder rule.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 76fbc90d32..f0c3b0c3c7 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -14,7 +14,7 @@// (help-text mentions count): accepting an ignored flag is the pre-#2185// status quo; missing a real one breaks working invocations.export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {- 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--as', '--bind-token', '--brain', '--client', '--groups', '--help', '--id', '--if-version', '--json', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operations', '--private-pages', '--refresh-operations', '--reset-default', '--scopes', '--source', '--sources', '--takes-holders', '--token', '--yes'],+ 'access': ['--add', '--adopt-columns', '--adopt-permissions', '--all', '--all-new', '--approved', '--as', '--bind-token', '--brain', '--client', '--expect', '--file', '--groups', '--help', '--id', '--if-version', '--json', '--limit', '--may-act-for', '--member', '--members', '--migrate-legacy', '--name', '--operation', '--operations', '--prefix', '--private-pages', '--readers', '--refresh-operations', '--reset-default', '--revision', '--scopes', '--source', '--sources', '--takes-holders', '--to', '--token', '--yes'],'advisor': ['--apply', '--brain', '--help', '--json', '--skills-dir', '--source', '--workspace', '--yes'],'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],'anomalies': ['--all', '--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--request-id', '--sigma', '--since', '--source'],@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -61,7 +61,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],'errors': ['--brain', '--changed', '--help', '--json', '--source'],'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--as', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--request-id', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--timings', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],- 'export': ['--accept-pending', '--as', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],+ 'export': ['--accept-pending', '--access-policy', '--as', '--background', '--body', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--as', '--background', '--backup-verified', '--body', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--retry-held', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--as', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--types', '--url', '--wait', '--workers', '--yes'],'facts': ['--admin-intent', '--after-id', '--all', '--brain', '--clear', '--conversation', '--dry-run', '--entity', '--examples', '--expected-state', '--force', '--help', '--include-private', '--json', '--limit', '--list', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--reset', '--retry-model', '--since', '--slug', '--slugs', '--source', '--source-id'],@@ -76,11 +76,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--plan', '--port', '--prefer-postgres', '--probe', '--provenance', '--purge-client', '--query', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--search-mode', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],- 'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'import': ['--accept-pending', '--access-policy', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--as', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],+ 'init': ['--access', '--access-policy', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -132,7 +132,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 3c5fe3c29f..255a78507b 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -85,6 +85,10 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['access_unknown_readers','access_recent_narrowings','access_page_readers_backfill',+ 'access_policy_pending',+ 'access_policy_widening_held',+ 'access_policy_invalid',+ 'access_policy_store_mismatch','extractor_facts_expired','loop_facts_drift','ontology_facts_fenced',diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 867e915dd4..65ede92aa1 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -36,6 +36,10 @@ export const ERROR_CATALOGUE = {access_member_invalid: { code: 'access_member_invalid', docs: 'docs/guides/write-refusals.md#access_member_invalid' },access_member_id_retired: { code: 'access_member_id_retired', docs: 'docs/guides/write-refusals.md#access_member_id_retired' },access_member_disabled: { code: 'access_member_disabled', docs: 'docs/guides/write-refusals.md#access_member_disabled' },+ // GBRA-218 (A2) folder rules: invalid rules and policy files, pending narrowing.+ access_rule_invalid: { code: 'access_rule_invalid', docs: 'docs/guides/write-refusals.md#access_rule_invalid' },+ access_policy_invalid: { code: 'access_policy_invalid', docs: 'docs/guides/write-refusals.md#access_policy_invalid' },+ access_policy_pending: { code: 'access_policy_pending', docs: 'docs/guides/write-refusals.md#access_policy_pending' },// W2 page-at-time: recorded-time reads (`known_as_of`).coverage_from: { code: 'coverage_from', docs: 'docs/guides/repair.md#coverage-from' },coverage_gap: { code: 'coverage_gap', docs: 'docs/guides/repair.md#coverage-gap' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ca7c7b2668..827db95364 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -65,6 +65,11 @@ export const CODES = {absent_from_worktree: { class: 'caller', retryable: false, reasons: ['skip_worktree', 'deleted_locally'], summary: "Sync held one file that is committed at HEAD but missing from the working tree (a sparse checkout or a skip-worktree bit, or a local deletion that is not committed); the rest of the source synced.", why: "Sync imports from the working tree, so it cannot import a file that is not on disk, and treating it as deleted would drop a committed file silently. Whether the file comes back or its deletion is committed is the user's choice; classic sync re-screens the hold on every run.", docs: 'docs/guides/write-refusals.md#absent_from_worktree', suggestion: 'Restore the file (git restore -- <path>, or widen the sparse checkout) and the next sync imports it; or commit the deletion with gbrain git commit-push -m <msg> -- <path> and the next sync clears the hold.' },access_command_failed: { class: 'caller', summary: "Google connect credential error: access command failed.", docs: 'docs/guides/google-connect.md#troubleshooting' },access_member_disabled: { class: 'host_only', actor: 'user', reasons: ['disabled', 'removed', 'missing', 'malformed'], summary: "The credential (access token, OAuth client or stdio binding) is bound to a member who is disabled, removed or missing, so it was refused at verification and nothing was read.", why: 'A credential bound to a member reads as that member. While the member cannot read, the credential is refused rather than silently treated as unbound.', docs: 'docs/guides/write-refusals.md#access_member_disabled', suggestion: 'Ask the brain operator to enable the member (gbrain access member enable <id>) or rebind the credential (gbrain auth rescope --token <name>|--client <id> --member <id>|none).' },+ access_policy_invalid: { class: 'host_only', actor: 'user', docs: 'docs/guides/write-refusals.md#access_policy_invalid', summary: "A source's folder-rule policy (the committed .gbrain/access.yml, or a file given to gbrain access rule import) does not validate, so it was not applied: the last applied rules stay in force and every prefix the bad file names reads as nobody (the whole source when its prefixes cannot be read).", why: 'A typo in an access file must never open a folder: an unreadable revision keeps the previous rules and hides what it touches until it is fixed.', suggestion: 'Show each problem with its line (gbrain access rule list --source <id>), fix the file, commit it with gbrain git commit-push and sync the source (gbrain sync --source <id> --no-pull).', fix: { argv: ['gbrain', 'access', 'rule', 'list', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the applied rules and each problem in the policy file with its line; changes nothing.' } },+ access_policy_pending: { class: 'retryable', docs: 'docs/guides/write-refusals.md#access_policy_pending', summary: "A narrowing change to a source's folder rules is still being applied to its pages, so the prefixes it touches read as nobody until it finishes; pages under other prefixes keep the last applied rules.", why: 'Pages under a newly restricted folder are restamped in batches; until the last batch and its re-check pass land, they read as nobody instead of under the old rules.', suggestion: 'Retry shortly. If it stays pending, the apply was interrupted: the brain host finishes it with gbrain access resume --source <id> (database store) or gbrain sync --source <id> --no-pull (git store).', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the pending prefixes and the revision being applied; changes nothing.' } },+ access_policy_widening_held: { class: 'consent', actor: 'user', summary: "A change to a source's folder rules widens who may read (a rule removed, readers added, a prefix moved), so it is recorded but held: the previous rules stay in force until an operator previews it with gbrain access apply --source <id> and approves the printed plan with --yes --expect <plan_hash> on the brain host.", why: 'Write access to the policy (a git commit or a rule edit) must not be enough to open a folder; widening needs a host-side preview and an explicit approval.', suggestion: 'Ask the user whether to approve the widening; the brain host previews it with gbrain access apply --source <id>.', fix: { argv: ['gbrain', 'access', 'apply', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the held widening (pages and members gaining access) and prints the plan hash an approval binds; changes nothing.' } },+ access_policy_store_mismatch: { class: 'host_only', actor: 'user', summary: "A source's persisted folder-rule store (sources.config.access_store) disagrees with what this host sees (a git store with no visible work tree, or a database store whose root became a repository), so the persisted store and its applied rules stay in force and nothing switches on its own.", why: 'Inferring the store per host would let a missing checkout or a stray git init change which rules apply; only gbrain access rule migrate moves them, and neither direction widens.', suggestion: 'On the brain host, preview the move with gbrain access rule migrate --source <id>, then apply it by adding --yes.', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the persisted store and the applied rules; changes nothing.' } },+ access_rule_invalid: { class: 'caller', docs: 'docs/guides/write-refusals.md#access_rule_invalid', summary: 'A folder rule given to gbrain access rule add is invalid (its prefix is not a literal lower-case folder ending in /, holds .. or *, its readers are not member ids or group:<id>, or another rule already covers the prefix), so nothing was written.', why: 'Prefixes are matched literally against slugs; a pattern or a typo would silently restrict the wrong pages or none.', suggestion: 'Write the prefix as a slug folder ending in / (partners/alice-example/) and the readers as member ids or group:<id>.' },access_member_id_retired: { class: 'caller', summary: "The member id was removed earlier and member ids are never reused, so nothing was created or enabled.", why: 'Pages and audit history may still name a removed id; reusing it would hand that history to a different person.', docs: 'docs/guides/write-refusals.md#access_member_id_retired', suggestion: 'Choose a new member id.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status, removed ones included.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },access_member_invalid: { class: 'caller', reasons: ['ill_formed', 'unknown', 'disabled', 'removed', 'exists', 'unknown_group'], summary: "A member or group id given to an access command, a credential binding or --as is ill-formed or names no usable member, so nothing was read or changed.", why: 'Ids are matched exactly against page readers; an unknown or disabled member is refused rather than read as unbound, so a typo never previews or binds the wrong view.', docs: 'docs/guides/write-refusals.md#access_member_invalid', suggestion: 'Check the id with gbrain access member list --all, or add the member first.', fix: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Read-only: lists every member id on this brain with its status.', verify: { argv: ['gbrain', 'access', 'member', 'list', '--all', '--json'] } } },access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },@@ -866,6 +871,7 @@ export const NOTICE_CODES = {mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },+ access_policy_pending: { kind: 'degraded', summary: 'A read touched a source whose folder rules are being narrowed or whose policy file does not validate: pages under the affected prefixes read as nobody until the brain host finishes it, so a missing page there is not proof the brain has nothing on it; the fix shows the policy state, then the host runs gbrain access resume --source <id> (database store) or gbrain sync --source <id> --no-pull (git store).' },sources_not_readable: { kind: 'degraded', summary: 'An unscoped search, query, recall or list_pages came back empty because every source this connection can read holds no page, while other sources on the brain hold pages it cannot read (not federated, and no source grant). The result is not proof of absence; the fix is the host command that federates a source or grants this connection the sources it should read. Hidden sources are never named.' },degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },facts_calibration_unmeasured: { kind: 'info', summary: 'recall --question ranked facts with semantic matching on an embedding model whose fact admission floors were never measured (`facts_calibration: {status: "unmeasured", model_key}`); a short facts list is weaker evidence of "nothing matched". Once per brain per session; the fix is the read-only `gbrain doctor --only fact_admission_floors --json`.' },diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.tsindex d794d85e4f..e5d4d25137 100644--- a/src/core/persistence/page-visibility.ts+++ b/src/core/persistence/page-visibility.ts@@ -1,7 +1,7 @@import { opError } from '../ops/contract.ts';-import { callerAccessAllowedSql, callerIdentity, readPolicyFragment, readRemotePolicyNow } from '../search/private-visibility.ts';+import { callerAccessAllowedSql, callerIdentity, readPolicyFragment, readRemotePolicyNow, withCallerAccess } from '../search/private-visibility.ts';import { parseMarkdown } from '../markdown.ts';-import { memberIdentityFor } from '../access/caller.ts';+import { folderAccessFor, memberIdentityFor } from '../access/caller.ts';import { hasReaders, normalizePrincipal, normalizeReaders, readersAllow, NOBODY } from '../access/principals.ts';import { catalogueError } from '../error-catalogue.ts';import type { SqlEngine, WriteAuthority } from './model.ts';@@ -24,8 +24,10 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writconst hidePrivate = (authority.excludePrivate ?? true) || !policy.privacyRelaxed;if (!hidePrivate && !policy.restricted) return;const identity = policy.restricted ? await memberIdentityFor(engine, authority) : [];+ const folder = policy.restricted ? await folderAccessFor(engine, identity) : { satisfiedRuleIds: [], folderCoverage: [] };+ const fragment = withCallerAccess({ folderCoverage: folder.folderCoverage }, () => readPolicyFragment('pages', identity, hidePrivate, folder.satisfiedRuleIds));const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2- AND NOT (${readPolicyFragment('pages', identity, hidePrivate)}) LIMIT 1`, [authority.sourceId, slug]);+ AND NOT (${fragment}) LIMIT 1`, [authority.sourceId, slug]);if (rows.length) throw pageNotVisibleError();}diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 6d1e21ecc7..4f1b5b8a21 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 274;+export const LATEST_SCHEMA_VERSION = 275;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 667e31f41d..3bfb31d5a7 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -275,6 +275,7 @@ import { v271 } from './v271-facts-superseded-by-index.ts';import { v272 } from './v272-git-canonical-declared.ts';import { v273 } from './v273-principal-private-pages.ts';import { v274 } from './v274-member-read-access.ts';+import { v275 } from './v275-folder-access-rules.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -548,4 +549,5 @@ export const MIGRATIONS: Migration[] = [v272,v273,v274,+ v275,];diff --git a/src/core/schema-migrations/v275-folder-access-rules.ts b/src/core/schema-migrations/v275-folder-access-rules.tsnew file mode 100644index 0000000000..3d6849b68f--- /dev/null+++ b/src/core/schema-migrations/v275-folder-access-rules.ts@@ -0,0 +1,147 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GBRA-218 (PR A2): per-folder read access. A source's applied rulebook+// (access_rules: id, literal slug prefix, normalized readers) is one table for+// both policy stores: on a git-backed source it is a derived copy of the+// approved `.gbrain/access.yml`, on a repo-less source it is the record. Every+// edit appends a row to access_policy_revisions (desired rules, how the change+// classified, who proposed and approved it). access_policy_state holds one+// row per source with a policy; rulebook installs lock it FOR UPDATE and every+// page write in that source takes it FOR SHARE before stamping, so a page+// written during an install is either stamped from the new rules or committed+// before the install's re-check pass, which restamps it.+//+// pages.folder_rule_ids is derived: the source-qualified ids+// (`<source>:<rule>`) of every applied rule whose prefix the slug starts with,+// NULL when none. A trigger stamps it on every insert and on every change of+// slug or source, reading the applied rulebook inside the write's own+// transaction, so put_page, sync, cycles, renames and derived writers all get+// it with no code path to miss. access_pending_coverage lists prefixes that+// read as nobody: a narrowing still being stamped ('pending') or a policy file+// that does not validate ('invalid'; prefix '' covers the whole source). The+// read-time lineage test treats an origin under a folder rule or a covered+// prefix as restricted. Nothing is rewritten on upgrade: with no rule, every+// page keeps folder_rule_ids NULL.+// No schema.sql mirror: like v274, these exist only through migrations.+// Provisional number: renumbered at the merge slot.+export const v275: Migration = {+ version: 275,+ name: 'folder_access_rules',+ idempotent: true,+ sql: `+ALTER TABLE pages ADD COLUMN IF NOT EXISTS folder_rule_ids TEXT[];+CREATE INDEX IF NOT EXISTS pages_folder_rule_ids_gin ON pages USING gin (folder_rule_ids) WHERE folder_rule_ids IS NOT NULL;+CREATE TABLE IF NOT EXISTS access_policy_state (+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE TABLE IF NOT EXISTS access_rules (+ source_id TEXT NOT NULL REFERENCES access_policy_state(source_id) ON DELETE CASCADE,+ rule_id TEXT NOT NULL CHECK (rule_id ~ '^[a-z0-9][a-z0-9._-]{0,63}$'),+ prefix TEXT NOT NULL CHECK (length(prefix) <= 512 AND prefix ~ '^([a-z0-9][a-z0-9._-]*/)+$' AND position('..' in prefix) = 0),+ readable_by TEXT[] NOT NULL,+ revision BIGINT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ created_by TEXT,+ PRIMARY KEY (source_id, rule_id)+);+CREATE TABLE IF NOT EXISTS access_policy_revisions (+ source_id TEXT NOT NULL REFERENCES access_policy_state(source_id) ON DELETE CASCADE,+ revision BIGINT NOT NULL CHECK (revision > 0),+ rules JSONB NOT NULL,+ digest TEXT NOT NULL,+ change_kind TEXT NOT NULL CHECK (change_kind IN ('narrowing', 'widening', 'mixed', 'unchanged')),+ origin TEXT NOT NULL,+ operation_id TEXT,+ proposed_by TEXT,+ approved_by TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ applied_at TIMESTAMPTZ,+ approved_at TIMESTAMPTZ,+ PRIMARY KEY (source_id, revision)+);+CREATE UNIQUE INDEX IF NOT EXISTS access_policy_revisions_operation_idx ON access_policy_revisions (operation_id) WHERE operation_id IS NOT NULL;+CREATE TABLE IF NOT EXISTS access_pending_coverage (+ source_id TEXT NOT NULL REFERENCES access_policy_state(source_id) ON DELETE CASCADE,+ prefix TEXT NOT NULL CHECK (prefix = '' OR (length(prefix) <= 512 AND prefix ~ '^([a-z0-9][a-z0-9._-]*/)+$' AND position('..' in prefix) = 0)),+ reason TEXT NOT NULL CHECK (reason IN ('pending', 'invalid')),+ revision BIGINT,+ detail JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, prefix, reason)+);+CREATE TABLE IF NOT EXISTS access_policy_migrations (+ id TEXT PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES access_policy_state(source_id) ON DELETE CASCADE,+ direction TEXT NOT NULL CHECK (direction IN ('to_git', 'to_database')),+ phase TEXT NOT NULL CHECK (phase IN ('started', 'exported', 'committed', 'switched')),+ receipts JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE OR REPLACE FUNCTION gbrain_access_folder_rules(p_source TEXT, p_slug TEXT) RETURNS TEXT[]+ LANGUAGE sql STABLE PARALLEL SAFE SET search_path = pg_catalog, public AS $fn$+ SELECT array_agg(p_source || ':' || r.rule_id ORDER BY r.rule_id COLLATE "C")+ FROM access_rules r WHERE r.source_id = p_source AND starts_with(p_slug, r.prefix)+$fn$;+CREATE OR REPLACE FUNCTION gbrain_access_pending_covers(p_source TEXT, p_slug TEXT) RETURNS boolean+ LANGUAGE sql STABLE PARALLEL SAFE SET search_path = pg_catalog, public AS $fn$+ SELECT EXISTS (SELECT 1 FROM access_pending_coverage c WHERE c.source_id = p_source AND starts_with(p_slug, c.prefix))+$fn$;+CREATE OR REPLACE FUNCTION gbrain_access_stamp_folder_rules() RETURNS trigger+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$+BEGIN+ IF EXISTS (SELECT 1 FROM access_policy_state s WHERE s.source_id = NEW.source_id) THEN+ PERFORM 1 FROM access_policy_state s WHERE s.source_id = NEW.source_id FOR SHARE;+ NEW.folder_rule_ids := gbrain_access_folder_rules(NEW.source_id, NEW.slug);+ ELSE+ NEW.folder_rule_ids := NULL;+ END IF;+ RETURN NEW;+END+$fn$;+DROP TRIGGER IF EXISTS pages_access_stamp_folder_rules ON pages;+CREATE TRIGGER pages_access_stamp_folder_rules BEFORE INSERT OR UPDATE OF slug, source_id, folder_rule_ids ON pages+ FOR EACH ROW EXECUTE FUNCTION gbrain_access_stamp_folder_rules();+CREATE OR REPLACE FUNCTION gbrain_access_origin_restricted(p_id INTEGER, p_source_id TEXT, p_type TEXT, fm JSONB) RETURNS boolean+ LANGUAGE plpgsql STABLE PARALLEL SAFE SET search_path = pg_catalog, public AS $fn$+BEGIN+ IF p_type = 'atom' THEN+ IF EXISTS (SELECT 1 FROM pages o WHERE o.source_id = p_source_id AND o.slug = fm->>'source_slug'+ AND (o.frontmatter ? 'readable_by' OR o.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(o.source_id, o.slug))) THEN+ RETURN true;+ END IF;+ ELSIF p_type = 'question' OR (p_type = 'concept' AND fm->>'synthesized_by' IS NOT NULL) THEN+ IF EXISTS (SELECT 1 FROM links l JOIN pages i ON i.id = l.to_page_id+ WHERE l.from_page_id = p_id AND l.link_source = 'concept-provenance' AND l.link_type = 'synthesized_from'+ AND (i.frontmatter ? 'readable_by' OR i.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(i.source_id, i.slug)+ OR EXISTS (SELECT 1 FROM pages io WHERE io.source_id = i.source_id AND io.slug = i.frontmatter->>'source_slug'+ AND (io.frontmatter ? 'readable_by' OR io.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(io.source_id, io.slug))))) THEN+ RETURN true;+ END IF;+ ELSIF p_type = 'event' AND fm->>'captured_via' LIKE 'life-chronicle:%' THEN+ IF EXISTS (SELECT 1 FROM pages c WHERE c.source_id = p_source_id AND c.slug = fm->'event'->>'depth'+ AND (c.frontmatter ? 'readable_by' OR c.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(c.source_id, c.slug))) THEN+ RETURN true;+ END IF;+ END IF;+ IF jsonb_typeof(fm->'derived_from') IN ('array', 'string') THEN+ RETURN EXISTS (SELECT 1 FROM pages d WHERE d.source_id = p_source_id+ AND (d.frontmatter ? 'readable_by' OR d.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(d.source_id, d.slug))+ AND d.slug = ANY(ARRAY(SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text(+ CASE WHEN jsonb_typeof(fm->'derived_from') = 'array' THEN fm->'derived_from' ELSE jsonb_build_array(fm->'derived_from') END) AS declared(slug))));+ END IF;+ RETURN false;+END+$fn$;+DROP TRIGGER IF EXISTS access_rules_mark_restricted ON access_rules;+CREATE TRIGGER access_rules_mark_restricted AFTER INSERT ON access_rules+ FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted();+DROP TRIGGER IF EXISTS access_pending_coverage_mark_restricted ON access_pending_coverage;+CREATE TRIGGER access_pending_coverage_mark_restricted AFTER INSERT ON access_pending_coverage+ FOR EACH ROW EXECUTE FUNCTION gbrain_access_mark_restricted();+`,+};diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 928136fbd2..4bef690279 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -24,6 +24,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import { isValidSourceId } from '../source-id.ts';import { hasReaders, readersAllow, validIdentity } from '../access/principals.ts';+import { validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';@@ -68,8 +69,40 @@ function privacyPartSql(pageAlias: string): string {* `identity` must pass validIdentity (its alphabet has no quote), so it is* embedded as literals; anything else empties it (fail closed).*/-export function accessAllowedSql(pageAlias: string, identity: readonly string[]): string {- return `(${readersAllowedSql(pageAlias, identity)} AND ${originAllowedSql(pageAlias)})`;+export function accessAllowedSql(pageAlias: string, identity: readonly string[], satisfied: readonly string[] = satisfiedFor(identity)): string {+ return `(${readersAllowedSql(pageAlias, identity)} AND ${folderRulesAllowedSql(pageAlias, satisfied)} AND ${originAllowedSql(pageAlias)})`;+}++/**+ * GBRA-218 (PR A2): the folder layer. `folder_rule_ids` holds the source-qualified ids+ * of every applied folder rule whose prefix the slug starts with (a trigger stamps it from the applied rulebook,+ * migration v275); a page passes only when the caller satisfies all of them (`<@`, set semantics), so nested member+ * and group rules both have to pass. `satisfied` is the caller's satisfied set (CallerAccess.satisfiedRuleIds); an+ * entry that is not a valid qualified id empties it (fail closed). Prefixes under a narrowing still being stamped,+ * or touched by a policy file that does not validate, read as nobody (CallerAccess.folderCoverage). Column tests+ * lead, so a page under no rule costs one NULL test.+ */+export function folderRulesAllowedSql(alias: string, satisfied: readonly string[]): string {+ const ids = satisfied.length && satisfied.every(validQualifiedRuleId) ? [...new Set(satisfied)].sort() : [];+ const listed = ids.length ? ` OR ${alias}.folder_rule_ids <@ ARRAY[${ids.map(id => `'${id}'`).join(', ')}]::text[]` : '';+ return `(${alias}.folder_rule_ids IS NULL${listed})${coverageSql(alias)}`;+}++/** The pending or invalid prefixes of the current record as a conjunct (empty when none); an ill-formed entry hides everything. */+function coverageSql(alias: string): string {+ const coverage = currentCallerAccess().folderCoverage;+ if (!coverage.length) return '';+ return coverage.map(c => !isValidSourceId(c.source_id) || (c.prefix !== '' && !validPrefix(c.prefix)) ? ' AND FALSE'+ : c.prefix === '' ? ` AND ${alias}.source_id <> '${c.source_id}'`+ : ` AND NOT (${alias}.source_id = '${c.source_id}' AND starts_with(${alias}.slug, '${c.prefix}'))`).join('');+}++/** The satisfied rule ids for `identity`: the current record's set when it is the record's identity, else none. */+function satisfiedFor(identity: readonly string[]): readonly string[] {+ const access = currentCallerAccess();+ if (!identity.length || identity.length !== access.identity.length) return [];+ const sorted = [...identity].sort();+ return sorted.every((p, i) => p === access.identity[i]) ? access.satisfiedRuleIds : [];}/**@@ -119,11 +152,11 @@ function originAllowedSql(p: string): string {* candidate pages (an entity's referrers).*/export function privatePagesFilterFragmentFast(pageAlias: string): string {- return `((${pageAlias}.frontmatter->'visibility' IS NULL AND ${pageAlias}.frontmatter->'derived_from' IS NULL${honorAliases()+ return `(${folderRulesAllowedSql(pageAlias, [])} AND ((${pageAlias}.frontmatter->'visibility' IS NULL AND ${pageAlias}.frontmatter->'derived_from' IS NULL${honorAliases()? `\n AND ${pageAlias}.frontmatter->'access' IS NULL AND ${pageAlias}.frontmatter->'confidentiality' IS NULL` : ''}AND ${pageAlias}.frontmatter->'readable_by' IS NULLAND ${pageAlias}.type NOT IN ('atom', 'concept', 'event'))- OR ${privatePagesFilterFragment(pageAlias)})`;+ OR ${privatePagesFilterFragment(pageAlias)}))`;}/**@@ -144,15 +177,20 @@ export function privatePagesFilterFragmentFast(pageAlias: string): string {*/export interface CallerAccess {identity: readonly string[];+ /** GBRA-218 (A2): the source-qualified folder-rule ids (`<source>:<rule>`) the identity satisfies, from the applied rulebook. */+ satisfiedRuleIds: readonly string[];+ /** GBRA-218 (A2): prefixes that read as nobody (a narrowing being stamped, an invalid policy file); prefix '' is the whole source. */+ folderCoverage: readonly FolderCoverage[];privateReadableSources: readonly string[];hidePrivate: boolean;applyRemoteReadPolicy: boolean;}+export interface FolderCoverage { source_id: string; prefix: string }const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false };+ return callerAccessStore.getStore() ?? { identity: [], satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), applyRemoteReadPolicy: false };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -160,8 +198,12 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):const base = currentCallerAccess();const identity = access.identity ?? base.identity;const sources = access.privateReadableSources ?? base.privateReadableSources;+ const validIds = identity.length > 0 && validIdentity(identity);+ const satisfied = validIds ? access.satisfiedRuleIds ?? (access.identity ? [] : base.satisfiedRuleIds) : [];return callerAccessStore.run(Object.freeze({- identity: identity.length && validIdentity(identity) ? Object.freeze([...new Set(identity)].sort()) : Object.freeze([]),+ identity: validIds ? Object.freeze([...new Set(identity)].sort()) : Object.freeze([]),+ satisfiedRuleIds: satisfied.length && satisfied.every(validQualifiedRuleId) ? Object.freeze([...new Set(satisfied)].sort()) : Object.freeze([]),+ 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,applyRemoteReadPolicy: access.applyRemoteReadPolicy ?? base.applyRemoteReadPolicy,@@ -230,8 +272,8 @@ export function callerAccessAllowedSql(pageAlias: string): string {* part, then the privacy part unless `hidePrivate` is false. With an empty* identity and `hidePrivate` it equals privatePagesFilterFragment.*/-export function readPolicyFragment(pageAlias: string, identity: readonly string[], hidePrivate: boolean): string {- return `(${accessAllowedSql(pageAlias, identity)} AND ${hidePrivate ? privacyPartSql(pageAlias) : 'TRUE'})`;+export function readPolicyFragment(pageAlias: string, identity: readonly string[], hidePrivate: boolean, satisfied?: readonly string[]): string {+ return `(${accessAllowedSql(pageAlias, identity, satisfied)} AND ${hidePrivate ? privacyPartSql(pageAlias) : 'TRUE'})`;}/** privatePagesFilterFragmentFast for a remote read. */diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 91fa1dd46f..57d322bac4 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -113,7 +113,7 @@ export interface VectorSearchStatement {* of the probe (a segmented page has no body string).*/export const INDEX_WALK_PAGE_COLUMNS = ['id', 'slug', 'source_id', 'title', 'type', 'frontmatter', 'deleted_at', 'updated_at', 'effective_date',- 'effective_date_source', 'trust_tier', 'body_generation', 'chunker_version', 'knowledge_revision', 'text_projection_revision', 'page_readers'] as const;+ 'effective_date_source', 'trust_tier', 'body_generation', 'chunker_version', 'knowledge_revision', 'text_projection_revision', 'page_readers', 'folder_rule_ids'] as const;/** Raw rows the index walk orders per window slot, so page filters can drop some and still fill the window. */export const INDEX_WALK_OVERFETCH = 2;diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex e4c2d6c037..4d48d68ce4 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -28,6 +28,7 @@ import { searchCountLine } from '../core/search/keyword-paging.ts';import { dateLabelLine } from '../core/search/date-labels.ts';import { hiddenTakesNotice, localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';import { unreadableSourcesNotice } from '../core/unreadable-sources-notice.ts';+import { accessPolicyNotices } from '../core/access/policy-notice.ts';import { hiddenToolHint, hiddenToolNext, hiddenToolRoute, type ToolConnection } from './hidden-tool-hint.ts';import { opAllowedForBoundClient } from '../core/ops/context.ts';import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';@@ -1156,7 +1157,7 @@ async function dispatchResolvedCall(notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,{ config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding, rerankDegradedCalls }));const unreadable = await unreadableSourcesNotice(name, safeParams, result, ctx);- if (unreadable) notices.push(unreadable);+ notices.push(...(unreadable ? [unreadable] : []), ...accessPolicyNotices(name, ctx));notices.push(...await hiddenContentNotices(engine, name, result, ctx, opts));// Monthly backup-coverage: one AGGREGATE notice per process (counts only —// never a local path or source id). The refresher runs on the stdiodiff --git a/test/access-folder-doctor.test.ts b/test/access-folder-doctor.test.tsnew file mode 100644index 0000000000..e1da9d3333--- /dev/null+++ b/test/access-folder-doctor.test.ts@@ -0,0 +1,70 @@+/**+ * GBRA-218 (A2) folder-rule doctor checks on a repo-less PGLite brain:+ * access_policy_pending, access_policy_widening_held, access_policy_invalid and+ * access_policy_store_mismatch each find their case, carry a fix whose verify+ * is the read-only check, clear once fixed, and are not applicable on a brain+ * where no source has a folder rule.+ */+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 { folderAccessEntry } from '../src/commands/doctor/checks/folder-access.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { markPolicyInvalid, clearPolicyInvalid, policySeams, proposeRevision, resumePolicy, writeAccessStore } from '../src/core/access/policy.ts';++const SRC = 'fd-team';+const page = (title: string) => ['---', 'type: note', 'title: ' + title, '---', '# ' + title, '', 'Body.'].join('\n');+const rule = (id: string, prefix: string, readers: string[]) => ({ id, prefix, readable_by: readers });++describe('folder-rule doctor checks (pglite, repo-less)', () => {+ let engine: BrainEngine;+ const run = async () => Object.fromEntries((await folderAccessEntry.run({ engine } as unknown as DoctorContext) as Array<{ name: string }>).map(c => [c.name, c])) as Record<string, any>;++ beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await importFromContent(engine, 'partners/alice-example/plan', page('Plan'), { sourceId: SRC, noEmbed: true });+ }, 120_000);+ afterAll(async () => { policySeams.afterInstall = undefined; await engine.disconnect(); });++ test('no folder rule: every check is not applicable', async () => {+ const checks = await run();+ expect(Object.keys(checks).sort()).toEqual(['access_policy_invalid', 'access_policy_pending', 'access_policy_store_mismatch', 'access_policy_widening_held']);+ for (const c of Object.values(checks)) expect(c).toMatchObject({ status: 'ok', readiness_state: 'not_applicable' });+ }, 60_000);++ test('a narrowing interrupted mid-apply is pending until resume', async () => {+ policySeams.afterInstall = () => { throw new Error('interrupted'); };+ try { await expect(proposeRevision(engine, SRC, [rule('alice', 'partners/alice-example/', ['member:alice-example'])], { origin: 'cli', store: 'database' })).rejects.toThrow('interrupted'); }+ finally { policySeams.afterInstall = undefined; }+ const c = (await run()).access_policy_pending;+ expect(c).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'access', 'resume', '--source', SRC], verify: { argv: ['gbrain', 'doctor', '--only', 'access_policy_pending', '--json'] } } });+ expect(c.details.sources[0]).toMatchObject({ source: SRC, prefixes: ['partners/alice-example/'], drifted: 1 });+ await resumePolicy(engine, SRC);+ expect((await run()).access_policy_pending.status).toBe('ok');+ }, 60_000);++ test('a held widening names the revision and previews with apply', async () => {+ await proposeRevision(engine, SRC, [], { origin: 'cli' });+ const c = (await run()).access_policy_widening_held;+ expect(c).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'access', 'apply', '--source', SRC, '--json'], ask_user: true } });+ expect(c.details.sources[0].changes).toEqual(['removed alice (partners/alice-example/)']);+ await proposeRevision(engine, SRC, [rule('alice', 'partners/alice-example/', ['member:alice-example'])], { origin: 'revert' });+ expect((await run()).access_policy_widening_held.status).toBe('ok');+ }, 60_000);++ test('an invalid policy file fails until cleared', async () => {+ await markPolicyInvalid(engine, SRC, ['hr/'], { problems: [{ line: 4, message: 'bad' }] });+ expect((await run()).access_policy_invalid).toMatchObject({ status: 'fail', details: { sources: [{ source: SRC, prefixes: ['hr/'] }] } });+ await clearPolicyInvalid(engine, SRC);+ expect((await run()).access_policy_invalid.status).toBe('ok');+ }, 60_000);++ test('a git store with no visible work tree is a store mismatch, fixed by a migrate preview', async () => {+ expect((await run()).access_policy_store_mismatch.status).toBe('ok');+ await writeAccessStore(engine, SRC, 'git');+ expect((await run()).access_policy_store_mismatch).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'access', 'rule', 'migrate', '--source', SRC, '--json'], ask_user: true } });+ await writeAccessStore(engine, SRC, 'database');+ }, 60_000);+});diff --git a/test/access-folder-rules-git.test.ts b/test/access-folder-rules-git.test.tsnew file mode 100644index 0000000000..ca411c013d--- /dev/null+++ b/test/access-folder-rules-git.test.ts@@ -0,0 +1,236 @@+/**+ * GBRA-218 (PR A2): folder rules on a git-backed source.+ *+ * 1. Protects: `<source root>/.gbrain/access.yml` is read by sync from the synced+ * commit (also when it is the only changed path) and applied before the+ * commit's pages are imported; narrowing applies, widening is held until+ * gbrain access apply, which commits `.gbrain/access.approved` through the+ * door. A malformed file keeps the last applied rules and hides what it+ * touches. A rebuilt database reaches the same rules from git alone. The+ * persisted store survives a removed .git, and rule migrate moves rules+ * between stores without a moment where one is missing.+ * 2. Fails when: a git commit alone widens access; sync skips a policy-only+ * commit; a bad file opens or keeps open a folder; a rebuild loses rules;+ * a migrate or a missing checkout drops rules.+ * 3. Existing coverage (access-folder-rules) pins the database store.+ * 4. Real seams: real git repositories (one with a bare remote), performSync,+ * gbrain git commit-push through commitPolicyFile, the CLI module, PGLite.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { performSync } from '../src/commands/sync.ts';+import { runAccessRules } from '../src/commands/access-rules.ts';+import { policyStatus } from '../src/core/access/policy.ts';+import { readCommittedPolicy, syncAccessPolicyAt, commitPolicyFile, POLICY_FILE } from '../src/core/access/policy-git.ts';+import { acquireCommitLock } from '../src/core/git/commit-push.ts';+import { withEnv } from './helpers/with-env.ts';++const SRC = 'gt-src';+const git = (dir: string, ...args: string[]) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();++function writePage(root: string, slug: string, body = 'Notes.') {+ mkdirSync(join(root, slug, '..'), { recursive: true });+ writeFileSync(join(root, `${slug}.md`), `---\ntype: note\ntitle: ${slug}\n---\n# ${slug}\n\n${body}\n`);+}+function writePolicy(root: string, text: string, file = POLICY_FILE) {+ mkdirSync(join(root, '.gbrain'), { recursive: true });+ writeFileSync(join(root, file), text);+}+const POLICY = (rules: Array<[string, string, string]>) => ['version: 1', 'rules:', ...rules.flatMap(([id, prefix, readers]) => [` - id: ${id}`, ` prefix: ${prefix}`, ` readable_by: [${readers}]`])].join('\n') + '\n';++async function seedBrain(engine: PGLiteEngine, root: string): Promise<PGLiteEngine> {+ await engine.executeRaw("INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, '{}')", [SRC, root]);+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);+ return engine;+}++async function stamps(engine: PGLiteEngine): Promise<Record<string, string[] | null>> {+ const rows = await engine.executeRaw<{ slug: string; folder_rule_ids: string[] | null }>('SELECT slug, folder_rule_ids FROM pages WHERE source_id = $1 ORDER BY slug', [SRC]);+ return Object.fromEntries(rows.map(r => [r.slug, r.folder_rule_ids]));+}++async function cli(engine: PGLiteEngine, args: string[]): Promise<any> {+ const lines: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });+ try { await runAccessRules(engine, args[0]!, [...args.slice(1), '--json'], true); } finally { spy.mockRestore(); }+ return JSON.parse(lines.join('\n'));+}++const sync = (engine: PGLiteEngine, root: string, full = false) => performSync(engine, { sourceId: SRC, repoPath: root, noPull: true, noEmbed: true, ...(full ? { full: true } : {}) });++describe('folder access rules, git store', () => {+ let root: string;+ let engine: PGLiteEngine;+ const spares: PGLiteEngine[] = [];++ beforeAll(async () => {+ for (let i = 0; i < 3; i++) {+ const e = new PGLiteEngine();+ await e.connect({ engine: 'pglite' } as never);+ await e.initSchema();+ spares.push(e);+ }+ root = mkdtempSync(join(tmpdir(), 'gbrain-frgit-'));+ git(root, 'init', '-q', '-b', 'main');+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'config', 'user.name', 't');+ for (const s of ['notes/open', 'partners/alice-example/plan', 'partners/team/notes']) writePage(root, s);+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example']]));+ git(root, 'add', '-A');+ git(root, 'commit', '-q', '-m', 'pages and policy');+ engine = await seedBrain(spares[0]!, root);+ }, 120_000);++ afterAll(async () => {+ for (const e of spares) await e.disconnect();+ rmSync(root, { recursive: true, force: true });+ });++ test('the first sync reads the committed policy before importing, persists the git store and stamps pages', async () => {+ await sync(engine, root, true);+ const s = await policyStatus(engine, SRC);+ expect({ store: s.store, rules: s.rules.map(r => r.id) }).toEqual({ store: 'git', rules: ['team'] });+ expect(await stamps(engine)).toEqual({ 'notes/open': null, 'partners/alice-example/plan': [`${SRC}:team`], 'partners/team/notes': [`${SRC}:team`] });+ }, 120_000);++ test('a policy-only commit is applied by the next sync (narrowing at once)', async () => {+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example'], ['alice', 'partners/alice-example/', 'alice-example']]));+ git(root, 'commit', '-q', '-am', 'narrow');+ await sync(engine, root);+ expect((await stamps(engine))['partners/alice-example/plan']).toEqual([`${SRC}:alice`, `${SRC}:team`]);+ expect((await policyStatus(engine, SRC)).held).toEqual([]);+ }, 120_000);++ test('a committed widening is held; gbrain access apply commits access.approved through the door and applies it', async () => {+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example']]));+ git(root, 'commit', '-q', '-am', 'drop alice rule');+ await sync(engine, root);+ const held = await policyStatus(engine, SRC);+ expect({ rules: held.rules.map(r => r.id), held: held.held.map(h => `${h.rule}:${h.kind}`) }).toEqual({ rules: ['alice', 'team'], held: ['alice:removed'] });+ const preview = await cli(engine, ['apply', '--source', SRC]);+ expect(preview.widening[0].gains).toEqual(['bob-example']);+ const applied = await cli(engine, ['apply', '--source', SRC, '--yes', '--expect', preview.plan_hash]);+ expect({ outcome: applied.git.outcome, path: applied.git.path }).toEqual({ outcome: 'committed_local', path: '.gbrain/access.approved' });+ expect(git(root, 'log', '-1', '--format=%s')).toContain('approve folder rules');+ expect(readCommittedPolicy(root).approved).toContain('id: team');+ expect((await policyStatus(engine, SRC)).rules.map(r => r.id)).toEqual(['team']);+ expect((await stamps(engine))['partners/alice-example/plan']).toEqual([`${SRC}:team`]);+ }, 120_000);++ test('a hand-edited access.approved does not widen: the removal stays held and the file is reported', async () => {+ writePolicy(root, POLICY([]));+ writePolicy(root, POLICY([]), '.gbrain/access.approved');+ git(root, 'commit', '-q', '-am', 'remove everything by hand');+ const r = await syncAccessPolicyAt(engine, SRC, root);+ expect({ approved: r?.approved_file, held: r?.proposal?.held.map(h => h.rule) }).toEqual({ approved: 'untrusted', held: ['team'] });+ expect((await policyStatus(engine, SRC)).rules.map(r => r.id)).toEqual(['team']);+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example']]));+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example']]), '.gbrain/access.approved');+ git(root, 'commit', '-q', '-am', 'restore');+ await syncAccessPolicyAt(engine, SRC, root);+ expect((await policyStatus(engine, SRC)).held).toEqual([]);+ }, 120_000);++ test('a malformed file keeps the applied rules and hides the prefixes it names; an unparseable one hides the source', async () => {+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example'], ['hr', 'hr/', 'Not Valid']]));+ git(root, 'commit', '-q', '-am', 'bad readers');+ const r = await syncAccessPolicyAt(engine, SRC, root);+ expect(r?.state).toBe('invalid');+ let s = await policyStatus(engine, SRC);+ expect({ rules: s.rules.map(x => x.id), invalid: s.invalid.map(c => c.prefix) }).toEqual({ rules: ['team'], invalid: ['hr/', 'partners/'] });+ expect((s.invalid[0]!.detail as { problems: Array<{ line: number }> }).problems[0]!.line).toBe(6);+ writePolicy(root, 'version: 1\nrules: [\n');+ git(root, 'commit', '-q', '-am', 'broken yaml');+ await syncAccessPolicyAt(engine, SRC, root);+ s = await policyStatus(engine, SRC);+ expect(s.invalid.map(c => c.prefix)).toEqual(['']);+ writePolicy(root, POLICY([['team', 'partners/', 'alice-example, bob-example']]));+ git(root, 'commit', '-q', '-am', 'fixed');+ await syncAccessPolicyAt(engine, SRC, root);+ expect((await policyStatus(engine, SRC)).invalid).toEqual([]);+ }, 120_000);++ test('gbrain access rule add on a git source commits access.yml through the door and applies it at once', async () => {+ const r = await cli(engine, ['rule', 'add', '--source', SRC, '--prefix', 'partners/alice-example/', '--readers', 'alice-example', '--id', 'alice', '--yes']);+ expect({ store: r.store, state: r.state, outcome: r.git.outcome, path: r.git.path }).toEqual({ store: 'git', state: 'applied', outcome: 'committed_local', path: POLICY_FILE });+ expect(readCommittedPolicy(root).yml).toContain('id: alice');+ expect(git(root, 'status', '--porcelain')).toBe('');+ expect((await stamps(engine))['partners/alice-example/plan']).toEqual([`${SRC}:alice`, `${SRC}:team`]);+ }, 120_000);++ test('a busy commit lock refuses after one retry and leaves the file as it was', async () => {+ const lock = acquireCommitLock(root);+ try {+ await withEnv({ GBRAIN_COMMIT_LOCK_WAIT_SECONDS: '0' }, async () => {+ expect(() => commitPolicyFile(root, POLICY_FILE, () => 'version: 1\nrules: []\n', 'should not land')).toThrow(expect.objectContaining({ code: 'commit_lock_busy' }));+ });+ } finally { lock.release(); }+ expect(readCommittedPolicy(root).yml).toContain('id: alice');+ expect(git(root, 'status', '--porcelain')).toBe('');+ }, 60_000);++ test('a rebuilt database reaches the same applied rules from git alone', async () => {+ const before = (await policyStatus(engine, SRC)).rules;+ const fresh = await seedBrain(spares[1]!, root);+ await sync(fresh, root, true);+ expect((await policyStatus(fresh, SRC)).rules).toEqual(before);+ expect(await stamps(fresh)).toEqual(await stamps(engine));+ }, 120_000);++ test('the persisted store survives a removed .git: rules stay applied and edits refuse access_policy_store_mismatch', async () => {+ renameSync(join(root, '.git'), join(root, '.git-away'));+ try {+ await expect(runAccessRules(engine, 'rule', ['add', '--source', SRC, '--prefix', 'x/', '--readers', 'alice-example', '--yes'], true)).rejects.toMatchObject({ code: 'access_policy_store_mismatch' });+ const s = await policyStatus(engine, SRC);+ expect({ store: s.store, rules: s.rules.map(r => r.id) }).toEqual({ store: 'git', rules: ['alice', 'team'] });+ } finally { renameSync(join(root, '.git-away'), join(root, '.git')); }+ }, 60_000);++ test('rule migrate moves the rules to the database and back with no rule missing at any phase', async () => {+ const rules = (await policyStatus(engine, SRC)).rules;+ const toDb = await cli(engine, ['rule', 'migrate', '--source', SRC, '--yes']);+ expect({ to: toDb.to, phase: toDb.phase }).toEqual({ to: 'database', phase: 'switched' });+ expect((await policyStatus(engine, SRC)).rules).toEqual(rules);+ writePolicy(root, POLICY([]));+ git(root, 'commit', '-q', '-am', 'ignored while the database is the record');+ expect((await syncAccessPolicyAt(engine, SRC, root))?.state).toBe('skipped');+ expect((await policyStatus(engine, SRC)).rules).toEqual(rules);+ const toGit = await cli(engine, ['rule', 'migrate', '--source', SRC, '--yes']);+ expect({ to: toGit.to, phase: toGit.phase, sync: toGit.receipts.sync }).toEqual({ to: 'git', phase: 'switched', sync: 'unchanged' });+ expect(readCommittedPolicy(root).yml).toContain('id: alice');+ expect((await policyStatus(engine, SRC)).rules).toEqual(rules);+ }, 120_000);++ test('a commit with a bare remote pushes, and two sources in one repo each read their own root', async () => {+ const bare = mkdtempSync(join(tmpdir(), 'gbrain-frgit-bare-'));+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-frgit-two-'));+ try {+ git(bare, 'init', '-q', '--bare', '-b', 'main');+ git(repo, 'init', '-q', '-b', 'main');+ git(repo, 'config', 'user.email', '[email protected]');+ git(repo, 'config', 'user.name', 't');+ for (const sub of ['sub-a', 'sub-b']) writePage(join(repo, sub), 'partners/x/plan');+ writePolicy(join(repo, 'sub-a'), POLICY([['x', 'partners/x/', 'alice-example']]));+ git(repo, 'add', '-A');+ git(repo, 'commit', '-q', '-m', 'two sources');+ git(repo, 'remote', 'add', 'origin', bare);+ git(repo, 'push', '-q', '-u', 'origin', 'main');+ const e = await seedBrain(spares[2]!, join(repo, 'sub-a'));+ {+ await e.executeRaw("INSERT INTO sources (id, name, local_path, config) VALUES ('gt-b', 'gt-b', $1, '{}')", [join(repo, 'sub-b')]);+ expect((await syncAccessPolicyAt(e, SRC, join(repo, 'sub-a')))?.state).toBe('applied');+ expect((await syncAccessPolicyAt(e, 'gt-b', join(repo, 'sub-b')))?.state).toBe('skipped');+ const r = await cli(e, ['rule', 'add', '--source', 'gt-b', '--prefix', 'partners/x/', '--readers', 'bob-example', '--yes']);+ expect({ store: r.store, outcome: r.git.outcome }).toEqual({ store: 'git', outcome: 'pushed' });+ expect(existsSync(join(repo, 'sub-b', POLICY_FILE))).toBe(true);+ expect(git(bare, 'log', '-1', '--format=%s', 'main')).toContain('partners/x/');+ expect((await policyStatus(e, SRC)).rules.map(x => x.readable_by)).toEqual([['member:alice-example']]);+ expect((await policyStatus(e, 'gt-b')).rules.map(x => x.readable_by)).toEqual([['member:bob-example']]);+ }+ } finally { rmSync(bare, { recursive: true, force: true }); rmSync(repo, { recursive: true, force: true }); }+ }, 120_000);+});diff --git a/test/access-folder-rules.test.ts b/test/access-folder-rules.test.tsnew file mode 100644index 0000000000..7576bb6bcc--- /dev/null+++ b/test/access-folder-rules.test.ts@@ -0,0 +1,404 @@+/**+ * GBRA-218 (PR A2): per-folder read access, the database store and the predicate.+ *+ * 1. Protects: a page under a folder rule is read remotely only by a credential+ * whose member satisfies every rule whose prefix the slug starts with+ * (nested member and group rules both pass); unbound credentials, other+ * members, granted_sources bots and both escape hatches read nothing there.+ * Narrowing applies at once; widening (a rule removed, readers added) is+ * held until a previewed, hash-bound gbrain access apply. Pages under a+ * narrowing still being stamped read as nobody.+ * 2. Fails when: a folder-ruled page leaks to an unlisted caller on a read+ * path or under a hatch; a widening applies without approval; an+ * interrupted narrowing leaves pages readable under the old rules; a page+ * written, renamed or derived during or after an apply escapes its rules.+ * 3. Existing coverage (member-read-access) pins page-level readable_by only.+ * 4. Real seams: tokens minted by the token service, verified by the serve+ * --http verifier, dispatched through MCP dispatch; rule edits through the+ * CLI module and the policy engine; a repo-less brain (no git checkout, the+ * default keyless install), and Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { 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 { parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.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 type { AuthInfo } from '../src/core/ops/contract.ts';+import { classifyRulebook, folderRulesAllow, matchingRuleIds, parsePolicyYaml, ruleIdForPrefix, serializePolicyYaml, type FolderRule } from '../src/core/access/folder-rules.ts';+import { applyApproved, policySeams, policyStatus, previewApply, proposeRevision, resumePolicy } from '../src/core/access/policy.ts';+import { runAccessRules } from '../src/commands/access-rules.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.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 rule = (id: string, prefix: string, readers: string[]): FolderRule => ({ id, prefix, readable_by: readers.map(r => (r.includes(':') ? r : `member:${r}`)).sort() });++describe('folder-rule grammar', () => {+ test('a valid file parses, omitted ids derive from the prefix, and serialize round-trips', () => {+ const parsed = parsePolicyYaml('version: 1\nrules:\n - prefix: partners/alice-example/\n readable_by: [alice-example, group:team-a]\n - id: team\n prefix: partners/\n readable_by: group:team-a\n');+ expect(parsed).toEqual({ ok: true, rules: [rule('partners-alice-example', 'partners/alice-example/', ['alice-example', 'group:team-a']), rule('team', 'partners/', ['group:team-a'])] });+ if (!parsed.ok) throw new Error('unreachable');+ expect(parsePolicyYaml(serializePolicyYaml(parsed.rules))).toEqual(parsed);+ expect(ruleIdForPrefix('a/'.repeat(40)).length).toBeLessThanOrEqual(64);+ expect(parsePolicyYaml('')).toEqual({ ok: true, rules: [] });+ });++ test('patterns, upper case, missing slashes, traversal, bad readers and duplicates are refused with a line', () => {+ const bad = (text: string) => { const p = parsePolicyYaml(text); if (p.ok) throw new Error(`accepted: ${text}`); return p; };+ for (const prefix of ['partners/*/', 'Partners/', 'partners', '../x/', '/partners/', 'a//b/']) {+ expect(bad(`version: 1\nrules:\n - prefix: "${prefix}"\n readable_by: alice-example\n`).problems[0]!.line).toBe(3);+ }+ expect(bad('version: 1\nrules:\n - prefix: notes/\n readable_by: [Not Valid]\n').prefixes).toEqual(['notes/']);+ const dup = bad('version: 1\nrules:\n - id: a\n prefix: x/\n readable_by: alice-example\n - id: a\n prefix: y/\n readable_by: alice-example\n');+ expect(dup.problems.map(p => p.message).join(' ')).toContain('appears twice');+ expect(bad('rules: [').prefixes).toBeNull();+ expect(bad('version: 2\nrules: []\n').problems[0]!.message).toContain('version');+ });++ test('classification: additions and removed readers narrow; removals, added readers and moved prefixes are held; the target is never wider', () => {+ const applied = [rule('a', 'x/', ['alice-example', 'bob-example']), rule('b', 'y/', ['alice-example']), rule('c', 'z/', ['alice-example'])];+ const desired = [rule('a', 'x/', ['alice-example', 'carol-example']), rule('c', 'w/', ['alice-example']), rule('d', 'v/', ['bob-example'])];+ const cls = classifyRulebook(applied, desired);+ expect(cls.changes.map(c => `${c.rule}:${c.kind}:${c.narrowing}`).sort()).toEqual(['a:readers_added:false', 'a:readers_removed:true', 'b:removed:false', 'c:prefix_moved:false', 'd:added:true']);+ expect(cls.target).toEqual([rule('a', 'x/', ['alice-example']), rule('b', 'y/', ['alice-example']), rule('c', 'z/', ['alice-example']), rule('d', 'v/', ['bob-example'])]);+ expect(cls.kind).toBe('mixed');+ expect(classifyRulebook([], desired).kind).toBe('narrowing');+ expect(classifyRulebook(desired, desired).kind).toBe('unchanged');+ });+});++const SRC = 'fr-team';+const SRC2 = 'fr-other';+const PAGES = {+ alicePlan: { slug: 'partners/alice-example/plan', source: SRC, canary: 'canaryfralice' },+ teamNotes: { slug: 'partners/team/notes', source: SRC, canary: 'canaryfrteam' },+ open: { slug: 'notes/open', source: SRC, canary: 'canaryfropen' },+ summary: { slug: 'notes/summary', source: SRC, canary: 'canaryfrsummary', extra: 'derived_from: partners/alice-example/plan' },+ other: { slug: 'partners/alice-example/plan', source: SRC2, canary: 'canaryfrother' },+} as const;+type Key = keyof typeof PAGES;+const ALL = Object.keys(PAGES) as Key[];+const pageText = (title: string, canary: string, extra?: string) => ['---', 'type: note', `title: ${title}`, ...(extra ? [extra] : []), '---', `# ${title}`, '', `Folder ledger notes ${canary} for the roadmap.`].join('\n');++for (const kind of testBackends()) {+ describe(`folder access rules, database store (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let other: PGLiteEngine;+ 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>): Promise<{ isError: boolean; text: string }> {+ 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 } : {}),+ });+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n') };+ }++ /** The pages `who` reads, on each of get_page, keyword search, hybrid search and list_pages. */+ async function visible(who: string, keys: readonly Key[] = ALL): Promise<Record<string, Key[]>> {+ const out: Record<string, Key[]> = {};+ for (const key of keys) {+ const p = PAGES[key];+ const paths: Array<[string, string, Record<string, unknown>]> = [+ ['get_page', 'get_page', { slug: p.slug, source_id: p.source }],+ ['search keyword', 'search', { query: p.canary, match: 'keyword', fields: 'full', limit: 20 }],+ ['search hybrid', 'search', { query: `folder ledger notes ${p.canary}`, fields: 'full', limit: 50 }],+ ['list_pages', 'list_pages', { slug_prefix: p.slug.split('/')[0] + '/', source_id: p.source }],+ ];+ for (const [label, op, params] of paths) {+ const { text } = await call(who, op, params);+ const seen = label === 'list_pages' ? text.includes(p.slug) && (p.source === SRC2 ? text.includes(SRC2) : true) && !text.includes('"pages": []') && text.includes(p.slug) : text.includes(p.canary);+ if (seen) (out[label] ??= []).push(key);+ }+ }+ return out;+ }+ /** Keys read on every path (and nothing read only partially). */+ async function reads(who: string, keys: readonly Key[] = ALL): Promise<Key[]> {+ const v = await visible(who, keys);+ return keys.filter(k => ['get_page', 'search keyword'].every(l => v[l]?.includes(k)) || Object.values(v).some(ks => ks.includes(k)));+ }++ async function stamps(): Promise<Record<string, string[] | null>> {+ const rows = await engine.executeRaw<{ source_id: string; slug: string; folder_rule_ids: string[] | null }>(+ 'SELECT source_id, slug, folder_rule_ids FROM pages WHERE source_id = ANY($1::text[]) ORDER BY source_id, slug', [[SRC, SRC2]]);+ return Object.fromEntries(rows.map(r => [`${r.source_id}:${r.slug}`, r.folder_rule_ids]));+ }++ async function cli(args: string[]): Promise<unknown> {+ const lines: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });+ try { await runAccessRules(engine, args[0]!, args.slice(1), args.includes('--json')); } finally { spy.mockRestore(); }+ const text = lines.join('\n');+ return args.includes('--json') ? JSON.parse(text) : text;+ }++ const NESTED = [rule('team', 'partners/', ['group:team-a']), rule('alice', 'partners/alice-example/', ['alice-example'])];+ const BASE = [...NESTED, rule('shared', 'partners/team/', ['bob-example', 'carol-example'])];++ 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(); }+ other = new PGLiteEngine(); await other.connect({ engine: 'pglite' } as never); await other.initSchema();+ __resetPrivateVisibilityCacheForTests();+ for (const s of [SRC, SRC2]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [s]);+ for (const key of ALL) {+ const p = PAGES[key];+ await importFromContent(engine, p.slug, pageText(key, p.canary, 'extra' in p ? p.extra : undefined), { sourceId: p.source });+ }+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);+ await engine.executeRaw("INSERT INTO access_groups (id) VALUES ('team-a')");+ for (const m of ['alice-example', 'bob-example']) await engine.executeRaw("INSERT INTO access_group_members (group_id, member_id) VALUES ('team-a', $1)", [m]);+ const mint = async (name: string, member?: string) => {+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC, SRC2] });+ tokens[name] = minted.token;+ if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ };+ await mint('alice', 'alice-example');+ await mint('bob', 'bob-example');+ await mint('carol', 'carol-example');+ await mint('unbound');+ }, 240_000);++ afterAll(async () => {+ policySeams.afterInstall = undefined;+ await other?.disconnect();+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('control: with no folder rule every caller reads every page and nothing is stamped', async () => {+ for (const who of ['alice', 'bob', 'carol', 'unbound']) expect({ who, keys: await reads(who) }).toEqual({ who, keys: ALL });+ expect(Object.values(await stamps()).every(v => v === null)).toBe(true);+ }, 240_000);++ test('a narrowing applies at once: nested group and member rules both have to pass, and other sources and folders are untouched', async () => {+ const r = await proposeRevision(engine, SRC, NESTED, { origin: 'cli', store: 'database' });+ expect({ state: r.state, kind: r.change_kind, held: r.held }).toEqual({ state: 'applied', kind: 'narrowing', held: [] });+ expect(await stamps()).toEqual({+ [`${SRC}:notes/open`]: null, [`${SRC}:notes/summary`]: null,+ [`${SRC}:partners/alice-example/plan`]: [`${SRC}:alice`, `${SRC}:team`],+ [`${SRC}:partners/team/notes`]: [`${SRC}:team`],+ [`${SRC2}:partners/alice-example/plan`]: null,+ });+ const [state] = await engine.executeRaw<{ store: string }>("SELECT config->>'access_store' AS store FROM sources WHERE id = $1", [SRC]);+ expect(state?.store).toBe('database');+ expect(await reads('alice')).toEqual(['alicePlan', 'teamNotes', 'open', 'other']);+ expect(await reads('bob')).toEqual(['teamNotes', 'open', 'other']);+ for (const who of ['carol', 'unbound']) expect({ who, keys: await reads(who) }).toEqual({ who, keys: ['open', 'other'] });+ }, 240_000);++ test('a page derived from a folder-ruled page is readable by no remote caller, members included (D4)', async () => {+ for (const who of ['alice', 'bob', 'unbound']) expect({ who, keys: await reads(who, ['summary']) }).toEqual({ who, keys: [] });+ }, 120_000);++ test('no escape hatch or granted_sources opens a folder rule', async () => {+ const arms: Array<[string, (fn: () => Promise<void>) => Promise<void>]> = [+ ['GBRAIN_REMOTE_PRIVATE_PAGES=1', fn => withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, fn)],+ ['search.remote_private_pages=visible', async fn => {+ await engine.setConfig('search.remote_private_pages', 'visible'); __resetPrivateVisibilityCacheForTests();+ try { await fn(); } finally { await engine.setConfig('search.remote_private_pages', 'hidden'); __resetPrivateVisibilityCacheForTests(); }+ }],+ ['granted_sources', async fn => {+ for (const who of ['bob', 'carol', 'unbound']) await rescopeLegacyToken(engine, parseRescopeTokenArgs([who, '--private-pages', 'granted-sources']));+ try { await fn(); } finally { for (const who of ['bob', 'carol', 'unbound']) await rescopeLegacyToken(engine, parseRescopeTokenArgs([who, '--private-pages', 'none'])); }+ }],+ ];+ for (const [name, run] of arms) {+ await run(async () => {+ expect({ name, bob: await reads('bob', ['alicePlan', 'teamNotes']) }).toEqual({ name, bob: ['teamNotes'] });+ for (const who of ['carol', 'unbound']) expect({ name, who, keys: await reads(who, ['alicePlan', 'teamNotes', 'summary']) }).toEqual({ name, who, keys: [] });+ });+ }+ }, 240_000);++ test('a rule in a second source with the same prefix is its own rule (source-qualified ids)', async () => {+ await proposeRevision(engine, SRC2, [rule('alice', 'partners/alice-example/', ['carol-example'])], { origin: 'cli', store: 'database' });+ expect((await stamps())[`${SRC2}:partners/alice-example/plan`]).toEqual([`${SRC2}:alice`]);+ expect(await reads('carol', ['alicePlan', 'other'])).toEqual(['other']);+ expect(await reads('alice', ['alicePlan', 'other'])).toEqual(['alicePlan']);+ }, 120_000);++ test('removing readers applies at once; adding them back is held until a hash-bound apply', async () => {+ expect((await proposeRevision(engine, SRC, [...NESTED, rule('shared', 'partners/team/', ['bob-example', 'carol-example'])], { origin: 'cli' })).state).toBe('applied');+ expect(await reads('bob', ['teamNotes'])).toEqual(['teamNotes']);+ const narrowed = await proposeRevision(engine, SRC, [...NESTED, rule('shared', 'partners/team/', ['carol-example'])], { origin: 'cli' });+ expect({ state: narrowed.state, kinds: narrowed.changes.map(c => c.kind) }).toEqual({ state: 'applied', kinds: ['readers_removed'] });+ expect(await reads('bob', ['teamNotes'])).toEqual([]);+ const widened = await proposeRevision(engine, SRC, BASE, { origin: 'cli' });+ expect({ state: widened.state, held: widened.held.map(h => h.kind) }).toEqual({ state: 'recorded', held: ['readers_added'] });+ expect(await reads('bob', ['teamNotes'])).toEqual([]);+ const preview = await previewApply(engine, SRC);+ expect(preview.widening.map(w => ({ rule: w.change.rule, pages: w.pages, gains: w.gains }))).toEqual([{ rule: 'shared', pages: 1, gains: ['bob-example'] }]);+ await expect(applyApproved(engine, SRC, { expect: 'not-the-plan' })).rejects.toMatchObject({ code: 'preview_changed' });+ expect(await reads('bob', ['teamNotes'])).toEqual([]);+ const applied = await applyApproved(engine, SRC, { expect: preview.plan_hash! });+ expect(applied.state).toBe('applied');+ expect(await reads('bob', ['teamNotes'])).toEqual(['teamNotes']);+ }, 240_000);++ test('a preview bound to one plan refuses once the desired rules move', async () => {+ await proposeRevision(engine, SRC, [NESTED[0]!], { origin: 'cli' });+ const preview = await previewApply(engine, SRC);+ expect(preview.widening[0]!.gains).toEqual(['bob-example']);+ await proposeRevision(engine, SRC, [NESTED[0]!, rule('extra', 'partners/extra/', ['alice-example'])], { origin: 'cli' });+ await expect(applyApproved(engine, SRC, { expect: preview.plan_hash! })).rejects.toMatchObject({ code: 'preview_changed' });+ expect(await reads('bob', ['alicePlan'])).toEqual([]);+ const back = await proposeRevision(engine, SRC, BASE, { origin: 'revert' });+ expect(back.held.map(h => `${h.rule}:${h.kind}`)).toEqual(['extra:removed']);+ await applyApproved(engine, SRC, { expect: (await previewApply(engine, SRC)).plan_hash! });+ expect((await policyStatus(engine, SRC)).held).toEqual([]);+ expect((await policyStatus(engine, SRC)).rules).toEqual(BASE.slice().sort((a, b) => a.id.localeCompare(b.id)));+ }, 240_000);++ test('pages written or renamed after the rules are stamped by the write itself', async () => {+ await importFromContent(engine, 'partners/alice-example/later', pageText('later', 'canaryfrlater'), { sourceId: SRC });+ await importFromContent(engine, 'notes/moving', pageText('moving', 'canaryfrmoving'), { sourceId: SRC });+ await engine.updateSlug('notes/moving', 'partners/alice-example/moved', { sourceId: SRC } as never);+ const s = await stamps();+ expect(s[`${SRC}:partners/alice-example/later`]).toEqual([`${SRC}:alice`, `${SRC}:team`]);+ expect(s[`${SRC}:partners/alice-example/moved`]).toEqual([`${SRC}:alice`, `${SRC}:team`]);+ const bob = await call('bob', 'search', { query: 'canaryfrmoving canaryfrlater', match: 'keyword', fields: 'full' });+ expect(bob.text).not.toContain('canaryfr');+ }, 120_000);++ test('an interrupted narrowing reads as nobody under its prefix (derivatives too) until resume finishes it', async () => {+ await importFromContent(engine, 'clients/acme-example/brief', pageText('brief', 'canaryfrbrief'), { sourceId: SRC });+ await importFromContent(engine, 'notes/brief-summary', pageText('brief summary', 'canaryfrbriefsum', 'derived_from: clients/acme-example/brief'), { sourceId: SRC });+ const ok = async (who: string, canary: string) => (await call(who, 'search', { query: canary, match: 'keyword', fields: 'full' })).text.includes(canary);+ expect(await ok('alice', 'canaryfrbrief')).toBe(true);+ policySeams.afterInstall = () => { throw new Error('interrupted'); };+ try {+ await expect(proposeRevision(engine, SRC, [...BASE, rule('acme', 'clients/acme-example/', ['alice-example'])], { origin: 'cli' })).rejects.toThrow('interrupted');+ } finally { policySeams.afterInstall = undefined; }+ const status = await policyStatus(engine, SRC);+ expect(status.pending.map(p => p.prefix)).toEqual(['clients/acme-example/']);+ expect((await stamps())[`${SRC}:clients/acme-example/brief`]).toBeNull();+ expect(await ok('alice', 'canaryfrbrief')).toBe(false);+ expect(await ok('alice', 'canaryfrbriefsum')).toBe(false);+ expect(await ok('alice', 'canaryfropen')).toBe(true);+ const notice = await call('alice', 'search', { query: 'canaryfrbrief', match: 'keyword' });+ expect(notice.text).toContain('access_policy_pending');+ await importFromContent(engine, 'clients/acme-example/during', pageText('during', 'canaryfrduring'), { sourceId: SRC });+ expect((await stamps())[`${SRC}:clients/acme-example/during`]).toEqual([`${SRC}:acme`]);+ const resumed = await resumePolicy(engine, SRC);+ expect(resumed.pending_before).toEqual(['clients/acme-example/']);+ expect((await policyStatus(engine, SRC)).pending).toEqual([]);+ expect((await stamps())[`${SRC}:clients/acme-example/brief`]).toEqual([`${SRC}:acme`]);+ expect(await ok('alice', 'canaryfrbrief')).toBe(true);+ expect(await ok('bob', 'canaryfrbrief')).toBe(false);+ expect(await ok('alice', 'canaryfrbriefsum')).toBe(false);+ }, 240_000);++ test('a lost reply is reconciled by operation id; a raced preview refuses', async () => {+ const desired = [...(await policyStatus(engine, SRC)).desired!.rules, rule('ops', 'ops/', ['alice-example'])];+ const first = await proposeRevision(engine, SRC, desired, { origin: 'cli', operationId: 'acc_test-1' });+ const again = await proposeRevision(engine, SRC, desired, { origin: 'cli', operationId: 'acc_test-1' });+ expect({ reconciled: again.reconciled, revision: again.revision }).toEqual({ reconciled: true, revision: first.revision });+ expect((await policyStatus(engine, SRC, 'acc_test-1')).operation).toEqual({ operation_id: 'acc_test-1', revision: first.revision, state: 'applied' });+ await expect(proposeRevision(engine, SRC, desired.slice(1), { origin: 'cli', expectDesired: first.revision! - 1 })).rejects.toMatchObject({ code: 'preview_changed' });+ }, 120_000);++ test('the CLI previews by default, writes with --yes, refuses an invalid rule and holds a removal', async () => {+ const before = (await policyStatus(engine, SRC)).desired!.revision;+ const preview = await cli(['rule', 'add', '--source', SRC, '--prefix', 'hr/', '--readers', 'carol-example,ghost-example', '--json']) as { applied: boolean; expect: number; unknown_readers: string[]; changes: unknown[] };+ expect({ applied: preview.applied, expect: preview.expect, unknown: preview.unknown_readers }).toEqual({ applied: false, expect: before, unknown: ['ghost-example'] });+ expect((await policyStatus(engine, SRC)).desired!.revision).toBe(before);+ const text = await cli(['rule', 'add', '--source', SRC, '--prefix', 'hr/', '--readers', 'carol-example']) as string;+ expect(text.split('\n').at(-1)).toContain(`Nothing written. To approve, add --yes --expect ${before}`);+ const done = await cli(['rule', 'add', '--source', SRC, '--prefix', 'hr/', '--readers', 'carol-example', '--yes', '--expect', String(before), '--json']) as { state: string; applied: boolean; store: string; operation_id: string };+ expect({ state: done.state, applied: done.applied, store: done.store }).toEqual({ state: 'applied', applied: true, store: 'database' });+ await expect(cli(['rule', 'add', '--source', SRC, '--prefix', 'HR/*', '--readers', 'carol-example', '--yes'])).rejects.toMatchObject({ code: 'access_rule_invalid' });+ const rm = await cli(['rule', 'rm', 'hr', '--source', SRC, '--yes', '--json']) as { state: string; held: Array<{ kind: string }> };+ expect({ state: rm.state, held: rm.held.map(h => h.kind) }).toEqual({ state: 'recorded', held: ['removed'] });+ expect((await policyStatus(engine, SRC)).rules.some(r => r.id === 'hr')).toBe(true);+ const history = await cli(['rule', 'history', '--source', SRC, '--json']) as { revisions: Array<{ revision: number; approved_at: string | null }> };+ expect(history.revisions[0]!.approved_at).toBeNull();+ const apply = await cli(['apply', '--source', SRC, '--json']) as { plan_hash: string; widening: Array<{ change: { rule: string } }> };+ expect(apply.widening.map(w => w.change.rule)).toEqual(['hr']);+ await cli(['apply', '--source', SRC, '--yes', '--expect', apply.plan_hash, '--json']);+ expect((await policyStatus(engine, SRC)).rules.some(r => r.id === 'hr')).toBe(false);+ }, 240_000);++ test('a remote write under .gbrain/ is refused and writes nothing', async () => {+ for (const slug of ['.gbrain/access', '.gbrain/access.yml']) {+ const out = await call('alice', 'put_page', { slug, content: '---\ntitle: x\n---\nversion: 1\n', request_id: crypto.randomUUID() });+ expect({ slug, isError: out.isError }).toEqual({ slug, isError: true });+ }+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE slug LIKE '.gbrain%'")).toEqual([]);+ }, 60_000);++ test('export carries the rules and import loads them into another repo-less brain, narrowing at once', async () => {+ const yml = await cli(['rule', 'export', '--source', SRC]) as string;+ const file = join(mkdtempSync(join(tmpdir(), 'gbrain-fr-')), 'access.yml');+ writeFileSync(file, yml);+ {+ await other.executeRaw("INSERT INTO sources (id, name) VALUES ('imported', 'imported')");+ await importFromContent(other, 'partners/team/notes', pageText('t', 'x'), { sourceId: 'imported' });+ const lines: string[] = [];+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });+ try { await runAccessRules(other, 'rule', ['import', '--file', file, '--source', 'imported', '--yes', '--json'], true); } finally { spy.mockRestore(); }+ expect(JSON.parse(lines.join('\n')).state).toBe('applied');+ const [row] = await other.executeRaw<{ ids: string[] }>("SELECT folder_rule_ids AS ids FROM pages WHERE slug = 'partners/team/notes'");+ expect(row?.ids).toEqual(['imported:shared', 'imported:team']);+ const parsed = parsePolicyYaml(yml);+ expect(parsed.ok && parsed.rules.map(r => r.id).sort()).toEqual((await policyStatus(engine, SRC)).desired!.rules.map(r => r.id).sort());+ }+ }, 120_000);++ test('property: the SQL predicate and the row helper agree on generated slugs, rules and identities', async () => {+ const src = 'fr-prop';+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [src]);+ const segs = ['a', 'b', 'c'];+ const slugs = [...new Set(segs.flatMap(x => segs.flatMap(y => [`${x}/${y}/p`, `${x}/p`])))];+ for (const s of slugs) await importFromContent(engine, s, pageText(s, 'prop'), { sourceId: src });+ const rules = [rule('ra', 'a/', ['group:team-a']), rule('rab', 'a/b/', ['alice-example']), rule('rc', 'c/', ['carol-example', 'bob-example']), rule('rcc', 'c/c/', ['group:team-a'])];+ await proposeRevision(engine, src, rules, { origin: 'cli', store: 'database' });+ const { folderAccessFor } = await import('../src/core/access/caller.ts');+ const { withCallerAccess, folderRulesAllowedSql } = await import('../src/core/search/private-visibility.ts');+ for (const identity of [[], ['member:alice-example', 'group:team-a'], ['member:bob-example', 'group:team-a'], ['member:carol-example']]) {+ const folder = await folderAccessFor(engine, identity);+ const sql = withCallerAccess({ identity, ...folder }, () => folderRulesAllowedSql('p', folder.satisfiedRuleIds));+ const rows = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages p WHERE source_id = $1 AND ${sql} ORDER BY slug`, [src]);+ const want = slugs.filter(s => folderRulesAllow(s, rules, identity)).sort();+ expect({ identity, got: rows.map(r => r.slug) }).toEqual({ identity, got: want });+ for (const s of slugs) expect(matchingRuleIds(s, rules)?.map(id => `${src}:${id}`) ?? null).toEqual((await stamps2(s)) ?? null);+ }+ async function stamps2(slug: string) {+ const [r] = await engine.executeRaw<{ ids: string[] | null }>('SELECT folder_rule_ids AS ids FROM pages WHERE source_id = $1 AND slug = $2', [src, slug]);+ return r?.ids ?? null;+ }+ }, 240_000);+ });+}diff --git a/test/access-folder-transfer.test.ts b/test/access-folder-transfer.test.tsnew file mode 100644index 0000000000..c4b11b7de5--- /dev/null+++ b/test/access-folder-transfer.test.ts@@ -0,0 +1,128 @@+/**+ * GBRA-218 (A2) folder rules across gbrain export and import, on repo-less+ * PGLite brains: an export carries the applied rulebook (never a held+ * widening), import installs it before publishing any page and keeps that+ * barrier across a failure and a rerun, several sources travel as+ * source-qualified files that import maps explicitly, and a source whose+ * committed file is invalid refuses to export.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+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 { runExport } from '../src/commands/export.ts';+import { runImport } from '../src/commands/import.ts';+import { parsePolicyYaml } from '../src/core/access/folder-rules.ts';+import { appliedRules, clearPolicyInvalid, coverageRows, markPolicyInvalid, policySeams, proposeRevision } from '../src/core/access/policy.ts';+import { exportPolicyFiles } from '../src/core/access/policy-transfer.ts';++const page = (title: string) => ['---', 'type: note', 'title: ' + title, '---', '# ' + title, '', 'Body.'].join('\n');+const rule = (id: string, prefix: string, readers: string[]) => ({ id, prefix, readable_by: readers });+const ALICE = rule('alice', 'partners/alice-example/', ['member:alice-example']);++async function seedSources(e: BrainEngine, sources: string[]): Promise<BrainEngine> {+ for (const s of sources) await e.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [s]);+ return e;+}+const stamps = async (e: BrainEngine, source: string) => Object.fromEntries((await e.executeRaw<{ slug: string; folder_rule_ids: string[] | null }>(+ 'SELECT slug, folder_rule_ids FROM pages WHERE source_id = $1 ORDER BY slug', [source])).map(r => [r.slug, r.folder_rule_ids]));+const silenced = async <T>(fn: () => Promise<T>): Promise<T> => {+ const [log, err] = [console.log, console.error];+ console.log = () => {}; console.error = () => {};+ try { return await fn(); } finally { console.log = log; console.error = err; }+};++describe('folder rules across export and import (pglite, repo-less)', () => {+ let from: BrainEngine; let to: BrainEngine;+ const dirs: string[] = [];+ const fresh = () => { const d = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-access-x-'))); dirs.push(d); return d; };++ beforeAll(async () => {+ from = new PGLiteEngine(); await from.connect({ engine: 'pglite' } as never); await from.initSchema();+ to = new PGLiteEngine(); await to.connect({ engine: 'pglite' } as never); await to.initSchema();+ await seedSources(from, ['src-a', 'src-b', 'src-c']);+ await seedSources(to, ['dst', 'dst2']);+ await importFromContent(from, 'partners/alice-example/plan', page('Plan'), { sourceId: 'src-a', noEmbed: true });+ await importFromContent(from, 'notes/open', page('Open'), { sourceId: 'src-a', noEmbed: true });+ await importFromContent(from, 'partners/bob-example/deal', page('Deal'), { sourceId: 'src-b', noEmbed: true });+ await proposeRevision(from, 'src-a', [ALICE], { origin: 'cli', store: 'database' });+ await proposeRevision(from, 'src-a', [], { origin: 'cli' });+ await proposeRevision(from, 'src-b', [rule('partners', 'partners/', ['member:bob-example'])], { origin: 'cli', store: 'database' });+ await proposeRevision(from, 'src-c', [rule('partners', 'partners/', ['member:carol-example'])], { origin: 'cli', store: 'database' });+ }, 120_000);+ afterAll(async () => {+ policySeams.afterInstall = undefined;+ await from.disconnect(); await to.disconnect();+ for (const d of dirs) rmSync(d, { recursive: true, force: true });+ });++ test('a one-source export carries the applied rulebook, not the held widening', async () => {+ const dir = fresh();+ await silenced(() => runExport(from, ['--dir', dir, '--source', 'src-a']));+ for (const f of ['.gbrain/access.yml', '.gbrain/access.approved']) {+ const parsed = parsePolicyYaml(readFileSync(join(dir, f), 'utf8'));+ expect(parsed.ok && parsed.rules).toEqual([ALICE]);+ }+ expect(existsSync(join(dir, 'partners/alice-example/plan.md'))).toBe(true);+ }, 60_000);++ test('import installs the rules before any page, across a failure and a rerun', async () => {+ const dir = fresh();+ await silenced(() => runExport(from, ['--dir', dir, '--source', 'src-a']));+ await importFromContent(to, 'partners/alice-example/old', page('Old'), { sourceId: 'dst', noEmbed: true });+ let seen = null as number | null;+ policySeams.afterInstall = async () => {+ seen = (await to.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE source_id = 'dst' AND slug = 'partners/alice-example/plan'"))[0]!.n;+ throw new Error('interrupted');+ };+ try { await expect(silenced(() => runImport(to, [dir, '--source', 'dst', '--no-embed']))).rejects.toThrow('folder rules not installed'); }+ finally { policySeams.afterInstall = undefined; }+ expect(seen).toBe(0);+ expect(Object.keys(await stamps(to, 'dst'))).toEqual(['partners/alice-example/old']);+ expect((await coverageRows(to, 'dst')).map(c => [c.prefix, c.reason])).toEqual([['partners/alice-example/', 'pending']]);+ expect(await appliedRules(to, 'dst')).toEqual([ALICE]);++ await silenced(() => runImport(to, [dir, '--source', 'dst', '--no-embed']));+ expect(await stamps(to, 'dst')).toEqual({ 'notes/open': null, 'partners/alice-example/old': ['dst:alice'], 'partners/alice-example/plan': ['dst:alice'] });+ expect(await coverageRows(to, 'dst')).toEqual([]);+ }, 60_000);++ test('several sources travel as source-qualified files, including one with no page, and import maps them explicitly', async () => {+ const dir = fresh();+ await silenced(() => runExport(from, ['--dir', dir]));+ expect(existsSync(join(dir, '.gbrain/access.yml'))).toBe(false);+ const qualified = (s: string) => { const p = parsePolicyYaml(readFileSync(join(dir, '.gbrain/access', s + '.yml'), 'utf8')); return p.ok ? p.rules : p.problems; };+ expect(qualified('src-a')).toEqual([ALICE]);+ expect(qualified('src-b')).toEqual([rule('partners', 'partners/', ['member:bob-example'])]);+ expect(qualified('src-c')).toEqual([rule('partners', 'partners/', ['member:carol-example'])]);++ await expect(silenced(() => runImport(to, [dir, '--source', 'dst2', '--no-embed']))).rejects.toThrow('folder rules not installed');+ expect(await stamps(to, 'dst2')).toEqual({});+ expect(await appliedRules(to, 'dst2')).toEqual([]);++ await silenced(() => runImport(to, [dir, '--source', 'dst2', '--no-embed', '--access-policy', 'src-b']));+ expect(await appliedRules(to, 'dst2')).toEqual([rule('partners', 'partners/', ['member:bob-example'])]);+ const s = await stamps(to, 'dst2');+ expect(s['partners/bob-example/deal']).toEqual(['dst2:partners']);+ expect(s['partners/alice-example/plan']).toEqual(['dst2:partners']);+ expect(s['notes/open']).toBeNull();+ }, 60_000);++ test('an imported rulebook that widens what the destination has is held', async () => {+ const dir = fresh();+ await silenced(() => runExport(from, ['--dir', dir, '--source', 'src-b']));+ await silenced(() => runImport(to, [dir, '--source', 'dst', '--no-embed']));+ expect(await appliedRules(to, 'dst')).toEqual([ALICE, rule('partners', 'partners/', ['member:bob-example'])].sort((x, y) => x.id.localeCompare(y.id)));+ }, 60_000);++ test('a source whose committed file is invalid refuses to export its rules', async () => {+ await markPolicyInvalid(from as never, 'src-c', ['hr/'], { problems: [{ line: 3, message: 'bad' }] });+ await expect(exportPolicyFiles(from, 'src-c')).rejects.toMatchObject({ code: 'access_policy_invalid' });+ await expect(exportPolicyFiles(from, null)).rejects.toMatchObject({ code: 'access_policy_invalid' });+ await clearPolicyInvalid(from, 'src-c');+ expect((await exportPolicyFiles(from, null)).map(f => f.path)).toEqual(['.gbrain/access/src-a.yml', '.gbrain/access/src-b.yml', '.gbrain/access/src-c.yml']);+ }, 60_000);+});diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex e915286550..5e461d46ab 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -369,6 +369,22 @@"category": "brain","name": "access_page_readers_backfill"},+ {+ "category": "brain",+ "name": "access_policy_pending"+ },+ {+ "category": "brain",+ "name": "access_policy_widening_held"+ },+ {+ "category": "brain",+ "name": "access_policy_invalid"+ },+ {+ "category": "brain",+ "name": "access_policy_store_mismatch"+ },{"category": "ops","name": "rls"diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 1194f42d96..0bcf504bf2 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -13,6 +13,7 @@# themselves from scripts/postgres-arm-weights.json.test/access-as.test.tstest/access-binding.test.ts+test/access-folder-rules.test.tstest/access-members.test.tstest/access-writes.test.tstest/activation-unbound-rooted-6449.test.ts