Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Hold a fact for a page-less entity under a folder rule on the folder's own holding page in Git (GST-2492)
garrytanb5d033c778ed
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f07510569f..1ec988edce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**On a strict source, a fact for a page-less entity under a folder access rule now lives in Git on its folder's own holding page, with exactly the readers the entity's page would have.** On a source whose pages are canonical in Git (`canonical: git`), a fact saved for an entity that has no page yet is held as a row of `memory/unattributed` until the page exists. An entity under a folder access rule was the exception: naming it on that shared page would tell every reader the entity exists, so its fact stayed in the database only, and a rebuild from Git lost it. Now it is held on the holding page of the entity's own folder (`partners/memory/unattributed` for `partners/acme-example`). Every rule that covers the entity covers that page by path, so the fact has the same readers as the entity's page, nested and pending rules included, and it is stored the way the entity's page would be: committed to Git, or database-only under `storage.db_only` or a path Git ignores. A rule added later moves the held facts it covers off the shared page as part of its own apply, and `gbrain access rule add` lists them in its preview first. An entity under an exact page rule (a rule on its own slug) has no such page, so `remember` now refuses with `git_home_required` (reason `facts_lane`) and a fix that creates the page; when the database role cannot read the access rules, it answers `access_policy_pending` with `next: wait`. Sources that are not strict and brains with no Git repository work as before.++### Itemized changes++- `src/core/facts-fence.ts`: `isHoldingSlug` (the shared `memory/unattributed` or any `<folder>/memory/unattributed`), its SQL twin and `folderHoldingSlug`. A folder's holding page reads only entity cells of its own folder; any other is a fence problem.+- `src/core/facts/held-fact-move.ts`: `holdingHome` replaces `holdsInGit` and names the holding page, or refuses (`page_rule`, `access_unreadable`). `moveHeldFacts` reads every holding page, moves rows into entity pages, and re-homes shared-page rows whose entity a rule now covers; the shared page's row is removed, never struck with the destination.+- `src/core/persistence/memory-mutations.ts`, `memory-prepare.ts`, `facts-prepare.ts`, `facts-maintenance.ts`, `prepared-maintenance.ts`, `forget-prepare.ts`, `single-prepare.ts`, `page-identity.ts`, `model.ts`, `src/core/facts/*`, `src/core/trust/release-publish.ts`: every fact writer, forget, purge and release treats any holding page as a holding page.+- `src/core/persistence/git-declared.ts`, `verb-errors.ts`: the `facts_lane` refusal for an exact page rule carries a `put_page` fix; through `remember` it keeps the frozen `invalid_params` (and `unavailable` for `access_policy_pending`) with the canonical code, reason and fix.+- `src/core/persistence/coordinator.ts`: a held fact on a database-only folder's holding page reports `write_through: {written: false, skipped: db_only, held_for}` instead of `no_repo_configured`.+- `src/core/search/private-visibility.ts`: a held fact is also judged by its holding page as a page, so a raw-only rule (`covers_derived: false`) hides it as it hides the page; a fact still on `memory/unattributed` for an entity a rule now covers (a rule synced from Git, until maintenance moves it) reads only for that rule's readers, and for nobody while the rule is pending.+- `src/core/entities/resolve.ts`: a holding page under an entity directory (`people/memory/unattributed`) is never an entity page itself.+- `src/commands/access-rules.ts`: the rule preview lists `held_facts_moving` and the apply moves them (`held_facts: {moved, unmovable}`), for the database and git stores; `gbrain access apply` and `gbrain access resume` move them too. The shared page's earlier versions and Git history keep the row as it was; nothing rewrites history.+- `src/core/repair/facts-home.ts`, `src/core/facts/facts-home.ts`: `gbrain repair facts-home` writes a ruled entity's fact to its folder's page; `folder_restricted` now means only `page_rule` or `access_unreadable`.+- Docs: `git-canonical.md`, `entity-scoped-facts.md`, `access-designations.md`, `repair.md`, `write-refusals.md`, `memory-boundaries.md`, `MEMORY_VERBS_v1.md`, `error-codes.md` (regenerated).+- Tests: new `test/folder-holding-page-gst2492.test.ts` (held in Git before the reply and kept by a rebuild from a clone; three nested rules plus a pending one; no existence leak on get_page, search, query, recall, list_pages and find_pages; a raw-only rule; the rule apply's preview and move; the owner with the opt-in on and off; the page-rule and unreadable refusals locally and over MCP; database-only folders; background writers and repair; non-strict and repo-less unchanged); updated GST-2492 suites; PGLite and Postgres.+## [0.60.697.0] - 2026-11-12**A quarantined fact or take for a page that already exists is now held for review on a strict source, instead of failing.** With trust protections on (`write_gate.external_mode = quarantine`), a `remember` or `takes_add` of tool output that reads like an instruction is held for the owner's review (`write_held`, a ref such as `h1`). On a source whose pages are canonical in Git (`canonical: git`), that write failed when its page already existed (for a fact, also when it had no entity and `memory/unattributed` already existed). Nothing was saved and nothing was held, so the owner had nothing to review, and the caller was told storage failed: `remember` answered `unavailable` with `write_error: storage_error` ("The write did not commit"), and `takes_add` answered `git_home_required` with `write_error: storage_error`. Now the write is held there exactly as on any other source. Nothing of the held text reaches a fact or take row, a page or Git until the owner decides. Releasing a fact commits it to the page's file before its database row, so a database rebuilt from Git keeps it; a held take still cannot be released on any source, and the owner drops it (`gbrain trust drop h1`). Sources that are not strict and brains with no Git repository answer as before.diff --git a/docs/guides/access-designations.md b/docs/guides/access-designations.mdindex 21dc379471..f45d6fd407 100644--- a/docs/guides/access-designations.md+++ b/docs/guides/access-designations.md@@ -138,7 +138,10 @@ shared brain, and it binds the owner too: the owner reads such a page only whenturns on the owner opt-in (below). No grant or hatch relaxes it. Use it for a page that belongs to specific people in a shared brain; a single-user brain needsnone. The page's writers set it; on an existing page the brain host sets or removes it with`gbrain repair visibility --slug <page> --readers <list>` (or `--slugs-file`), which keeps the page's trust tier and-changes only that line ([how](repair.md)). Widening a folder rule waits for `gbrain access apply`. A credential bound to a+changes only that line ([how](repair.md)). Widening a folder rule waits for `gbrain access apply`. On a git-canonical+source, a fact held for an entity that has no page yet sits on the holding page of the entity's folder+(`<folder>/memory/unattributed`), which the folder's rules cover; a new rule's preview lists the held facts it would move+there (`held_facts_moving`) and its apply moves them (`held_facts` in the result) ([details](git-canonical.md#how-writes-reach-a-strict-source)). A credential bound to amember with `default` or a federated source as its write source gets it on the pages it creates there (`readable_by: [member:<id>]`),except the owner's, whose new pages stay shared (`POST /ingest` still refuses both). See[company brain, Model C](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape).diff --git a/docs/guides/entity-scoped-facts.md b/docs/guides/entity-scoped-facts.mdindex 2aedb07062..96fa2d5f18 100644--- a/docs/guides/entity-scoped-facts.md+++ b/docs/guides/entity-scoped-facts.md@@ -122,9 +122,16 @@ column names the entity, before the reply returns. The reply then nameshas a page, the next maintenance cycle moves the row into it in one commitand strikes the held row (`moved to <entity>`; a restricted page's held row isremoved instead); a page kept out of Git does not take it, and the run warns-`HELD_FACT_UNMOVABLE`. An entity under a folder access rule is not held: its-fact stays in the database, as on other sources. Forgetting or replacing a held fact strikes its row-too. A brain with no Git+`HELD_FACT_UNMOVABLE`. An entity under a folder access rule is held on its+folder's own holding page instead (`partners/memory/unattributed` for+`partners/acme-example`): the rules covering the entity cover that page by+path, so the fact has exactly the readers the entity's page would have, and a+folder kept out of Git keeps the page database-only. A rule added later moves+the held rows it covers there in its own apply; the shared page's row is then+removed, so the shared page never names the ruled entity. An entity under an+exact page rule is refused with `git_home_required` (reason `facts_lane`):+create its page with `put_page`, then remember the fact again. Forgetting or+replacing a held fact strikes its row too. A brain with no Gitrepository gets no notice: there the database is the record, and the fact isas safe as everything else in it.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 8d6a62a3d7..d1111ff749 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2116,7 +2116,7 @@ More: [docs/guides/concurrent-writes.md#git-durability-at-activation](../../docs| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A git-canonical source would store content in the database without a file in Git; nothing was written. | On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet. | Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id. | agent | `repeat the read that failed` | 1 | no |+| A git-canonical source would store content in the database without a file in Git; nothing was written. | On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet, or a fact for a page-less entity under an exact page rule, which no holding page can carry (create the page with put_page, then remember again). | Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id. | agent | `repeat the read that failed` | 1 | no |Reasons: `no_file_form`, `declared_target`, `facts_lane`.diff --git a/docs/guides/git-canonical.md b/docs/guides/git-canonical.mdindex fcbe6e9629..034796ed0f 100644--- a/docs/guides/git-canonical.md+++ b/docs/guides/git-canonical.md@@ -185,7 +185,22 @@ Every write goes through the same door, whoever sends it:a row for an entity names it in the `entity` column and moves into theentity's page once that page exists, including a name saved without afolder (`kofi-example`) once exactly one page such as- `people/kofi-example` carries it.+ `people/kofi-example` carries it. An entity under a folder access rule is+ held on its own folder's holding page instead (`partners/memory/unattributed`+ for `partners/acme-example`), which every rule covering the entity covers by+ path, so the row has exactly the readers the entity's page would have and is+ stored like it (in Git, or database-only under `storage.db_only` or a path+ Git ignores). A rule added later moves the held rows it covers there as part+ of its own apply (`gbrain access rule add` previews them as+ `held_facts_moving`; `gbrain access apply` and `gbrain access resume` move+ them too). A rule that arrives through a sync of the policy file moves them+ at the next maintenance cycle; until then the row stays in the shared page's+ body, while the fact itself reads only for the rule's readers. The shared+ page's earlier versions and its Git history keep the row as it was before+ the rule: gbrain never rewrites history. An entity under an exact page rule (a rule on the+ entity's own slug) has no holding page with its readers: the fact is refused+ with [`git_home_required`](write-refusals.md#git_home_required) (reason+ `facts_lane`) until the page exists.- **Remote MCP callers and thin clients** send a write request that thecheckout owner's door commits. The reply carries the revision once it iscommitted and indexed, or `write_pending` with a request id (exit 10 on the@@ -217,7 +232,7 @@ file is refused with [`git_home_required`](write-refusals.md#git_home_required).| Detached pages and origin twins | Kept database-only. || Derived data: chunks, embeddings, links and rows parsed from pages | Rebuilt from Git, never content of record. || Write receipts and other operational records | Kept in the database as metadata; Git commits don't carry them. |-| Facts for an entity under a folder access rule that has no page yet | Kept database-only: such an entity is never named on the world-readable `memory/unattributed` page. Doctor's `strict_facts_outside_git` counts them and `gbrain repair facts-home` lists them as `folder_restricted`. |+| Facts held for an entity under a folder that is database-only | Held on that folder's holding page, which is database-only like the entity's own page would be. |A file under a Git LFS rule is refused with `git_lfs_not_enabled` unless`storage.git_lfs` is on and the checkout configures the LFS filter; the door@@ -260,8 +275,9 @@ gbrain sources reindex <source-id> --from-git # preview the re-dergbrain sources reindex <source-id> --from-git --apply --expect <hash>```-Facts that were held on `memory/unattributed` come back from its file with the-entity they were saved for. Back up the database as well: Git does not hold the+Facts that were held on `memory/unattributed` or on a folder's holding page+(`<folder>/memory/unattributed`) come back from its file with the entity they+were saved for. Back up the database as well: Git does not hold thedatabase-only classes, the write receipts or the other operational records.## What doctor and status show@@ -269,7 +285,7 @@ database-only classes, the write receipts or the other operational records.| Where | What it tells you ||---|---|| `gbrain doctor` → `git_index_lag` | Per strict source, how many commits and seconds the index trails HEAD. It warns once the oldest unindexed commit is older than 900 s (`GBRAIN_DOCTOR_GIT_INDEX_LAG_WARN_SECONDS`), and its fix is `gbrain sync --source <id> --no-pull`. Until then, search and reads show the older version. |-| `gbrain doctor` → `strict_facts_outside_git` | Per strict source, the facts with no Git home, the facts held on `memory/unattributed` for more than 30 days, and held facts that cannot move (with the reason, or the candidate pages of a bare name). It warns when any is non-zero, and its fix is the read-only preview of [`gbrain repair facts-home`](repair.md#facts-home). A source that is not strict is not judged. |+| `gbrain doctor` → `strict_facts_outside_git` | Per strict source, the facts with no Git home, the facts held on a holding page for more than 30 days, and held facts that cannot move (with the reason, or the candidate pages of a bare name). It warns when any is non-zero, and its fix is the read-only preview of [`gbrain repair facts-home`](repair.md#facts-home). A source that is not strict is not judged. || `gbrain doctor` → `db_ahead_of_git` | The git-gap totals for every source with a checkout, strict or not, with each source's live pages (a scan the budget stopped reads `PARTIAL, <read> of <live> live page(s) read`). Informational: always ok. Bounded by `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (10 s by default). || `gbrain sources git-gap <id> [--sample n] [--json]` | Each page's state against HEAD: `equal`, `database_ahead`, `git_ahead`, declared or undeclared database-only, `worktree_only`, `unparseable`, `unsafe_path`, with a sample of paths, the source's `live_pages`, and `direction_evidence` for differing pages with no import record. Read-only. || `gbrain sources reindex <id> --from-git` | A preview of every database version Git would replace, bound to HEAD by a hash; `--apply --expect <hash>` runs that pass. Use it to re-derive a strict source's index on purpose. |diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 0fc053529e..a20fca8fd0 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -491,9 +491,10 @@ What one purge does, in one transaction:stored page body and from every saved page version, then rebuilds that page'schunks; the canonical file is rewritten by the owner and committed as`gbrain: purge fact <hash8>` (no claim text in the commit). A purge of a- fact held on `memory/unattributed` for an entity with no page also drops- every copy of the same claim text on that page, whether it is held for- another entity or has no entity;+ fact held on a holding page (`memory/unattributed`, or a folder's+ `<folder>/memory/unattributed`) for an entity with no page also drops every+ copy of the same claim text on that page, whether it is held for another+ entity or has no entity;- redacts stored write intents that carry the claim (a write that is runningor recovering blocks the purge with `purge_blocked_pending_recovery` until itfinishes; retry with the same request id; a write still queued, or deferreddiff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 84f44af5f2..5275462753 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2809,11 +2809,11 @@ The preview puts each fact in one group:| Group | What the apply does ||---|---|-| `entity_page_missing` | Writes the fact to `memory/unattributed` as a held row that names its entity, in one commit. Once the entity has a page, the next maintenance cycle moves it there. |+| `entity_page_missing` | Writes the fact as a held row that names its entity, one commit per holding page: `memory/unattributed`, or for an entity under a folder access rule its folder's holding page (`<folder>/memory/unattributed`, which the rule covers). Once the entity has a page, the next maintenance cycle moves it there. || `no_entity` | Writes the fact to `memory/unattributed`. || `entity_page_exists` | Nothing: the entity has a page, and the next maintenance cycle (`gbrain dream`) moves the fact into it. || `cannot_render` | Nothing: the Facts table cannot show the fact as it stands (the class says why). It stays in the database, active and searchable. |-| `folder_restricted` | Nothing: the entity is under a folder access rule, so the fact is never named on the world-readable holding page. It stays in the database only. |+| `folder_restricted` | Nothing: an exact page rule covers the entity (`page_rule`: create the entity's page, then the next maintenance cycle moves the fact into it), or this database role cannot read the access rules (`access_unreadable`). It stays in the database only. || `entity_page_deleted` | Nothing: the entity's page is deleted (it may have been private, and purging it would not reach a row on the holding page). Restore the page or purge it; the fact stays in the database only. || `held_fact_unmovable` | Nothing: a held row whose page cannot take it, with the reason. `entity_ambiguous` names the pages a bare name could mean; save the fact again with the page slug and forget the held one. || `held_over_30_days` | Nothing: a held row whose entity still has no page after 30 days, with the nearest existing page gbrain finds. |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 32a3c75147..56d5ff09f1 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -1032,7 +1032,7 @@ Earlier commits keep whatever was pushed before the change; gbrain never rewrite| Code | What happened | What to do ||---|---|---|-| <a id="git_home_required"></a>`git_home_required` | The write would store content in the database with no file in Git and is in no declared class (`no_file_form`), a publication would commit a file for a declared page (`declared_target`), or a writer with no file form yet wrote to the source (`facts_lane`). Nothing was written. A fact for an entity with no page, or with no entity, is not refused this way: every fact writer commits it as a row of `memory/unattributed` instead. Nor is a fact or take the write gate holds for the owner's review, whatever page it names: it is refused `write_held` and nothing reaches a page or Git; releasing a held fact commits it to its page's file before its row. | Ask the user which git home to configure: write the page to a path Git tracks, declare its directory under `storage.db_only` in `gbrain.yml`, or mark it `visibility: private`. `gbrain sources git-gap <source> --json` shows every page's class. Submit again with a new request ID. |+| <a id="git_home_required"></a>`git_home_required` | The write would store content in the database with no file in Git and is in no declared class (`no_file_form`), a publication would commit a file for a declared page (`declared_target`), or a writer with no file form yet wrote to the source (`facts_lane`). Nothing was written. A fact for an entity with no page, or with no entity, is not refused this way: every fact writer commits it as a row of `memory/unattributed` instead, or of its folder's `<folder>/memory/unattributed` when a folder access rule covers the entity. The one exception is an entity with no page under an exact page rule (a rule on the entity's own slug): no holding page carries that rule's readers, so `remember` refuses with `facts_lane` and a fix that creates the page (`put_page`), after which the fact can be remembered again. Through `remember` the frozen `error` is `invalid_params` and `code` is `git_home_required`. Nor is a fact or take the write gate holds for the owner's review, whatever page it names: it is refused `write_held` and nothing reaches a page or Git; releasing a held fact commits it to its page's file before its row. | Ask the user which git home to configure: write the page to a path Git tracks, declare its directory under `storage.db_only` in `gbrain.yml`, or mark it `visibility: private`. `gbrain sources git-gap <source> --json` shows every page's class. Submit again with a new request ID. || <a id="git_private_commit_refused"></a>`git_private_commit_refused` | A publication would have committed the file bytes of a private, alias-private or lineage-private page. Nothing was written and `HEAD` is unchanged. A grouped publication refuses as a whole. | The page stays database-only. Write it with `put_page`, which publishes a private page without a file, or remove `visibility: private` if it belongs in Git. || <a id="git_protocol_required"></a>`git_protocol_required` | A database trigger refused a row on a strict source because the writing process does not declare the git-canonical protocol: an older gbrain, or `gbrain.write_sources` set by hand. Nothing was written. | Upgrade (`gbrain upgrade`) or stop every gbrain process that shares the database, then retry with a new request ID. || <a id="git_lfs_not_enabled"></a>`git_lfs_not_enabled` | The file falls under a Git LFS rule in `.gitattributes`, and either `storage.git_lfs` is off (`opt_in_off`, the default) or the checkout does not configure the LFS filter or git-lfs does not run (`checkout_unconfigured`). Nothing was written. | Ask the user. To store it with LFS: `git lfs install --local` in the checkout, then `gbrain config set storage.git_lfs true`. Otherwise narrow the `.gitattributes` rule. With the key on and LFS configured, the door commits the LFS pointer and the object goes to the checkout's LFS store; a publication that rolls back can leave an unreferenced object there, which is harmless. |@@ -1049,7 +1049,7 @@ same on a repo-less brain and on a git-backed one.| <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. In a partial clone (`git clone --filter`), a policy file or an earlier version of it that the clone never fetched makes the whole source read as nobody the same way, because sync fetches nothing. | `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`. In a partial clone, run the `git cat-file -p` or `git log -p` the problem names in the checkout, which fetches what is missing, then sync the same way. |-| <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. |+| <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. On a git-canonical source, a `remember` for an entity with no page whose access rules this database role cannot read refuses with it (frozen `error` `unavailable`, `next: wait`), because gbrain cannot tell which holding page has the entity's readers; nothing was written. | 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. |## Shared-agent refusalsdiff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 2969fd5ff6..69c3c9d8da 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -433,9 +433,12 @@ Optional response fields; clients must ignore any they do not know.checkout, so the database is its record. `disabled_by_config` and`subagent_sandbox`: write-through is off for the brain or for this caller.`held_for: string`: on a source whose pages are canonical in Git, the- entity a fact was saved for while it has no page; the fact is a row of- `memory/unattributed` (`page`) whose `entity` column names it, until- maintenance moves it into the entity's page.+ entity a fact was saved for while it has no page; the fact is a row of a+ holding page (`page`) whose `entity` column names it, until maintenance+ moves it into the entity's page. The holding page is `memory/unattributed`,+ or for an entity under a folder access rule its folder's+ `<folder>/memory/unattributed`; under a database-only folder that page has+ no file (`persistence.mode` `database`, `skipped: db_only`).A fact saved for an entity with no page is stored and recalled like anyother. Where the source's pages are in Git, the reply also carries onediff --git a/llms-full.txt b/llms-full.txtindex 17bc03954f..8e65af66a6 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -7986,9 +7986,12 @@ Optional response fields; clients must ignore any they do not know.checkout, so the database is its record. `disabled_by_config` and`subagent_sandbox`: write-through is off for the brain or for this caller.`held_for: string`: on a source whose pages are canonical in Git, the- entity a fact was saved for while it has no page; the fact is a row of- `memory/unattributed` (`page`) whose `entity` column names it, until- maintenance moves it into the entity's page.+ entity a fact was saved for while it has no page; the fact is a row of a+ holding page (`page`) whose `entity` column names it, until maintenance+ moves it into the entity's page. The holding page is `memory/unattributed`,+ or for an entity under a folder access rule its folder's+ `<folder>/memory/unattributed`; under a database-only folder that page has+ no file (`persistence.mode` `database`, `skipped: db_only`).A fact saved for an entity with no page is stored and recalled like anyother. Where the source's pages are in Git, the reply also carries onediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a5d6b6e423..adf7a8a2af 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -49,6 +49,6 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)src/commands/config.ts 1530 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts)src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)-src/core/behavior-change-notice.ts 1758 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3+src/core/behavior-change-notice.ts 1759 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +1 GST-2492 PR 3 folder_holding_page_gst2492 row (since TBD until the merge slot; rows are data and cannot move)src/core/git/commit-push.ts 1627 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140)src/commands/auth.ts 1503 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot movediff --git a/src/commands/access-rules.ts b/src/commands/access-rules.tsindex f7f484471d..3078108483 100644--- a/src/commands/access-rules.ts+++ b/src/commands/access-rules.ts@@ -21,7 +21,8 @@ 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, coversDerived, folderRulesAllow, normalizeRule, ruleCoversSql, parsePolicyYaml, serializePolicyYaml, sortRules, type FolderRule, type RuleChange } from '../core/access/folder-rules.ts';+import { classifyRulebook, coversDerived, folderRulesAllow, normalizeRule, ruleCovers, ruleCoversSql, parsePolicyYaml, serializePolicyYaml, sortRules, type FolderRule, type RuleChange } from '../core/access/folder-rules.ts';+import { folderHoldingSlug, UNATTRIBUTED_MEMORY_SLUG } from '../core/facts-fence.ts';import { identityFor } from '../core/access/principals.ts';import { boundCredentials, listGroups, listMembers } from '../core/access/members.ts';import {@@ -115,6 +116,11 @@ export interface RulePreview {unknown_readers: string[];members_losing: string[];credentials_losing: Array<{ member: string; kind: string; name: string }>;+ /**+ * GST-2492: facts a strict source holds on memory/unattributed for an entity this change starts covering, and the page+ * the apply moves each to (its folder's holding page, or the entity's own page, created for an exact page rule).+ */+ held_facts_moving: Array<{ fact_id: number; entity_slug: string; to: string }>;}async function previewRules(engine: BrainEngine, sourceId: string, store: AccessStore, persisted: boolean, desired: FolderRule[]): Promise<RulePreview> {@@ -140,8 +146,15 @@ async function previewRules(engine: BrainEngine, sourceId: string, store: Access}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 });+ // A narrowing applies at once, so the held facts it covers leave the world-readable holding page in the same apply.+ const heldRows = await engine.executeRaw<{ id: number; entity_slug: string; page: boolean }>(`SELECT f.id::int AS id, f.entity_slug,+ EXISTS (SELECT 1 FROM pages p WHERE p.source_id=f.source_id AND p.slug=f.entity_slug AND p.deleted_at IS NULL) AS page+ FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND f.dimension IS NULL+ AND f.entity_slug IS NOT NULL AND f.entity_slug <> $2 ORDER BY f.id`, [sourceId, UNATTRIBUTED_MEMORY_SLUG]);+ const moving = heldRows.filter(row => cls.target.some(rule => ruleCovers(row.entity_slug, rule.prefix))).map(row => ({ fact_id: Number(row.id), entity_slug: row.entity_slug,+ to: row.page || cls.target.some(rule => rule.prefix === row.entity_slug) ? row.entity_slug : folderHoldingSlug(row.entity_slug) }));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 };+ unknown_readers: unknown, members_losing: losing, credentials_losing: credentials, held_facts_moving: moving };}function previewLines(p: RulePreview, rerun: string): string[] {@@ -152,6 +165,7 @@ function previewLines(p: RulePreview, rerun: string): string[] {...(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(', ')}`] : []),+ ...(p.held_facts_moving.length ? [` Held facts leaving ${UNATTRIBUTED_MEMORY_SLUG} with this change: ${p.held_facts_moving.length} (${p.held_facts_moving.slice(0, 10).map(m => `fact ${m.fact_id} for ${m.entity_slug} to ${m.to}${m.to === m.entity_slug ? ' (its page)' : ''}`).join(', ')}${p.held_facts_moving.length > 10 ? ', ...' : ''})`] : []),'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}).`,];@@ -170,6 +184,28 @@ export interface EditResult {pages_restamped: number;git?: GitPolicyReceipt;note?: string;+ /** GST-2492: held facts this apply moved off memory/unattributed to a page the new rules cover, and those that could not move. */+ held_facts?: { moved: number; unmovable: Array<{ slug: string; fact_ids: number[]; reason: string }> };+}++/**+ * GST-2492: a narrowing applies at once, held facts included: after the rules apply, each fact a strict source holds on+ * memory/unattributed for an entity the rules now cover moves to its folder's holding page (or into the entity's page),+ * the same step the extract_facts upkeep runs. A source that is not strict holds none.+ */+async function withHeldFactsMoved(engine: BrainEngine, result: EditResult): Promise<EditResult> {+ if (result.state !== 'applied' && result.state !== 'pending') return result;+ const held = await heldFactsMoved(engine, result.source_id);+ return held ? { ...result, held_facts: held } : result;+}++/** The held-fact move after any rule apply (edit, approved widening, resume); undefined when nothing was held. */+async function heldFactsMoved(engine: BrainEngine, sourceId: string): Promise<EditResult['held_facts']> {+ const { moveHeldFacts } = await import('../core/facts/held-fact-move.ts');+ const moved = await moveHeldFacts(engine, sourceId).catch((error: unknown) =>+ ({ moved: 0, rehomed: 0, unmovable: [{ slug: UNATTRIBUTED_MEMORY_SLUG, fact_ids: [], reason: (error instanceof Error ? error.message : String(error)).slice(0, 300) }] }));+ if (!moved.moved && !moved.rehomed && !moved.unmovable.length) return undefined;+ return { moved: moved.moved + moved.rehomed, unmovable: moved.unmovable.map(({ slug, fact_ids, reason }) => ({ slug, fact_ids, reason })) };}/** Writes a desired rulebook through the source's store (after the caller's preview) and reports the result. */@@ -179,8 +215,8 @@ async function writeRules(engine: BrainEngine, sourceId: string, desired: Folderif (!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.' } : {}) };+ return withHeldFactsMoved(engine, { 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;@@ -190,9 +226,9 @@ async function writeRules(engine: BrainEngine, sourceId: string, desired: Folderif (!(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,+ return withHeldFactsMoved(engine, { 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 } : {}) };+ ...(receipt.note ? { note: receipt.note } : {}) });}function editLines(r: EditResult): string[] {@@ -201,6 +237,8 @@ function editLines(r: EditResult): string[] {...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_facts?.moved ? [` ${r.held_facts.moved} held fact(s) moved to a page the rules now cover`] : []),+ ...(r.held_facts?.unmovable.length ? [` Held facts that could not move yet (the next gbrain dream retries): ${r.held_facts.unmovable.map(u => `${u.slug} facts ${u.fact_ids.join(',')} (${u.reason})`).join('; ')}`] : []),...(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] : []),@@ -371,7 +409,8 @@ async function applyCmd(engine: BrainEngine, args: string[], json: boolean): Progit = 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)`,+ const held = await heldFactsMoved(engine, sourceId);+ return print(json, { ...r, ...(git ? { git } : {}), ...(held ? { held_facts: held } : {}) }, () => [`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}`] : [])]);}@@ -384,7 +423,8 @@ export async function runAccessRules(engine: BrainEngine, cmd: string, rest: strcase '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'}`]);+ const held = await heldFactsMoved(engine, sourceId);+ print(json, { source_id: sourceId, ...r, ...(held ? { held_facts: held } : {}) }, () => [`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/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 243c45a0de..aa927bc710 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1560,6 +1560,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.693.0', id: 'member_save_withdrawn_scope_gst2346', text: 'A remote `remember` onto a member\'s own page (`memory/members/<id>`) is refused `fact_withdrawn` only when that member could read what was withdrawn: a fact on its own page, its own copy withdrawn by the brain host, or for the brain owner a fact it reads. A claim withdrawn by the brain host or the owner that the member never read no longer refuses its save: the fact saves as the member\'s own active row with the same reply as a new claim. A schema migration makes the database insert guards mark a row on a member page only by that page\'s own withdrawals; a withdrawal still expires matching rows on member pages when it is made, and strikes them in the page\'s file, so an import of a member page\'s file no longer marks a row withdrawn by a withdrawal of another subject. The same holds for each item of a `remember` batch (`items`), a replay with the same `request_id`, a `replaces` and the write receipt (`get_write_request`). Trusted local saves keep the check they had.' },{ since: '0.60.694.0', id: 'owner_labels_guarded_gst2521', text: 'Labels the owner sets with `gbrain repair visibility` (or its `--readers` setter, or `gbrain repair private-labels`) now raise the page\'s label guard to operator_curated, so a later local agent write at the page\'s own tier that drops or widens them is held like a write over an owner page, with a `lower_page` item. A local write below operator_curated whose `readable_by` would leave the brain owner out of a page the owner reads now publishes with the owner kept in the readers (the rest of the narrowing applies), and its item records the requested readers. Accepting such an item (`gbrain trust confirm tp<id>`) on a page whose own tier is an agent\'s writes only the labels and keeps the agent\'s tier; on an owner page it still endorses the edit at the owner\'s tier. The guard is stored in the database (`page_label_guards`) and set only by label repairs run after the upgrade, so labels set earlier, and a managed Git brain rebuilt from a clone, start unguarded; re-running `gbrain repair visibility --slug` or `--readers` on a page that already has those labels raises the guard without changing them. The owner\'s own label writes, synced owner edits, agent narrowing that keeps the owner, and brains with `access.owner_reads_restricted` on are unchanged.' },{ since: '0.60.694.0', id: 'page_label_widening_held_gst2518', text: 'A local agent write (`put_page`, `capture`, `edit_page`, `append_page`, `revert_version`, `restore_page`) less trusted than a page that drops or widens its `visibility`, `access`, `confidentiality` or `readable_by` now publishes with the page\'s earlier labels kept, in the database and in the committed file, and its receipt lists them under `privacy_labels_kept`; so does a maintenance job\'s derived page publication, and a page whose tier is still `unknown` counts as the owner\'s. A soft delete no longer lowers the page\'s tier. Before, the page became readable to remote callers and other members at once, and only a `lower_page` item waited for the owner. That item now records the requested labels: `gbrain trust confirm tp<id>` applies them if the page has not changed since, `gbrain trust drop tp<id>` keeps the earlier ones, and undoing a confirm restores them while the page is unchanged since. Narrowing writes, label-neutral writes, writers at or above the page\'s tier, synced owner edits and `gbrain repair visibility` are unchanged.' },+ { since: 'TBD', id: 'folder_holding_page_gst2492', text: 'On a source whose pages are canonical in Git (`canonical: git`), a fact for an entity with no page under a folder access rule is no longer kept in the database only: it is held on the holding page of the entity\'s folder (`partners/memory/unattributed` for `partners/acme-example`), which every rule covering the entity covers by path, so it is in Git (or database-only where the folder is, under `storage.db_only` or a path Git ignores) with exactly the readers the entity\'s page would have. The reply names that `page` and `write_through.held_for`. `gbrain access rule add` previews the held facts a new rule covers (`held_facts_moving`) and its apply moves them off `memory/unattributed` (`held_facts`), as do `gbrain access apply` and `gbrain access resume`; maintenance does the same for rules applied by a sync, and until then the fact reads only for the rule\'s readers. A held fact is now also hidden from a caller who cannot read its holding page, even under a rule with `covers_derived: false`. `gbrain repair facts-home` writes such facts to their folder\'s page and lists as `folder_restricted` only an exact page rule (`page_rule`) or unreadable rules (`access_unreadable`). A `remember` for a page-less entity under an exact page rule now refuses `git_home_required` (reason `facts_lane`, frozen `error` `invalid_params`) with a fix that creates the page, and one whose access rules this database role cannot read refuses `access_policy_pending` (`next: wait`); both wrote the fact to the database before. Sources that are not strict and brains with no Git repository are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex b43b217945..85a70be9e9 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -739,7 +739,7 @@ export interface ExtractFactsResult {legacyPages: string[];/** Unfenced rows this run appended to their page's fence and stamped with a row number (#5299). */unfencedRowsFenced: number;- /** GST-2492: facts held on memory/unattributed this run moved into their new entity page (present only when it moved any). */+ /** GST-2492: held facts this run moved into their new entity page or their folder's holding page (present only when it moved any). */heldFactsMoved?: number;/** Active fence-owned rows expired because their page was soft-deleted. */factsExpiredForDeletedPages: number;@@ -859,10 +859,11 @@ export async function runExtractFacts(fenceStepFailed = !isFenceHold(e);result.warnings.push(`FACTS_FENCE_FAILED: ${(e instanceof Error ? e.message : String(e)).slice(0, 300)}`);}- // GST-2492: facts a strict source held on memory/unattributed move into their entity page once it exists.+ // GST-2492: facts a strict source holds move into their entity page once it exists, and a fact held on+ // memory/unattributed whose entity a folder rule now covers moves to that folder's holding page.try {const held = await moveHeldFacts(engine, sourceId);- if (held.moved) result.heldFactsMoved = held.moved;+ if (held.moved + held.rehomed) result.heldFactsMoved = held.moved + held.rehomed;result.pagesFailed += held.write_errors;for (const row of held.unmovable) result.warnings.push(`HELD_FACT_UNMOVABLE: ${row.slug} facts ${row.fact_ids.join(',')} (${row.reason})`);} catch (e) {diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex ff7e4684b1..779bee1529 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -32,6 +32,7 @@ const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonicaimport { isMissingSchemaObject } from '../utils.ts';import { privatePagesFilterForCaller, privatePagesFilterFragment } from '../search/private-visibility.ts';import { rankingLinkSql } from '../link-ranking-policy.ts';+import { isHoldingSlug } from '../facts-fence.ts';/*** Canonicalize a free-form entity reference to a page slug.@@ -166,7 +167,7 @@ const NAME_NOISE_TOKENS = new Set(['the', 'inc', 'llc', 'ltd', 'co', 'corp', 'co/** True for pages that name one real-world person, company, fund or organization. */export function isIdentityEntity(slug: string, type?: string | null): boolean {- return (type != null && IDENTITY_TYPES.has(type)) || IDENTITY_DIRS.some(dir => slug.startsWith(dir));+ return !isHoldingSlug(slug) && ((type != null && IDENTITY_TYPES.has(type)) || IDENTITY_DIRS.some(dir => slug.startsWith(dir)));}const FACT_ENTITY_TYPES = new Set(['concept', 'project', 'deal']);@@ -174,8 +175,8 @@ const FACT_ENTITY_DIRS = ['hosts/', 'projects/', 'concepts/', 'deals/'];/** Pages a fuzzy fact attribution may land on: entities, never meetings, notes or other documents. */export function isFactEntityPage(slug: string, type: string | null): boolean {- return isIdentityEntity(slug, type) || (type != null && FACT_ENTITY_TYPES.has(type))- || FACT_ENTITY_DIRS.some(dir => slug.startsWith(dir));+ return !isHoldingSlug(slug) && (isIdentityEntity(slug, type) || (type != null && FACT_ENTITY_TYPES.has(type))+ || FACT_ENTITY_DIRS.some(dir => slug.startsWith(dir)));}function nameTokens(value: string): string {diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5de3c80547..24b65a61de 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -392,7 +392,7 @@ export const CODES = {git_conversion_delta: { class: 'consent', actor: 'user', summary: "An approved conversion found pages that changed since the approval, or decisions it did not approve, so only the unchanged pages were applied and the source stays mixed.", why: "gbrain sources canonical --to git --apply --approved applies only the pages whose slug, revision, committed blob, evidence and action are the ones the owner approved. A page that changed since, a new page, a database edit the plan would now discard, and any decision the approval did not hold stay unapplied and are listed (delta) with counts; nothing outside the approved set is applied without a new decision.", docs: 'docs/guides/git-canonical.md#approval-across-time', suggestion: 'Relay the delta list and its counts to the owner; once they decide, preview again with --approval-out and apply the new approval.' },conversion_file_in_source_root: { class: 'caller', summary: "A conversion review list, decisions file or approval was refused because its path is inside a source's checkout.", why: "Those files name pages and paths. Written or read only outside every registered source root and the Git working tree holding it (mode 0600), they can never be synced, imported or committed.", docs: 'docs/guides/git-canonical.md#review-list-and-decisions', suggestion: 'Pass a path outside every source checkout, e.g. under ~/.gbrain.' },git_conversion_incomplete: { class: 'retryable', summary: "A git-canonical conversion stopped because its strict pass did not finish, or finished with work left after the flag was set.", why: "The conversion runs a full strict-equivalent pass before it sets canonical: git, and one genuine strict pass after, then up to three closing strict passes while only door commits a live writer landed meanwhile are left (Git ahead of the database). A pass that ends partial, blocked or deferred stops the conversion where it is: before the flag the source stays as it was, after it the source stays strict (Git wins) and the plan lists what is left.", docs: 'docs/designs/GIT_CANONICAL_MEMORY.md#conversion', suggestion: 'Wait until gbrain sync status --source <id> --json shows the source idle, then preview again with gbrain sources canonical <id> --to git --dry-run and apply the new hash.' },- git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet.", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },+ git_home_required: { class: 'caller', summary: "A git-canonical source would store content in the database without a file in Git; nothing was written.", reasons: ['no_file_form', 'declared_target', 'facts_lane'], why: "On a source with canonical: git, page content reaches the database only after Git commits its file. The declared database-only classes (private, alias-private and lineage-private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores, detached pages and origin twins) are the only exceptions. no_file_form: the write has no file and is in no declared class; declared_target: a publication would commit a file for a declared page; facts_lane: a writer with no file form yet, or a fact for a page-less entity under an exact page rule, which no holding page can carry (create the page with put_page, then remember again).", docs: 'docs/guides/write-refusals.md#git_home_required', suggestion: 'Ask the user which git home to configure (a path Git tracks, or a storage.db_only directory in gbrain.yml), then submit the write again with a new request_id.' },git_private_commit_refused: { class: 'caller', summary: "A git-canonical source refused to commit the file of a private, alias-private or lineage-private page; nothing was written and HEAD is unchanged.", reasons: ['private', 'alias_private', 'lineage_private'], why: "Private pages of a source with canonical: git are database-only: their bytes never enter Git history. A page turning private is published as the door commit that removes its file, never as a commit of its bytes.", docs: 'docs/guides/write-refusals.md#git_private_commit_refused', suggestion: 'The page stays database-only. Write it through put_page (which publishes a private page without a file), or remove visibility: private if it belongs in Git, then submit again with a new request_id.' },git_protocol_required: { class: 'host_only', summary: "A write reached a git-canonical source from a process that does not declare the git-canonical protocol (an older gbrain, or gbrain.write_sources set by hand); nothing was written.", docs: 'docs/guides/write-refusals.md#git_protocol_required', suggestion: 'Upgrade or stop the gbrain process that wrote it (gbrain upgrade on its host), then retry with a new request_id.' },git_lfs_not_enabled: { class: 'caller', summary: "A git-canonical write falls under a Git LFS rule, but storage.git_lfs is off or the checkout does not configure the LFS filter; nothing was written.", reasons: ['opt_in_off', 'checkout_unconfigured'], why: "The door commits a file before its database row. A path .gitattributes routes through Git LFS commits as an LFS pointer only when the checkout configures the LFS filter (git lfs install --local) and the operator opted in; otherwise the raw bytes would be committed.", docs: 'docs/guides/write-refusals.md#git_lfs_not_enabled', suggestion: 'Ask the user: configure git-lfs in the checkout and run gbrain config set storage.git_lfs true, or narrow the .gitattributes rule; then submit again with a new request_id.' },diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex 793da5d182..9111268385 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -58,13 +58,28 @@ import { isOpPageSlug } from './page-slug-grammar.ts';export const UNATTRIBUTED_MEMORY_SLUG = 'memory/unattributed';/**- * Which page a fence is parsed for: only `memory/unattributed` reads the `entity` column, so on every other page an- * `entity` header stays an unsupported column. `reader` is for a body-only reader that decides nothing about what a page- * may hold (the withdrawal overlay, the remote-read strip): every write and import is parsed for its page, so only- * `memory/unattributed` can carry the column, and such a reader reads it wherever it finds it.+ * GST-2492: the holding pages, `memory/unattributed` and each folder's `<folder>/memory/unattributed`. An entity under a+ * folder access rule holds its fact on the page of its own folder (`partners/alice-example/deal-notes` on+ * `partners/alice-example/memory/unattributed`), so every prefix rule that covers the entity covers its holding page.+ */+export const isHoldingSlug = (slug: string | null | undefined): boolean =>+ slug === UNATTRIBUTED_MEMORY_SLUG || typeof slug === 'string' && slug.endsWith(`/${UNATTRIBUTED_MEMORY_SLUG}`);++/** SQL twin of isHoldingSlug over a text expression. */+export const holdingSlugSql = (column: string): string => `(${column} = '${UNATTRIBUTED_MEMORY_SLUG}' OR ${column} LIKE '%/${UNATTRIBUTED_MEMORY_SLUG}')`;++/** The holding page of `entity`'s own folder (memory/unattributed for an entity with no folder). */+export const folderHoldingSlug = (entity: string): string =>+ entity.includes('/') ? `${entity.slice(0, entity.lastIndexOf('/'))}/${UNATTRIBUTED_MEMORY_SLUG}` : UNATTRIBUTED_MEMORY_SLUG;++/**+ * Which page a fence is parsed for: only a holding page (isHoldingSlug) reads the `entity` column, so on every other page+ * an `entity` header stays an unsupported column. `reader` is for a body-only reader that decides nothing about what a page+ * may hold (the withdrawal overlay, the remote-read strip): every write and import is parsed for its page, so only a+ * holding page can carry the column, and such a reader reads it wherever it finds it.*/export interface FactsFenceParseOpts { slug?: string | null; reader?: boolean }-const readsEntity = (opts?: FactsFenceParseOpts): boolean => opts?.reader === true || opts?.slug === UNATTRIBUTED_MEMORY_SLUG;+const readsEntity = (opts?: FactsFenceParseOpts): boolean => opts?.reader === true || isHoldingSlug(opts?.slug);// HTML-comment fence markers — verbatim per spec. Same shape as the takes// fence markers so anyone who's seen one immediately recognizes the other.@@ -379,8 +394,10 @@ export function parseFactsFenceFor(body: string, opts?: FactsFenceParseOpts): Fa}// GST-2492: a held row's entity is a page slug; any other cell is a fence problem, so the page is held, never misfiled.+ // A folder's holding page holds only entities of that folder.const entity = entityRaw.trim();- if (entity && (!isOpPageSlug(entity) || entity === UNATTRIBUTED_MEMORY_SLUG)) {+ if (entity && (!isOpPageSlug(entity) || isHoldingSlug(entity)+ || isHoldingSlug(opts?.slug) && opts?.slug !== UNATTRIBUTED_MEMORY_SLUG && folderHoldingSlug(entity) !== opts?.slug)) {warnings.push(`FACTS_TABLE_MALFORMED: invalid entity "${entity}" in row ${rowNumStr} (expected a page slug such as people/alice-example)`);continue;}diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.tsindex 9d947ff50b..7936da85cc 100644--- a/src/core/facts/extract-from-fence.ts+++ b/src/core/facts/extract-from-fence.ts@@ -50,7 +50,7 @@ import { computeEffectiveDate } from '../effective-date.ts';* was. A held row (GST-2492: its entity has no page yet, on a strict source) projects the entity its cell names.*/export { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';export const FACT_DATE_SOURCES: ReadonlySet<string> = new Set(['event_date', 'date', 'published', 'filename']);@@ -274,7 +274,7 @@ export function extractFactsFromFenceText(const row: FenceExtractedFact = {fact: f.claim,kind: f.kind as FactKind,- entity_slug: slug === UNATTRIBUTED_MEMORY_SLUG ? f.entity ?? null : slug,+ entity_slug: isHoldingSlug(slug) ? f.entity ?? null : slug,visibility: f.visibility as FactVisibility,notability: f.notability,context: f.context ?? null,diff --git a/src/core/facts/facts-home.ts b/src/core/facts/facts-home.tsindex 16b5d6f7b2..2d9f284904 100644--- a/src/core/facts/facts-home.ts+++ b/src/core/facts/facts-home.ts@@ -5,12 +5,14 @@* Groups, one per row:* - `entity_page_exists`: a database-only fact (or a fact held on memory/unattributed) whose entity now has a page; the* extract_facts upkeep step moves it there.- * - `entity_page_missing`: a database-only fact for an entity with no page; the repair writes it to memory/unattributed- * as a held row that names the entity.+ * - `entity_page_missing`: a database-only fact for an entity with no page; the repair writes it to its holding page+ * (`home`: memory/unattributed, or under a folder access rule the holding page of the entity's folder) as a held row+ * that names the entity.* - `no_entity`: a database-only fact with no entity; the repair writes it to memory/unattributed.* - `cannot_render`: a database-only fact the Facts table cannot render as it stands (its class says why); stays, listed.- * - `folder_restricted`: a database-only fact for an entity under a folder access rule; it is never named on the- * world-readable holding page, so it stays, listed.+ * - `folder_restricted`: a database-only fact for an entity no holding page can carry: an exact page rule on its slug+ * (`page_rule`; create the page and the upkeep step fences it) or an access state this role cannot read+ * (`access_unreadable`); it stays, listed.* - `entity_page_deleted`: a database-only fact whose entity page is soft-deleted (it may be private, and its purge would* not reach a row on the holding page); restore or purge that page; stays, listed.* - `held_fact_unmovable`: a held row whose entity has a page that cannot take it, or whose bare name matches two or more@@ -22,12 +24,12 @@* row on any page's Facts table; the census counts it, so it is listed, never moved.*/import type { BrainEngine } from '../engine.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { folderHoldingSlug, holdingSlugSql, UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { getWorktreeBinding } from '../persistence/ownership.ts';import { folderRestricted } from '../search/private-visibility.ts';import { adoptableClaim, pageHasFile, planPageFence, type UnfencedFactRow } from './unfenced-facts.ts';-import { ambiguousHeldReason, heldFactTarget } from './held-fact-move.ts';+import { ambiguousHeldReason, heldFactTarget, holdingHome } from './held-fact-move.ts';export const FACTS_HOME_DOCS = 'docs/guides/repair.md#facts-home';export const HELD_TOO_LONG_DAYS = 30;@@ -47,6 +49,8 @@ export interface FactsHomeRow {nearest?: string | null;/** held_over_30_days: when the row was written. */held_since?: string;+ /** entity_page_missing and no_entity: the holding page the repair writes it to. */+ home?: string;}export interface FactsHomeScan {@@ -54,8 +58,8 @@ export interface FactsHomeScan {strict: boolean;rows: FactsHomeRow[];counts: Record<FactsHomeGroup, number>;- /** entity_page_missing and no_entity rows, as the repair writes them to memory/unattributed. */- homeable: UnfencedFactRow[];+ /** entity_page_missing and no_entity rows, as the repair writes them to their holding page (`home`). */+ homeable: Array<UnfencedFactRow & { home: string }>;}const ROW_COLUMNS = `f.id, f.source_id, f.entity_slug, f.fact, f.kind, f.visibility, f.notability, f.context, f.valid_from, f.valid_until, f.source,@@ -79,16 +83,20 @@ export async function scanFactsHome(engine: BrainEngine, sourceId: string): Promif (row.dimension != null) { add({ ...base, group: 'ontology_observation', reason: row.dimension }); continue; }if (row.entity_slug !== null && row.page_exists) { add({ ...base, group: 'entity_page_exists' }); continue; }if (row.entity_slug !== null && row.page_deleted) { add({ ...base, group: 'entity_page_deleted' }); continue; }- if (row.entity_slug !== null && row.entity_slug !== UNATTRIBUTED_MEMORY_SLUG && await folderRestricted(engine, sourceId, row.entity_slug)) { add({ ...base, group: 'folder_restricted', reason: 'folder_rule' }); continue; }+ const entity = row.entity_slug === UNATTRIBUTED_MEMORY_SLUG ? null : row.entity_slug;+ // The holding page every fact writer uses (held-fact-move.ts holdingHome); with write-through off, the one it would use.+ const found = await holdingHome(engine, sourceId, entity);+ const home = found ?? (entity !== null && await folderRestricted(engine, sourceId, entity) ? { slug: folderHoldingSlug(entity) } : { slug: UNATTRIBUTED_MEMORY_SLUG });+ if ('refused' in home) { add({ ...base, group: 'folder_restricted', reason: home.refused }); continue; }const oracle = adoptableClaim(row);if ('rejected' in oracle) { add({ ...base, group: 'cannot_render', reason: oracle.rejected }); continue; }- add({ ...base, group: row.entity_slug === null || row.entity_slug === UNATTRIBUTED_MEMORY_SLUG ? 'no_entity' : 'entity_page_missing' });- out.homeable.push(row);+ add({ ...base, group: entity === null ? 'no_entity' : 'entity_page_missing', home: home.slug });+ out.homeable.push({ ...row, home: home.slug });}- const held = await engine.executeRaw<UnfencedFactRow & { held_since: string; old: boolean }>(`SELECT ${ROW_COLUMNS}, ${pageLive} AS page_exists,- to_char(f.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS held_since, f.created_at < now() - ($3 || ' days')::interval AS old- FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND f.dimension IS NULL- AND f.entity_slug IS NOT NULL AND f.entity_slug <> $2 ORDER BY f.entity_slug, f.id`, [sourceId, UNATTRIBUTED_MEMORY_SLUG, String(HELD_TOO_LONG_DAYS)]);+ const held = await engine.executeRaw<UnfencedFactRow & { held_since: string; old: boolean; from_slug: string }>(`SELECT ${ROW_COLUMNS}, ${pageLive} AS page_exists, f.source_markdown_slug AS from_slug,+ to_char(f.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS held_since, f.created_at < now() - ($2 || ' days')::interval AS old+ FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug IN (SELECT hp.slug FROM pages hp WHERE hp.source_id = $1 AND ${holdingSlugSql('hp.slug')}) AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND f.dimension IS NULL+ AND f.entity_slug IS NOT NULL AND NOT ${holdingSlugSql('f.entity_slug')} ORDER BY f.entity_slug, f.id`, [sourceId, String(HELD_TOO_LONG_DAYS)]);const waiting = new Map<string, typeof held>();const targets = new Map<string, Awaited<ReturnType<typeof heldFactTarget>>>();for (const row of held) {@@ -120,12 +128,19 @@ async function nearestPage(engine: BrainEngine, sourceId: string, slug: string):}/** Each held row of `slug` with why its page cannot take it (null: the upkeep move takes it), planned read-only as the move plans it. */-async function heldUnmovable(engine: BrainEngine, sourceId: string, slug: string, group: UnfencedFactRow[]): Promise<Array<[number, string | null]>> {+async function heldUnmovable(engine: BrainEngine, sourceId: string, slug: string, group: Array<UnfencedFactRow & { from_slug: string }>): Promise<Array<[number, string | null]>> {const planned = await planPageFence(engine, sourceId, slug, group);if (!planned) return group.map(row => [Number(row.id), null]);- if (!await pageHasFile(engine, sourceId, slug, planned.snapshot.page)) return group.map(row => [Number(row.id), 'entity_page_database_only']);+ // A held row in Git does not move into a page kept out of Git (a row a database-only holding page holds does).+ const filed = new Set<string>();+ if (!await pageHasFile(engine, sourceId, slug, planned.snapshot.page)) {+ for (const from of new Set(group.map(row => row.from_slug))) {+ const [page] = await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>('SELECT source_path, source_uri FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, from]);+ if (page && await pageHasFile(engine, sourceId, from, page)) filed.add(from);+ }+ }const plan = planned.fence;- if ('warnings' in plan) return group.map(row => [Number(row.id), `entity_fence_malformed: ${plan.warnings.join('; ')}`]);- const rejected = new Map(plan.rejected.map(record => [record.fact_id, record.class]));- return group.map(row => [Number(row.id), rejected.get(Number(row.id)) ?? null]);+ const rejected = 'warnings' in plan ? null : new Map(plan.rejected.map(record => [record.fact_id, record.class]));+ return group.map(row => [Number(row.id), filed.has(row.from_slug) ? 'entity_page_database_only'+ : 'warnings' in plan ? `entity_fence_malformed: ${plan.warnings.join('; ')}` : rejected!.get(Number(row.id)) ?? null]);}diff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.tsindex 5bbdd2bc2e..4c3192614f 100644--- a/src/core/facts/fence-fact-append.ts+++ b/src/core/facts/fence-fact-append.ts@@ -46,7 +46,8 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';import { withPendingFenceRows } from '../eligibility/fence-overlay.ts';import { withPageTierKept } from '../trust/fence-append.ts';import type { TrustTier } from '../trust/tier.ts';-import { extractFactsFromFenceText, UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';+import { extractFactsFromFenceText } from './extract-from-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';import { rememberAcceptsPageCreatedSince } from '../persistence/page-identity.ts';import { fenceRowOf, withHeldFactsFence, type FenceRowInput } from './unfenced-facts.ts';import { withdrawnFact } from './withdrawal-overlay.ts';@@ -91,9 +92,9 @@ async function insertFenceFactRow(tx: BrainEngine, row: WriteRequest, rowNum: nu{ fix: requestReceiptFix(row) });}-/** One fact as its fence cell at `rowNum` (`fenceRowOf`, the one renderer); on memory/unattributed a held fact names its entity (GST-2492). */+/** One fact as its fence cell at `rowNum` (`fenceRowOf`, the one renderer); on a holding page a held fact names its entity (GST-2492). */function fenceCellFor(fact: FenceFactAppendInput['fact'], rowNum: number, slug: string): ReturnType<typeof fenceRowOf> {- const entity = slug === UNATTRIBUTED_MEMORY_SLUG && fact.entity_slug ? { entity: fact.entity_slug } : {};+ const entity = isHoldingSlug(slug) && fact.entity_slug ? { entity: fact.entity_slug } : {};return { ...entity, ...fenceRowOf({ kind: (fact.kind ?? 'fact') as FenceRowInput['kind'], visibility: fact.visibility ?? 'private', context: fact.context ?? null, valid_from: fact.valid_from,valid_until: fact.valid_until ?? null, source: fact.source, claim_metric: fact.claim_metric ?? null, claim_value: fact.claim_value ?? null,claim_unit: fact.claim_unit ?? null, claim_period: fact.claim_period ?? null, attributed_to: fact.attributed_to ?? null,@@ -129,7 +130,7 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequinput: FenceFactAppendInput, signal?: AbortSignal): Promise<FenceFactAppend> {const { fact } = input;const page = { sourceId: row.source_id, slug: row.slug };- if (!snapshot && (row.slug !== UNATTRIBUTED_MEMORY_SLUG || input.mode === 'index-existing')) {+ if (!snapshot && (!isHoldingSlug(row.slug) || input.mode === 'index-existing')) {throw opError('storage_error', 'The facts fence target page does not exist.',`Request ${row.request_id} writes a facts row on ${row.slug} in source ${row.source_id}, which has no page, so nothing was written. Inspect the request; if it repeats, run gbrain doctor --json and report it to the user.`,{ fix: requestReceiptFix(row) });diff --git a/src/core/facts/held-fact-move.ts b/src/core/facts/held-fact-move.tsindex 7339e676c5..b3b3803d42 100644--- a/src/core/facts/held-fact-move.ts+++ b/src/core/facts/held-fact-move.ts@@ -1,37 +1,56 @@/**- * GST-2492: on a strict git-canonical source, `remember` for an entity that has no page holds the fact as a row of- * memory/unattributed whose `entity` cell names the entity (memory-mutations.ts planRememberTarget), so Git has it- * before the database does. Once the entity has a page, the extract_facts phase moves the held rows here: one- * maintenance publication per entity appends them to the entity page's Facts fence and strikes their holding rows,- * and the facts rows move in place (ids, embeddings and provenance kept; the belief ledger transfers their stream).- * A row that cannot move stays held, active and searchable, and is reported as `held_fact_unmovable`.+ * GST-2492: on a strict git-canonical source, a fact for an entity that has no page is held as a row of a holding page+ * whose `entity` cell names the entity (memory-mutations.ts planRememberTarget, and every other fact writer through+ * `holdingHome`), so Git has it before the database does: the shared memory/unattributed, or, for an entity under a folder+ * access rule, the holding page of the entity's own folder (`<folder>/memory/unattributed`, which every prefix rule+ * covering the entity covers too). Once the entity has a page, the extract_facts phase moves the held rows there: one+ * maintenance publication per entity appends them to the entity page's Facts fence and strikes their holding rows, and+ * the facts rows move in place (ids, embeddings and provenance kept; the belief ledger transfers their stream). A held row+ * on the shared page whose entity a folder rule now covers is moved to its folder's holding page the same way (the rule's+ * own apply step runs this, so a narrowing reaches held rows at once). A row that cannot move stays held, active and+ * searchable, and is reported as `held_fact_unmovable`.*/import type { BrainEngine } from '../engine.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { opError, type OperationContext, type OperationError } from '../ops/contract.ts';+import { folderHoldingSlug, holdingSlugSql, isHoldingSlug, UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';import { maintenancePreflight, submitPlannedFactFenceAdoption } from '../persistence/prepared-maintenance.ts';-import { folderRestricted, privatePagesFilterFragment } from '../search/private-visibility.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { getWorktreeBinding } from '../persistence/ownership.ts';import { isFenceHold, pageHasFile, planManagedPage, type UnfencedFactRow } from './unfenced-facts.ts';export interface HeldFactMoveOutcome {moved: number;moved_slugs: string[];- /** Held rows that stay on memory/unattributed this run, with the reason (the entity page's fence, a duplicate claim, a refusal). */+ /** Held rows moved from memory/unattributed to the holding page of their entity's folder, now under a folder rule. */+ rehomed: number;+ /** Held rows that stay on their holding page this run, with the reason (the entity page's fence, a duplicate claim, a refusal). */unmovable: Array<{ code: 'held_fact_unmovable'; slug: string; fact_ids: number[]; reason: string }>;/** #8568: entities whose move threw (I/O, database), as opposed to holds the next run settles. */write_errors: number;}/**- * GST-2492 PR 2: whether a fact for `entity` (null: no entity) that has no page of its own is written to memory/unattributed- * on this source: the source is strict, write-through is on, and no folder access rule covers the entity and its page is not- * soft-deleted (such an entity is not named on the world-readable holding page, so its fact stays database-only).+ * Where a fact for `entity` (null: no entity) that has no page of its own is held on this source. Null when it is not+ * held: the source is not strict, write-through is off, or the entity's page is soft-deleted (it may be private, and its+ * purge would not reach a holding row). Otherwise the shared memory/unattributed, or, when a folder rule or pending folder+ * coverage covers the entity, its folder's holding page. An exact page rule on the entity's own slug, and an access state+ * this database role cannot read, are refused: no holding page carries their readers.*/-export async function holdsInGit(engine: BrainEngine, sourceId: string, entity: string | null): Promise<boolean> {- if ((await getWorktreeBinding(engine, sourceId))?.canonical_git !== true) return false;- if (/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true')) return false;- return entity === null || !await folderRestricted(engine, sourceId, entity)- && !(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NOT NULL', [sourceId, entity])).length;+export async function holdingHome(engine: BrainEngine, sourceId: string, entity: string | null):+ Promise<{ slug: string } | { refused: 'page_rule' | 'access_unreadable' } | null> {+ if ((await getWorktreeBinding(engine, sourceId))?.canonical_git !== true) return null;+ if (/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true')) return null;+ if (entity === null || entity === UNATTRIBUTED_MEMORY_SLUG) return { slug: UNATTRIBUTED_MEMORY_SLUG };+ if ((await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NOT NULL', [sourceId, entity])).length) return null;+ const access = await engine.executeRaw<{ unreadable: boolean; page_rule: boolean; restricted: boolean }>(+ `SELECT gbrain_access_state_unreadable() AS unreadable,+ (EXISTS (SELECT 1 FROM access_rules r WHERE r.source_id=$1 AND r.prefix=$2)+ OR EXISTS (SELECT 1 FROM access_pending_coverage c WHERE c.source_id=$1 AND c.prefix=$2)) AS page_rule,+ (gbrain_access_folder_rules($1, $2) IS NOT NULL OR gbrain_access_pending_covers($1, $2)) AS restricted`, [sourceId, entity]).catch(() => null);+ const row = access?.[0];+ if (!row || row.unreadable) return { refused: 'access_unreadable' };+ if (row.page_rule) return { refused: 'page_rule' };+ return { slug: row.restricted ? folderHoldingSlug(entity) : UNATTRIBUTED_MEMORY_SLUG };}/**@@ -48,51 +67,101 @@ export async function heldFactTarget(engine: BrainEngine, sourceId: string, key:return strict.miss === 'ambiguous' ? { ambiguous: await entityReferenceCandidates(engine, sourceId, key) } : null;}+/** holdingHome's `access_unreadable`: the folder rules covering the entity cannot be read now, so nothing was written; retry. */+export function accessStateUnreadable(sourceId: string): OperationError {+ return opError('access_policy_pending', `The folder access rules of source ${sourceId} cannot be read right now, so gbrain cannot tell which holding page keeps this fact to its entity's readers; nothing was written.`,+ 'Retry the same request shortly; if it keeps failing, the brain host checks the folder access tables (gbrain doctor names the check).',+ { docs: 'docs/guides/write-refusals.md#access_policy_pending', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', sourceId, '--json'], consent: [], actor: 'provider',+ requires_exclusive: false, why: 'Shows the folder rules and anything pending; changes nothing. The write succeeds once the rules read again.' } });+}+export const ambiguousHeldReason = (candidates: string[]) => `entity_ambiguous: candidates ${candidates.join(', ')}`;+/**+ * Creates `slug` through the write door when it has no page yet: maintenance publishes only to a page that exists. A+ * holding page is the empty note the first held fact creates (titled Unattributed memory); an entity page is created for+ * an entity an exact page rule names, whose held rows only its own page can carry.+ */+export async function ensurePageForHeldRows(engine: BrainEngine, sourceId: string, slug: string, ctx?: OperationContext): Promise<void> {+ if (await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true })) return;+ const { submitPageMutation } = await import('../persistence/page-mutations.ts');+ const { repairRequestId } = await import('../repair/core.ts');+ const local = { ...(ctx ?? { engine, config: { engine: engine.kind }, dryRun: false, logger: { info() {}, warn() {}, error() {} } }), remote: false, sourceId } as OperationContext;+ const title = isHoldingSlug(slug) ? 'Unattributed memory' : slug.slice(slug.lastIndexOf('/') + 1);+ await submitPageMutation(local, { operation: 'put_page', params: { slug,+ request_id: await repairRequestId(local, 'facts-home', { source_id: sourceId, slug }, 'holding-page'),+ content: `---\ntype: note\ntitle: ${JSON.stringify(title)}\n---\n` } });+}++type HeldRow = UnfencedFactRow & { from_slug: string };+export async function moveHeldFacts(engine: BrainEngine, sourceId: string): Promise<HeldFactMoveOutcome> {- const outcome: HeldFactMoveOutcome = { moved: 0, moved_slugs: [], unmovable: [], write_errors: 0 };- const rows = await engine.executeRaw<UnfencedFactRow>(+ const outcome: HeldFactMoveOutcome = { moved: 0, moved_slugs: [], rehomed: 0, unmovable: [], write_errors: 0 };+ const rows = await engine.executeRaw<HeldRow>(`SELECT id, source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, source, confidence,- claim_metric, claim_value, claim_unit, claim_period, attributed_to, true AS page_exists+ claim_metric, claim_value, claim_unit, claim_period, attributed_to, true AS page_exists, source_markdown_slug AS from_slugFROM facts f- WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND f.dimension IS NULL- AND f.entity_slug IS NOT NULL AND f.entity_slug <> $2- AND (f.entity_slug NOT LIKE '%/%' OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id AND p.slug = f.entity_slug AND p.deleted_at IS NULL))- ORDER BY f.entity_slug, f.id`, [sourceId, UNATTRIBUTED_MEMORY_SLUG]);+ WHERE f.source_id = $1 AND f.source_markdown_slug IN (SELECT hp.slug FROM pages hp WHERE hp.source_id = $1 AND ${holdingSlugSql('hp.slug')}) AND f.row_num IS NOT NULL AND f.expired_at IS NULL AND f.dimension IS NULL+ AND f.entity_slug IS NOT NULL AND NOT ${holdingSlugSql('f.entity_slug')}+ ORDER BY f.source_markdown_slug, f.entity_slug, f.id`, [sourceId]);if (rows.length === 0) return outcome;const unmovable = (slug: string, ids: Array<string | number>, reason: string) => {if (ids.length) outcome.unmovable.push({ code: 'held_fact_unmovable', slug, fact_ids: ids.map(Number), reason });};- const keys = new Map<string, UnfencedFactRow[]>();- for (const row of rows) keys.set(row.entity_slug!, [...keys.get(row.entity_slug!) ?? [], row]);- // A row keyed by a bare name moves to the page that name now resolves to, which re-keys it to that page.- const groups: Array<{ slug: string; from?: string; group: UnfencedFactRow[] }> = [];- for (const [key, group] of keys) {- const target = await heldFactTarget(engine, sourceId, key);- if (target && 'ambiguous' in target) unmovable(key, group.map(r => r.id), ambiguousHeldReason(target.ambiguous));- else if (target) groups.push({ slug: target.slug, ...(target.slug === key ? {} : { from: key }), group });+ const keys = new Map<string, HeldRow[]>();+ for (const row of rows) keys.set(`${row.from_slug}\0${row.entity_slug}`, [...keys.get(`${row.from_slug}\0${row.entity_slug}`) ?? [], row]);+ // A row keyed by a bare name moves to the page that name now resolves to, which re-keys it to that page; a row of an+ // entity with no page whose folder a rule now covers moves to that folder's holding page.+ const groups: Array<{ slug: string; from: string; fromEntity?: string; group: HeldRow[]; rehome: boolean }> = [];+ let authority: Awaited<ReturnType<typeof maintenancePreflight>> | undefined;+ for (const [, group] of keys) {+ const { from_slug: from, entity_slug: key } = group[0]!;+ let target = await heldFactTarget(engine, sourceId, key!);+ const home = target ? null : await holdingHome(engine, sourceId, key!);+ if (home && 'refused' in home && home.refused === 'access_unreadable') { unmovable(key!, group.map(r => r.id), 'access_unreadable'); continue; }+ if (home && 'refused' in home) {+ // An exact page rule on the entity: only its own page carries those readers, so the page is created for its rows.+ authority ??= await maintenancePreflight(engine, sourceId);+ if (!authority) return outcome;+ try { await ensurePageForHeldRows(engine, sourceId, key!); } catch (error) {+ unmovable(key!, group.map(r => r.id), (error instanceof Error ? error.message : String(error)).slice(0, 300));+ continue;+ }+ target = { slug: key! };+ }+ if (target && 'ambiguous' in target) unmovable(key!, group.map(r => r.id), ambiguousHeldReason(target.ambiguous));+ else if (target) groups.push({ slug: target.slug, from, ...(target.slug === key ? {} : { fromEntity: key! }), group, rehome: false });+ else if (home && 'slug' in home && home.slug !== from && from === UNATTRIBUTED_MEMORY_SLUG) groups.push({ slug: home.slug, from, group, rehome: true });}if (groups.length === 0) return outcome;- const authority = await maintenancePreflight(engine, sourceId);+ authority ??= await maintenancePreflight(engine, sourceId);if (!authority) return outcome;- for (const { slug, from, group } of groups) {+ for (const { slug, from, fromEntity, group, rehome } of groups) {try {+ if (rehome) await ensurePageForHeldRows(engine, sourceId, slug);const [page] = await engine.executeRaw<{ source_path: string | null; source_uri: string | null; visible: boolean }>(`SELECT p.source_path, p.source_uri, ${privatePagesFilterFragment('p')} AS visible FROM pages p WHERE p.source_id=$1 AND p.slug=$2 AND p.deleted_at IS NULL`, [sourceId, slug]);- if (!page) continue;- // The holding row is in Git; a move into a page kept out of Git would strike it there with no file holding the fact.- if (!await pageHasFile(engine, sourceId, slug, page)) { unmovable(slug, group.map(r => r.id), 'entity_page_database_only'); continue; }- // A fact moved into a page not every reader of the source can read leaves the world-readable holding page altogether.- const plan = await planManagedPage(engine, authority, sourceId, slug, group, { note: page.visible === true ? `moved to ${slug}` : 'moved', ...(from ? { from_entity: from } : {}) });+ if (!page) { unmovable(slug, group.map(r => r.id), rehome ? 'holding_page_deleted' : 'entity_page_deleted'); continue; }+ // A held row in Git moved into a page kept out of Git would be struck there with no file holding the fact; a row+ // re-homed because a folder rule now covers it moves whatever the folder's storage class (the rule applies at once).+ const [held] = await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>(+ 'SELECT source_path, source_uri FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, from]);+ if (!rehome && held && await pageHasFile(engine, sourceId, from, held) && !await pageHasFile(engine, sourceId, slug, page)) {+ unmovable(slug, group.map(r => r.id), 'entity_page_database_only'); continue;+ }+ // A fact moved into a page not every reader of the source can read, or off a folder's holding page, leaves the+ // holding page with no trace of where it went.+ const note = !rehome && from === UNATTRIBUTED_MEMORY_SLUG && page.visible === true ? `moved to ${slug}` : 'moved';+ const plan = await planManagedPage(engine, authority, sourceId, slug, group,+ { note, ...(fromEntity ? { from_entity: fromEntity } : {}), ...(from === UNATTRIBUTED_MEMORY_SLUG ? {} : { from_slug: from }) });if (plan.kind === 'no_page') continue;if (plan.kind === 'warnings') { unmovable(slug, group.map(r => r.id), `entity_fence_malformed: ${plan.warnings.join('; ')}`); continue; }const rejected = plan.kind === 'unadoptable' ? plan.records : plan.fence.rejected;for (const reason of new Set(rejected.map(r => r.class))) unmovable(slug, rejected.filter(r => r.class === reason).map(r => r.fact_id), reason);if (plan.kind === 'unadoptable') continue;await submitPlannedFactFenceAdoption(engine, authority, slug, plan.request, true);- outcome.moved += plan.fence.assignments.length;- outcome.moved_slugs.push(slug);+ if (rehome) outcome.rehomed += plan.fence.assignments.length;+ else { outcome.moved += plan.fence.assignments.length; outcome.moved_slugs.push(slug); }} catch (error) {unmovable(slug, group.map(r => r.id), (error instanceof Error ? error.message : String(error)).slice(0, 300));if (!isFenceHold(error)) outcome.write_errors += 1;diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 5c4601710f..b316487505 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -48,7 +48,7 @@ import { rebuildPendingPageProjections } from '../page-state/projections.ts';import { buildSegmentedProjection } from '../page-body/projection.ts';import { liveStagingSql } from '../page-body/schema.ts';import { escapeFenceCell } from '../fence-shared.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { holdingSlugSql } from '../facts-fence.ts';import { carriesClaimSql, claimNeedles, purgeCompletion, reasonNeedle, verifyFactPurge, type PurgeReceipt, type StoreCount } from './purge-verify.ts';import { noteBelief, withBeliefBatch } from '../belief/ledger.ts';import { markBeliefCommits } from '../belief/append.ts';@@ -531,11 +531,11 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Recawait tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason)VALUES ($1,$2,$3,$4,$5::uuid,$6,$7) ON CONFLICT DO NOTHING`,[p.sourceId, current.visibility, plan.subject, current.fact_hash, admitted.id, `${principal.kind}:${principal.id}`, p.reason]);- // GST-2492: a fact memory/unattributed holds for an entity with no page is purged from the holding page as well.+ // GST-2492: a fact a holding page holds for an entity with no page is purged from that holding page as well.if (plan.subject !== '*') await tx.executeRaw(`INSERT INTO fact_purges(source_id,visibility,subject,fact_hash,request_id,actor,reason)- SELECT $1::text,$2::text,$3::text,$4::text,$5::uuid,$6::text,$7::text WHERE EXISTS (SELECT 1 FROM facts- WHERE id=ANY($8::bigint[]) AND source_id=$1 AND source_markdown_slug=$3 AND entity_slug IS NOT NULL) ON CONFLICT DO NOTHING`,- [p.sourceId, current.visibility, UNATTRIBUTED_MEMORY_SLUG, current.fact_hash, admitted.id, `${principal.kind}:${principal.id}`, p.reason, plan.factIds]);+ SELECT DISTINCT $1::text,$2::text,f.source_markdown_slug,$3::text,$4::uuid,$5::text,$6::text FROM facts f+ WHERE f.id=ANY($7::bigint[]) AND f.source_id=$1 AND ${holdingSlugSql('f.source_markdown_slug')} AND f.entity_slug IS NOT NULL ON CONFLICT DO NOTHING`,+ [p.sourceId, current.visibility, current.fact_hash, admitted.id, `${principal.kind}:${principal.id}`, p.reason, plan.factIds]);await tx.executeRaw(`INSERT INTO take_purges(source_id,subject,claim_hash,request_id) VALUES ($1,$2,$3,$4::uuid) ON CONFLICT DO NOTHING`,[p.sourceId, plan.subject, current.fact_hash, admitted.id]);const takes = plan.takes.length ? (await tx.executeRaw('DELETE FROM takes WHERE id=ANY($1::bigint[]) RETURNING id', [plan.takes.map(t => t.id)])).length : 0;diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex eb543db4c5..8a30bb391d 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -15,7 +15,7 @@ import { MEMBER_PAGE_PREFIX } from '../access/principals.ts';import { pageNotVisibleError } from '../persistence/page-visibility.ts';import { slugUnderBoundPrefixes } from '../ops/context.ts';import { ownedPageWithdrawalSubject, onOwnedMemoryPageSql, withdrawalCoversFactSql, withdrawalReachedFactSql } from '../access/member-facts.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';import { sameClaimSlot } from './typed-claim.ts';export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };@@ -267,7 +267,7 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i}// GBRA-190 G4: a fact saved without an entity is a row of memory/unattributed; linking it strikes that row in the same write.// GST-2492: so does replacing a fact a strict source held there for the same entity (checked above).- const linking = input.entity_slug != null && candidate.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG;+ const linking = input.entity_slug != null && isHoldingSlug(candidate.source_markdown_slug);if (candidate.source_markdown_slug && candidate.source_markdown_slug !== opts.pageSlug && !linking) {const derived = String(candidate.source ?? '').startsWith('cli:extract-conversation-facts');throw verbError('invalid_params', `replaces_cross_page: fact #${targetId} lives on page ${candidate.source_markdown_slug}${derived ? ', extracted from that conversation page' : ''}.`,diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex e7a9b6711e..b1ee4e873c 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -59,7 +59,7 @@ import { sanitizeText } from '../batch-rows.ts';import { isDurabilityHardened } from '../brain-repo-durability.ts';import { factsFenceHeld } from '../generations/fence-evidence.ts';import { readFenceBlocks } from '../generations/fence.ts';-import { fenceCellReadBackProblem, formatFenceDate, normalizeClaimWhitespace, parseFactsFence, parseFactsFenceFor, renderFactsTable, replaceOrInsertFactsFence, UNATTRIBUTED_MEMORY_SLUG, type FactAttribution, type ParsedFact } from '../facts-fence.ts';+import { fenceCellReadBackProblem, formatFenceDate, normalizeClaimWhitespace, parseFactsFence, parseFactsFenceFor, renderFactsTable, replaceOrInsertFactsFence, isHoldingSlug, type FactAttribution, type ParsedFact } from '../facts-fence.ts';import { FENCE_SOURCE_DEFAULT } from './extract-from-fence.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';@@ -365,9 +365,9 @@ export async function heldFenceFactRows(engine: BrainEngine, sourceId: string, s.map(r => heldEntityCell(slug, r.entity_slug, fenceRowOf(r, Number(r.row_num), r.fact)));}-/** GST-2492: on memory/unattributed a row whose entity has no page names it in the `entity` cell; every other page renders no such cell. */+/** GST-2492: on a holding page a row whose entity has no page names it in the `entity` cell; every other page renders no such cell. */function heldEntityCell(slug: string, entity: string | null, row: ParsedFact): ParsedFact {- return slug === UNATTRIBUTED_MEMORY_SLUG && entity && entity !== slug ? { ...row, entity } : row;+ return isHoldingSlug(slug) && entity && entity !== slug ? { ...row, entity } : row;}/**@@ -413,8 +413,8 @@ export async function planFence(engine: BrainEngine, sourceId: string, entitySlu// same source and visibility (the projection's identity), or that an// earlier row of this group plans, is not adopted a second time. A private// and a world row with one text are two facts and both adopt, as before.- // GST-2492: on memory/unattributed a row also names its entity, and two entities' rows with one claim are two facts.- const cellEntity = (entity: string | null | undefined) => entitySlug === UNATTRIBUTED_MEMORY_SLUG && entity && entity !== entitySlug ? entity : '';+ // GST-2492: on a holding page a row also names its entity, and two entities' rows with one claim are two facts.+ const cellEntity = (entity: string | null | undefined) => isHoldingSlug(entitySlug) && entity && entity !== entitySlug ? entity : '';const dupKey = (claim: string, source: string | undefined, visibility: string, entity: string) => `${claim}\u0000${source || FENCE_SOURCE_DEFAULT}\u0000${visibility}\u0000${entity}`;const planned = new Set<string>();const ownedKeys = new Set(existingFence.facts.filter(f => {@@ -517,7 +517,7 @@ export async function planPageFence(engine: BrainEngine, sourceId: string, slug:}export async function planManagedPage(engine: BrainEngine, authority: MaintenanceAuthority, sourceId: string, entitySlug: string, group: UnfencedFactRow[],- move?: { note: string; from_entity?: string }): Promise<ManagedPagePlan> {+ move?: { note: string; from_entity?: string; from_slug?: string }): Promise<ManagedPagePlan> {const planned = await planPageFence(engine, sourceId, entitySlug, group);if (!planned) return { kind: 'no_page' };const { snapshot, fence } = planned;diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex b57979b8fd..914893ae47 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -331,10 +331,10 @@ export function privateFactNotice(factId?: string | number): Notice {* per session. GST-2492: a fact held in Git (on memory/unattributed) needs nothing, so the notice only says where it is* and when it moves; a fact in the database alone needs the user's word, so the step asks before creating the page.*/-export function entityPageMissingNotice(sourceId: string, entitySlug: string, held = false): Notice {+export function entityPageMissingNotice(sourceId: string, entitySlug: string, held?: { slug: string; committed: boolean }): Notice {const base = { code: 'entity_page_missing', kind: 'info' as const, dedupe_key: `${sourceId}\0${entitySlug}` };if (held) return { ...base,- why: `Saved and committed to Git; held on memory/unattributed until ${entitySlug} has a page. Say that when you report the save. Nothing needs to run: once the page exists, the next maintenance cycle (gbrain dream) moves the fact into the page's Facts table, in its file.` };+ why: `${held.committed ? 'Saved and committed to Git' : 'Saved in the database only, as its folder keeps its pages out of Git'}; held on ${held.slug} until ${entitySlug} has a page. Say that when you report the save. Nothing needs to run: once the page exists, the next maintenance cycle (gbrain dream) moves the fact into the page's Facts table${held.committed ? ', in its file' : ''}.` };const userMessage = `The fact is saved in the database only: ${entitySlug} has no page, so it is in no file in Git. Should I create a page for ${entitySlug}?`;return { ...base,why: `Entity ${entitySlug} has no page in source ${sourceId}, so a fact saved for it is stored in the database only: recall returns it, but it is on no page and in no file in Git. Say that when you report the save, and ask the user whether to create the page; once it exists, the next maintenance cycle (gbrain dream) can move the facts saved for ${entitySlug} into the page's Facts table, in its file.`,diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex cbb5db5221..d8644ac2d4 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -429,7 +429,8 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Preparedif (final) outcome.revision = final.revision;outcome.persistence = { mode: fileCount ? 'filesystem' : 'database', ...(fileCount ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };outcome.write_through = fileCount ? { written: !prepared.noop, ...(row.authority.heldFor ? { held_for: row.authority.heldFor } : {}) }- : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };+ : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? (row.authority.heldFor ? 'db_only' : 'no_repo_configured'),+ ...(row.authority.heldFor ? { held_for: row.authority.heldFor } : {}) };if (prepared.databaseOnlyReason === 'mirror_read_only') outcome.storage = 'database_only';if ((row.operation === 'put_page' || row.operation === 'edit_page' || row.operation === 'append_page') && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);if ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex 020df292a0..643a3d3f62 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -594,13 +594,16 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFif (embedded) await assertManagedFactsEmbedding(engine, session.config, session.embedding);const sourceId = session.authority.sourceId;const groups = new Map<string, FrozenExtractedFact[]>();+ const { holdingHome } = await import('../facts/held-fact-move.ts');for (const fact of facts) {if (ctx.abortSignal?.aborted) throw new DOMException('Fact extraction was aborted before admission.', 'AbortError');if (ctx.notabilityFilter === 'high-only' && fact.notability !== 'high' || ctx.notabilityFilter === 'medium-and-up' && fact.notability === 'low') continue;const resolved = fact.entity_slug ? await resolveEntitySlugWithSource(engine, sourceId, fact.entity_slug) : null;const entitySlug = resolved && resolved.source !== 'fallback_slugify' ? resolved.slug : null;- const slug = entitySlug ?? 'memory/unattributed';const attributed = entitySlug ?? (options.attributeFallback && resolved ? resolved.slug : null);+ // GST-2492: on a strict source a kept fallback entity is held on its holding page (its folder's under a folder rule).+ const home = !entitySlug && attributed ? await holdingHome(engine, sourceId, attributed) : null;+ const slug = entitySlug ?? (home && 'slug' in home ? home.slug : 'memory/unattributed');await authorizeWrite(engine, session.authority, 'extract_facts', slug);await authorizePageVisibility(engine, session.authority, slug);const group = groups.get(slug) ?? [];diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex d58f1bcf60..19043c14d3 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -6,9 +6,9 @@ import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { withHeldFactsFence } from '../facts/unfenced-facts.ts';-import { factsFenceEditor, factsFenceSection, parseFactsFenceFor, formatFenceDate, UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { factsFenceEditor, factsFenceSection, parseFactsFenceFor, formatFenceDate, isHoldingSlug } from '../facts-fence.ts';import { getWorktreeBinding } from './ownership.ts';-import { folderRestricted } from '../search/private-visibility.ts';+import { holdingHome } from '../facts/held-fact-move.ts';import { serializePageToMarkdown } from '../markdown.ts';import { wholeBodySnapshot } from './segmented-apply.ts';import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';@@ -166,17 +166,19 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ}const facts = (p.facts ?? []).map(fact => ({ ...thawFact(fact), embedding_model: fact.embedding ? p.embedding?.model ?? null : null }));// writeSingleFact's opt-in: an unattributed row keeps its fallback entity slug, database-only.- const fallback = (fact: { entity_slug: string | null }) => p.attribute_fallback === true && row.slug === UNATTRIBUTED_MEMORY_SLUG+ const fallback = (fact: { entity_slug: string | null }) => p.attribute_fallback === true && isHoldingSlug(row.slug)&& fact.entity_slug !== null && fact.entity_slug !== row.slug;- // GST-2492 PR 2: on a strict source (Git is the record) a fact routed to memory/unattributed (no entity, or an entity- // with no page) gets a row there, committed before its database row; a held row names its entity in the `entity`- // cell. An entity under a folder access rule, or whose page is soft-deleted (it may be private, and a purge would not- // reach its row there), is not named on that world-readable page and stays database-only.- const holding = row.slug === UNATTRIBUTED_MEMORY_SLUG && !row.authority.databaseOnlyReason+ // GST-2492: on a strict source (Git is the record) a fact routed to a holding page (no entity, or an entity with no+ // page) gets a row there, committed before its database row; a held row names its entity in the `entity` cell. Each+ // fact is held on the page holdingHome names for it (its folder's under a folder access rule); one that page cannot+ // carry (an exact page rule, an unreadable access state, a soft-deleted entity page) stays database-only.+ const holding = isHoldingSlug(row.slug) && !row.authority.databaseOnlyReason&& (await getWorktreeBinding(engine, row.source_id))?.canonical_git === true;- const holdable = async (fact: { entity_slug: string | null }) => holding- && (fact.entity_slug === null || fact.entity_slug === row.slug || !await folderRestricted(engine, row.source_id, fact.entity_slug)- && !(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NOT NULL', [row.source_id, fact.entity_slug])).length);+ const holdable = async (fact: { entity_slug: string | null }) => {+ if (!holding) return false;+ const home = await holdingHome(engine, row.source_id, fact.entity_slug === row.slug ? null : fact.entity_slug);+ return home !== null && 'slug' in home && home.slug === row.slug;+ };if (!facts.length || facts.some(fact => !fallback(fact) && (fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !stored))) {throw factsRefusal('invalid_params', 'The prepared facts do not match their entity.', row,`The request holds no facts, or facts attributed to a page other than ${row.slug}, so none were published.`);diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.tsindex 183f0c7cf4..07c701b07d 100644--- a/src/core/persistence/forget-prepare.ts+++ b/src/core/persistence/forget-prepare.ts@@ -31,7 +31,7 @@ import { MEMBER_PAGE_PREFIX, onOwnedMemoryPageSql } from '../access/member-factsimport { storedOwnerSpeaksForItself } from './page-visibility.ts';import type { CompanionPage, PageMutationFile, PreparedMutation } from './coordinator.ts';import type { WriteAuthority, WriteRequest } from './model.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';import { prepareFenceRowRetirement } from '../facts/fence-fact-append.ts';interface ForgetTarget { id: number; entity_slug: string | null; trust_tier?: string | null }@@ -162,9 +162,9 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque};const own = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });if ((own?.page.id ?? null) !== row.page_id) throw pageIdentityError(own != null || row.page_id === null, 'The page of the forgotten fact was deleted or recreated.');- // GST-2492: a fact held on memory/unattributed for an entity with no page is struck at its own row, in the file and the+ // GST-2492: a fact held on a holding page for an entity with no page is struck at its own row, in the file and the// page, so a rebuild from Git does not bring it back; the claim-wide strike would also reach other entities' rows there.- const held = row.slug === UNATTRIBUTED_MEMORY_SLUG && fact.source_markdown_slug === row.slug && fact.entity_slug !== null && fact.row_num !== null+ const held = isHoldingSlug(row.slug) && fact.source_markdown_slug === row.slug && fact.entity_slug !== null && fact.row_num !== null&& plan.subject !== '*' && own && !own.page.deleted_at && row.worktree_id? await prepareFenceRowRetirement(engine, row, _config, row.slug, { rowNum: Number(fact.row_num), note: 'memory withdrawn', validUntil: new Date(withdrawnAt), forgotten: true }, signal): null;diff --git a/src/core/persistence/git-declared.ts b/src/core/persistence/git-declared.tsindex 25b6d9f4c3..d7a6f9bafd 100644--- a/src/core/persistence/git-declared.ts+++ b/src/core/persistence/git-declared.ts@@ -161,11 +161,22 @@ export function gitHomeRequired(row: Pick<WriteRequest, 'source_id' | 'slug'>, rconst why = 'Git is the source of truth for a git-canonical source: page content reaches the database only after Git commits its file, except for the declared database-only classes (private pages, storage.db_only directories, never-filed derive-phase pages, paths Git ignores).';const message = reason === 'declared_target'? `Source ${row.source_id} is git-canonical and page ${row.slug} is declared database-only${remote || !declared ? '' : ` (${declared})`}, so its file is never committed; nothing was written.`- : `Source ${row.source_id} is git-canonical and this write would store ${reason === 'facts_lane' ? 'rows' : `page ${row.slug}`} in the database without a file in Git, so nothing was written.`;+ : reason === 'facts_lane'+ ? `Source ${row.source_id} is git-canonical and ${row.slug} has no page${remote ? '' : ' while a page rule keeps it to its own readers'}, so no file in Git can hold its fact yet; nothing was written.`+ : `Source ${row.source_id} is git-canonical and this write would store page ${row.slug} in the database without a file in Git, so nothing was written.`;+ // GST-2492: a fact for an entity no holding page can carry (an exact page rule on it) waits for the entity's own page.+ if (reason === 'facts_lane') {+ return opError('git_home_required', message, `Create the page ${row.slug} with put_page, then remember the fact again with a new request_id.`, { reason, why, docs: DOCS,+ fix: { ask_user: true, argv: ['gbrain', 'put', row.slug], mcp: { tool: 'put_page', arguments: { slug: row.slug, content: '<content>' } },+ inputs: [{ name: 'content', how: `The page as Markdown: frontmatter with type and title, then what is known about ${row.slug}. On the CLI, pass it on stdin.` }],+ consent: [], actor: 'agent', requires_exclusive: false, why: `Creates the page ${row.slug}, so the fact has a file; then remember it again. Run it only after the user agrees.`,+ user_message: `${row.slug} has no page yet, so the fact can't be saved in Git. Should I create a page for ${row.slug} and then save the fact on it?`,+ verify: { argv: ['gbrain', 'get', row.slug], mcp: { tool: 'get_page', arguments: { slug: row.slug } } } } });+ }const fix: Action = { ask_user: true, actor: 'user', consent: [], requires_exclusive: false, why, docs: DOCS,user_message: reason === 'declared_target'? `Page ${row.slug} in git-canonical source ${row.source_id} is declared database-only, so gbrain will not commit its file. Should it stay database-only, or move to a path Git tracks (outside storage.db_only and the derive folders, and not private)?`- : `Source ${row.source_id} is git-canonical, so every page needs a home in Git. Should ${reason === 'facts_lane' ? 'these rows' : `page ${row.slug}`} be written to a file Git tracks, or declared database-only (its directory under storage.db_only in gbrain.yml, or the page marked visibility: private)?`,+ : `Source ${row.source_id} is git-canonical, so every page needs a home in Git. Should page ${row.slug} be written to a file Git tracks, or declared database-only (its directory under storage.db_only in gbrain.yml, or the page marked visibility: private)?`,verify: { argv: ['gbrain', 'sources', 'git-gap', row.source_id, '--json'] } };return opError('git_home_required', message, 'Ask the user which git home to configure, then submit the write again with a new request_id.', { reason, why, fix, docs: DOCS });}@@ -204,7 +215,10 @@ export async function assertNoPrivateCommit(tx: BrainEngine, row: WriteRequest,if (privacy) throw privateCommitRefused(row, privacy, row.authority?.remote === true);}-/** For writers with no file form yet (G4, G5): refuses on a strict source, so a database-only row is never written there. */+/**+ * For a fact no holding page can carry (GST-2492: remember for an entity with no page that an exact page rule names):+ * refuses on a strict source, so a database-only row is never written there.+ */export async function assertStrictGitHome(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'slug'>, remote: boolean): Promise<void> {const [source] = await engine.executeRaw<{ strict: boolean }>(`SELECT COALESCE(config->>'canonical','')='git' AS strict FROM sources WHERE id=$1`, [row.source_id]);if (source?.strict === true) throw gitHomeRequired(row, 'facts_lane', remote);diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 3f279ed5d0..1cebb66385 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -10,7 +10,7 @@ import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } frimport { isNullLikeEntity } from '../facts/write-single.ts';import { isFactWithdrawn, planFactWithdrawal } from '../facts/withdrawal.ts';import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';-import { parseFactsFence } from '../facts-fence.ts';+import { isHoldingSlug, parseFactsFence, UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';import { segmentedRememberRefusal, type RememberCarry } from './verb-errors.ts';import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';@@ -26,8 +26,8 @@ import { grantedWriteSource, writeGrantRefusal } from './write-grant.ts';import type { WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { ownerReachesFact, readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';-import { callerIsOwner, currentCallerAccess, folderRestricted, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';+import { assertStrictGitHome } from './git-declared.ts';+import { callerIsOwner, currentCallerAccess, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { projectionEligibleSql } from '../eligibility/sql.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';import { callerMember, factVisibilitySql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug, ownMemberFactIds, scopePageIsShared, scopePageNotShared, SCOPE_PAGE_SLUG } from '../access/member-facts.ts';@@ -121,15 +121,20 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourcconst writeThrough = configuredWriteThrough && !sandbox;if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';- // GST-2492: on a strict source (Git is the record) a named entity with no page holds its fact in Git, as a row of- // memory/unattributed that names the entity, until the entity's page exists. The fences and the authority above ran on- // the entity (decision D1); the holding row is gbrain's own companion write, authorized as a write to that entity.- // An entity under a folder access rule is not named on the world-readable holding page, and a holding page kept out of- // Git would not commit it: both keep the fact database-only, as before.- const holding = !inferred && memberPage === null && entitySlug !== null && !snapshot && writeThrough- && (await getWorktreeBinding(ctx.engine, sourceId))?.canonical_git === true && !await folderRestricted(ctx.engine, sourceId, entitySlug)- ? await ctx.engine.readPageSnapshot(UNATTRIBUTED_MEMORY_SLUG, { sourceId, includeDeleted: true }) ?? 'absent' : null;- const held = holding !== null && (holding === 'absent' || !holding.page.deleted_at && Boolean(holding.page.source_path));+ // GST-2492: on a strict source (Git is the record) a named entity with no page holds its fact in Git, as a row of a+ // holding page that names the entity, until the entity's page exists: memory/unattributed, or for an entity under a+ // folder access rule its folder's holding page, which every rule covering the entity covers by path. The fences and the+ // authority above ran on the entity (decision D1); the holding row is gbrain's own companion write, authorized as a write+ // to that entity. A folder's holding page takes the folder's storage class (database-only under storage.db_only or a path+ // Git ignores, as the entity's own page would be); a shared one kept out of Git keeps the fact database-only, as before.+ const { accessStateUnreadable, holdingHome } = await import('../facts/held-fact-move.ts');+ const home = !inferred && memberPage === null && entitySlug !== null && !snapshot && writeThrough ? await holdingHome(ctx.engine, sourceId, entitySlug) : null;+ // An exact page rule on the entity, or an access state this role cannot read: no holding page carries those readers.+ if (home && 'refused' in home && home.refused === 'page_rule') await assertStrictGitHome(ctx.engine, { source_id: sourceId, slug: entitySlug! }, ctx.remote !== false);+ if (home && 'refused' in home) throw accessStateUnreadable(sourceId);+ const holdingSlug = home && 'slug' in home ? home.slug : null;+ const holding = holdingSlug ? await ctx.engine.readPageSnapshot(holdingSlug, { sourceId, includeDeleted: true }) ?? 'absent' : null;+ const held = holding !== null && (holding === 'absent' || !holding.page.deleted_at && (Boolean(holding.page.source_path) || holdingSlug !== UNATTRIBUTED_MEMORY_SLUG));const page = held && holding !== 'absent' ? holding : snapshot;if (held) fence = true;// An inferred link never designates an owner or reports a missing one.@@ -167,7 +172,7 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourcthrow new InferredTargetRejected('ENTITY_LINK_FAILED');}}- return held && fence ? { slug: UNATTRIBUTED_MEMORY_SLUG, authority, snapshot: page, fence, binding, writeThrough, heldFor: entitySlug }+ return held && fence ? { slug: holdingSlug!, authority, snapshot: page, fence, binding, writeThrough, heldFor: entitySlug }: { slug, authority, snapshot, fence, binding, writeThrough, heldFor: null };}@@ -302,7 +307,8 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco*/async function rememberLanded<T extends Record<string, unknown>>(ctx: OperationContext, row: WriteRequest, response: T): Promise<T> {const intent = row.intent as { visibility?: unknown; fence?: unknown; entity_slug?: unknown } | null;- if (row.authority.heldFor) ctx.emitNotice?.(entityPageMissingNotice(row.source_id, row.authority.heldFor, true));+ if (row.authority.heldFor) ctx.emitNotice?.(entityPageMissingNotice(row.source_id, row.authority.heldFor,+ { slug: row.slug, committed: (response.persistence as { mode?: unknown } | undefined)?.mode === 'filesystem' }));if ((response.write_through as { skipped?: unknown } | undefined)?.skipped === 'entity_page_missing' && typeof intent?.entity_slug === 'string') {const binding = await getWorktreeBinding(ctx.engine, row.source_id);const root = binding?.local_path || (await ctx.engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]))[0]?.local_path@@ -445,8 +451,8 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo// root has no owner refuses when a canonical file carries the claim (Git is the parent: a database-only withdrawal// would come back on a rebuild from Git); a claim only database-only pages carry is withdrawn database-only.const plan = await planFactWithdrawal(ctx.engine, id, sourceId, worldOnly, ownPage ? undefined : targetHidden, ownPage);- // GST-2492: a fact held on memory/unattributed for an entity with no page is struck there too (its row names the entity).- const heldOn = fact.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG && fact.entity_slug !== null ? UNATTRIBUTED_MEMORY_SLUG : null;+ // GST-2492: a fact held on a holding page for an entity with no page is struck there too (its row names the entity).+ const heldOn = isHoldingSlug(fact.source_markdown_slug) && fact.entity_slug !== null ? fact.source_markdown_slug : null;const struck = plan ? plan.slugs.filter(page => plan.subject === '*' || plan.subject === page || page === heldOn) : [];const fileBacked = struck.length > 0 && (await ctx.engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL AND source_path IS NOT NULL LIMIT 1', [sourceId, struck])).length > 0;diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 391ac75ff5..fb50f20003 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -22,7 +22,7 @@ import { fenceAppendPendingTier } from '../eligibility/fence-overlay.ts';import { prepareFenceFactAppend, prepareFenceFactCreate, prepareFenceRowRetirement, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { tightenToPage } from '../facts/visibility.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';import { noteBelief } from '../belief/ledger.ts';import { attestedShareRefused, MEMBER_PAGE_PREFIX, memberPageFrontmatter, memberPageIsOwn, memberPageNotOwned, onOwnedMemoryPageSql, scopePageFrontmatter, scopePageIsShared, scopePageNotShared } from '../access/member-facts.ts';import { claimColumns, storedClaim } from '../facts/typed-claim.ts';@@ -161,7 +161,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst retiredUntil = status === 'superseded' ? supersededValidUntil(decision.candidate!, validFrom) : null;// The fact is published as a row of its entity page's facts fence, file before facts row (facts/fence-fact-append.ts).let fence: FenceFactAppend | undefined;- if (p.fence === true && (snapshot || row.slug === UNATTRIBUTED_MEMORY_SLUG)) {+ if (p.fence === true && (snapshot || isHoldingSlug(row.slug))) {const old = decision.candidate;fence = await prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier: fenceAppendPendingTier(writerTier),supersede: status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null ? { rowNum: Number(old.row_num), validUntil: retiredUntil } : undefined }, signal);@@ -172,10 +172,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequefence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier),frontmatter: scopePageFrontmatter(), heading: '# Scope memory' }, signal);}- // GBRA-190 G4: linking a fact saved without an entity retires its memory/unattributed row in the same publication.+ // GBRA-190 G4: linking a fact saved without an entity retires its holding row in the same publication.const old = status === 'superseded' ? decision.candidate! : null;- const linkedRow = old && old.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG && row.slug !== UNATTRIBUTED_MEMORY_SLUG && old.row_num != null- ? await prepareFenceRowRetirement(engine, row, config, UNATTRIBUTED_MEMORY_SLUG, { rowNum: Number(old.row_num), note: `linked to ${input.entity_slug}`, validUntil: retiredUntil }, signal) : null;+ const linkedRow = old && isHoldingSlug(old.source_markdown_slug) && row.slug !== old.source_markdown_slug && old.row_num != null+ ? await prepareFenceRowRetirement(engine, row, config, old.source_markdown_slug!, { rowNum: Number(old.row_num), note: `linked to ${input.entity_slug}`, validUntil: retiredUntil }, signal) : null;// The belief ledger records the superseded fact in its own stream, so that stream's page key is held too.const supersededStream = status === 'superseded' ? decision.candidate!.source_markdown_slug ?? decision.candidate!.entity_slug ?? null : null;const additionalPageKeys = supersededStream && supersededStream !== row.slug && !linkedRow ? [{ sourceId: row.source_id, slug: supersededStream }] : undefined;diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 00bfbf2697..11a941dba3 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -1,6 +1,6 @@import type { BrainEngine } from '../engine.ts';import { assertRecoveryVersion } from './recovery-version.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';export type Principal = { kind: 'oauth_client' | 'legacy_token' | 'local_cli' | 'local_stdio' | 'application'; id: string };/** `deferred` (PR B, docs/designs/REFRESH_WRITE_BARRIER.md): admitted during a worktree refresh, unclaimable until it is released. */@@ -56,7 +56,7 @@ export interface WriteAuthority {}/** GST-2492: the slug a write is authorized as: a held remember's entity in place of the holding page, else the page itself. */export function authorizedSlug(authority: Pick<WriteAuthority, 'heldFor'>, slug: string): string {- return authority.heldFor && slug === UNATTRIBUTED_MEMORY_SLUG ? authority.heldFor : slug;+ return authority.heldFor && isHoldingSlug(slug) ? authority.heldFor : slug;}/**diff --git a/src/core/persistence/page-identity.ts b/src/core/persistence/page-identity.tsindex 1e65e33783..ba94cc5574 100644--- a/src/core/persistence/page-identity.ts+++ b/src/core/persistence/page-identity.ts@@ -6,7 +6,7 @@* recovers the distinction from the stored message alone (no schema change).*/import { opError, type OperationError } from '../ops/contract.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';+import { isHoldingSlug } from '../facts-fence.ts';import type { WriteRequest } from './model.ts';export const PAGE_MISSING_MESSAGE = 'The accepted page no longer exists.';@@ -48,5 +48,5 @@ export function rememberAcceptsPageCreatedSince(row: Pick<WriteRequest, 'operatisnapshot: { page: { deleted_at?: Date | string | null } } | null): boolean {const p = row.intent;return row.operation === 'remember' && row.page_id === null && snapshot !== null && !snapshot.page.deleted_at && !!p- && (p.member_page === true || p.scope_page === true || (row.slug === UNATTRIBUTED_MEMORY_SLUG && (p.entity_slug == null || row.authority.heldFor === p.entity_slug)));+ && (p.member_page === true || p.scope_page === true || (isHoldingSlug(row.slug) && (p.entity_slug == null || row.authority.heldFor === p.entity_slug)));}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex f0d7d9bd12..4fe933facd 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -10,7 +10,7 @@ import type { Action } from '../agent-output.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';import { fenceOperationError, scanCanonicalFences } from '../fence-repair/refusal.ts';-import { fenceCellReadBackProblem, formatFenceDate, parseFactsFence, parseFactsFenceFor, renderFactsTable, replaceOrInsertFactsFence, UNATTRIBUTED_MEMORY_SLUG, type ParsedFact } from '../facts-fence.ts';+import { fenceCellReadBackProblem, formatFenceDate, parseFactsFence, parseFactsFenceFor, renderFactsTable, replaceOrInsertFactsFence, isHoldingSlug, UNATTRIBUTED_MEMORY_SLUG, type ParsedFact } from '../facts-fence.ts';import { prepareFenceRowRetirement } from '../facts/fence-fact-append.ts';import { noteBelief } from '../belief/ledger.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';@@ -457,12 +457,13 @@ export type FactFenceAdoptionPlan =* every cycle, so the page waits a day or a planner change.*/export async function planFactFenceAdoption(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }>; move?: { note: string; from_entity?: string } }): Promise<FactFenceAdoptionPlan> {+ options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }>; move?: { note: string; from_entity?: string; from_slug?: string } }): Promise<FactFenceAdoptionPlan> {const current = await readFacts(engine, authority.writer.sourceId, options.assignments.map(a => a.id));const facts: FactFenceAssignment[] = options.assignments.map(a => ({ ...a, hash: digest(current.find(f => f.id === a.id)?.value ?? null) }));const intent = { kind: options.move ? HELD_FACT_MOVE : 'managed_maintenance_adopt_fact_fence', expected_revision: options.expectedRevision,source_incarnation: authority.writer.sourceIncarnation, content: options.content, facts, planner: FACT_FENCE_PLANNER,- ...(options.move ? { note: options.move.note, ...(options.move.from_entity ? { from_entity: options.move.from_entity } : {}) } : {}) };+ ...(options.move ? { note: options.move.note, ...(options.move.from_entity ? { from_entity: options.move.from_entity } : {}),+ ...(options.move.from_slug ? { from_slug: options.move.from_slug } : {}) } : {}) };for (let attempt = 0; ; attempt++) {const requestId = maintenanceRequestId({ authority: authority.writer, slug, intent, ...(attempt ? { attempt } : {}) });const prior = await getWriteRequest(engine, authority.writer.principal, requestId);@@ -515,8 +516,11 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteRequesenterClaimStep(clock, 'adoption_parse_fence');const fence = new Map(parseFactsFenceFor(p.content as string, { slug: row.slug }).facts.map(f => [f.rowNum, f]));// GST-2492 PR 2 (gbrain repair facts-home): a database-only fact with no entity, or whose entity has no page, is adopted- // onto memory/unattributed; its cell must name the fact's entity (none for a fact with no entity), so the projection keeps it.- const holdingAdoption = !held && row.slug === UNATTRIBUTED_MEMORY_SLUG;+ // onto a holding page; its cell must name the fact's entity (none for a fact with no entity), so the projection keeps it.+ // A held move onto a holding page (a held row whose entity a folder rule now covers) keeps its entity the same way.+ const holdingAdoption = isHoldingSlug(row.slug);+ // The holding page a held row moves off (`from_slug`, memory/unattributed when absent).+ const fromSlug = held && typeof p.from_slug === 'string' && isHoldingSlug(p.from_slug) ? p.from_slug : UNATTRIBUTED_MEMORY_SLUG;// A held row keyed by a bare name (`from_entity`) moves to the page that name resolved to, and is re-keyed to it.const fromEntity = held && typeof p.from_entity === 'string' ? p.from_entity : null;const ownsRow = (value: Record<string, unknown>, rowNum: number) => holdingAdoption@@ -529,7 +533,7 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteRequesfor (const assignment of facts) {const fact = current.find(f => f.id === assignment.id);if (!fact || digest(fact.value) !== assignment.hash || !ownsRow(fact.value, assignment.row_num) || fact.value.expired_at !== null- || (held ? fact.value.source_markdown_slug !== UNATTRIBUTED_MEMORY_SLUG || fact.value.row_num === null : fact.value.row_num !== null)) {+ || (held ? fact.value.source_markdown_slug !== fromSlug || fact.value.row_num === null : fact.value.row_num !== null)) {throw opError('revision_conflict', 'A legacy fact changed, was already adopted or moved to another owner before adoption.',`A legacy fact on ${row.slug} in ${row.source_id} changed before fact-fence adoption request ${row.request_id} published; nothing was written. The next fact backfill run re-reads the facts and plans a fresh request.`,{ fix: receiptFix(row) });@@ -554,7 +558,7 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteRequesawait check(engine, false);const pageRow = { ...row, intent: { kind: 'managed_maintenance_page', content: p.content, expected_revision: p.expected_revision } };const prepared = await preparePageMutation(unbounded, pageRow, config, undefined, undefined, { clock });- const holding = held ? await prepareFenceRowRetirement(unbounded, pageRow, config, UNATTRIBUTED_MEMORY_SLUG, { note: String(p.note), remove: p.note === 'moved',+ const holding = held ? await prepareFenceRowRetirement(unbounded, pageRow, config, fromSlug, { note: String(p.note), remove: p.note === 'moved',rowNum: (await readFacts(engine, row.source_id, facts.map(f => f.id))).map(f => Number(f.value.row_num)), validUntil: null }) : null;return { ...prepared, ...(holding ? { companions: [holding] } : {}), validate: async tx => { await prepared.validate?.(tx); await check(tx, true); }, apply: async tx => {// Runs ahead of the page import and its canonical projection, so the@@ -562,14 +566,14 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques// The fence cell's parsed text is written back with the row number: the// projection expires any row whose (row_num, fact, visibility) differs from// its fence row and inserts a new one, which would lose the legacy id.- const adopted = await tx.executeRaw(`UPDATE facts f SET row_num=a.row_num,source_markdown_slug=$2,fact=a.fact${held ? ',entity_slug=$2' : ''}+ const adopted = await tx.executeRaw(`UPDATE facts f SET row_num=a.row_num,source_markdown_slug=$2,fact=a.fact${held && !holdingAdoption ? ',entity_slug=$2' : ''}FROM jsonb_to_recordset($3::text::jsonb) AS a(id integer,row_num integer,fact text)WHERE f.source_id=$1 AND f.id=a.id AND ${held ? 'f.source_markdown_slug=$4' : 'f.row_num IS NULL'} RETURNING f.id`,- [row.source_id, row.slug, JSON.stringify(facts.map(({ id, row_num }) => ({ id, row_num, fact: fence.get(row_num)!.claim }))), ...(held ? [UNATTRIBUTED_MEMORY_SLUG] : [])]);+ [row.source_id, row.slug, JSON.stringify(facts.map(({ id, row_num }) => ({ id, row_num, fact: fence.get(row_num)!.claim }))), ...(held ? [fromSlug] : [])]);if (adopted.length !== facts.length) throw opError('revision_conflict', 'A legacy fact was adopted by another run.',`Another run adopted a legacy fact on ${row.slug} in ${row.source_id} while request ${row.request_id} was publishing, so its transaction rolled back. Read the receipt with gbrain write-request -- ${row.request_id} for the final state before planning any new adoption.`,{ fix: receiptFix(row) });- if (held) noteBelief({ kind: 'transferred', fromSlug: UNATTRIBUTED_MEMORY_SLUG, table: 'facts', ids: facts.map(f => f.id) });+ if (held) noteBelief({ kind: 'transferred', fromSlug, table: 'facts', ids: facts.map(f => f.id) });const outcome = await prepared.apply(tx);return { ...outcome, facts_adopted: facts.length };} };diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 58d1134643..6a6eb090ff 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -292,6 +292,13 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {Object.assign(fenced, { canonical: 'worktree_refreshing', docs: error.docs, fix: error.fix, retryable: true, requestId: error.requestId });throw markNotAdmitted(fenced);}+ // GST-2492: a strict source that has no file to hold the fact (an exact page rule on a page-less entity) or cannot read+ // its access state refuses before admission; the frozen code stays and the canonical code, reason and fix ride along.+ if (error.code === 'git_home_required' || error.code === 'access_policy_pending') {+ const strict = verbError(error.code === 'git_home_required' ? 'invalid_params' : 'unavailable', error.message, error.suggestion ?? 'Inspect writer status before retrying.');+ Object.assign(strict, { canonical: error.code, reason: error.reason, why: error.why, docs: error.docs, fix: error.fix });+ throw strict;+ }const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)? 'invalid_params' : 'unavailable';diff --git a/src/core/repair/facts-home.ts b/src/core/repair/facts-home.tsindex 87f7739c08..2c4ede94a0 100644--- a/src/core/repair/facts-home.ts+++ b/src/core/repair/facts-home.ts@@ -1,28 +1,30 @@/*** `gbrain repair facts-home --source <id> [--apply --expect <hash>]` (GST-2492 PR 2): give the facts of a strict source* that live in the database alone a home in Git. The preview (facts/facts-home.ts `scanFactsHome`) lists every such fact- * by group and writes nothing: a fact with no entity, or for an entity with no page, is what the apply writes to- * memory/unattributed (a held row names its entity, so the upkeep move takes it to the entity's page once that page- * exists); a fact whose entity has a page is left to that upkeep step; a fact the Facts table cannot render, one for an- * entity under a folder access rule, a held row its page cannot take, and a held row older than 30 days (with the nearest- * existing page the resolver finds) are listed and left alone. `--apply --expect <hash>` writes exactly the previewed set- * in one maintenance publication through the write door; the facts rows move in place (ids, vectors and provenance kept).+ * by group and writes nothing: a fact with no entity, or for an entity with no page, is what the apply writes to its+ * holding page, memory/unattributed or, for an entity under a folder access rule, the holding page of its folder (a held+ * row names its entity, so the upkeep move takes it to the entity's page once that page exists); a fact whose entity has+ * a page is left to that upkeep step; a fact the Facts table cannot render, one no holding page can carry (an exact page+ * rule on its entity), a held row its page cannot take, and a held row older than 30 days (with the nearest existing page+ * the resolver finds) are listed and left alone. `--apply --expect <hash>` writes exactly the previewed set+ * in one maintenance publication per holding page through the write door; the facts rows move in place (ids, vectors and+ * provenance kept).* A source that isn't strict lists nothing and says so (its database keeps such facts by design), so the bare preview a* remediation plan prints runs as pasted. Runs only when named; never on upgrade.*/import type { BrainEngine } from '../engine.ts';import { opError, OperationError, type OperationContext } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';-import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';import { digest } from '../persistence/digest.ts';import { maintenancePreflight, planFactFenceAdoption, readFacts, submitPlannedFactFenceAdoption } from '../persistence/prepared-maintenance.ts';import { clearApprovedSet, loadApprovedSet, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { FACTS_HOME_DOCS, factsHomePreviewCommand, scanFactsHome, type FactsHomeRow, type FactsHomeScan } from '../facts/facts-home.ts';import { planPageFence } from '../facts/unfenced-facts.ts';-import { submitPageMutation } from '../persistence/page-mutations.ts';-import { repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';+import { ensurePageForHeldRows } from '../facts/held-fact-move.ts';+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';+import { type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';-interface ApprovedFact { id: number; value: string }+interface ApprovedFact { id: number; value: string; home: string }interface HomeItem extends RepairItem { facts: ApprovedFact[]; hash: string }/** At most this many facts are written per preview, in one publication; the preview after an apply lists the rest. */@@ -40,10 +42,12 @@ function previewChanged(hash: string, sourceId: string): OperationError {const DETAIL: Record<FactsHomeRow['group'], (row: FactsHomeRow) => string> = {entity_page_exists: row => `${row.entity_slug} has a page; the extract_facts upkeep step moves this fact there (gbrain dream --phase extract_facts runs it now)`,- entity_page_missing: row => `${row.entity_slug} has no page; the apply writes it to ${UNATTRIBUTED_MEMORY_SLUG} as a held row naming ${row.entity_slug}`,- no_entity: () => `no entity; the apply writes it to ${UNATTRIBUTED_MEMORY_SLUG}`,+ entity_page_missing: row => `${row.entity_slug} has no page; the apply writes it to ${row.home} as a held row naming ${row.entity_slug}`,+ no_entity: row => `no entity; the apply writes it to ${row.home}`,cannot_render: row => `the Facts table cannot render it as it stands (${row.reason}); it stays database-only, active and searchable`,- folder_restricted: row => `${row.entity_slug} is under a folder access rule, so it is not named on the world-readable holding page; it stays database-only`,+ folder_restricted: row => row.reason === 'page_rule'+ ? `a page rule keeps ${row.entity_slug} to its own readers, which no holding page carries; create the page (gbrain put ${row.entity_slug}) and the extract_facts upkeep step fences the fact there; it stays database-only until then`+ : `the folder access rules covering ${row.entity_slug} cannot be read now, so no holding page is chosen; it stays database-only (retry later)`,entity_page_deleted: row => `${row.entity_slug} is deleted (it may be private, and its purge would not reach the holding page); restore the page (gbrain restore ${row.entity_slug}) or purge it; the fact stays database-only`,held_fact_unmovable: row => `held for ${row.entity_slug}, whose page cannot take it (${row.reason}); edit the row, or forget the duplicate`,held_over_30_days: row => `held for ${row.entity_slug} since ${row.held_since} and the page still does not exist; ${row.nearest ? `the nearest existing page is ${row.nearest}` : 'no existing page resolves to it'}`,@@ -53,12 +57,12 @@ const DETAIL: Record<FactsHomeRow['group'], (row: FactsHomeRow) => string> = {const hashParts = (scope: RepairScope, scan: FactsHomeScan, approved: ApprovedFact[]) =>({ kind: 'facts-home-v1', brain_id: scope.brain_id, source_id: scan.source_id, approved: approved.map(f => [f.id, f.value]),- listed: scan.rows.map(row => [row.id, row.group, row.reason ?? null, row.nearest ?? null]) });+ listed: scan.rows.map(row => [row.id, row.group, row.reason ?? null, row.nearest ?? null, row.home ?? null]) });/** The previewed facts with the digest of each stored row, as the apply re-checks them. */async function approvedFacts(engine: BrainEngine, scan: FactsHomeScan): Promise<ApprovedFact[]> {- const ids = scan.homeable.slice(0, MAX_PER_APPLY).map(row => Number(row.id));- return (await readFacts(engine, scan.source_id, ids)).map(fact => ({ id: fact.id, value: digest(fact.value) })).sort((a, b) => a.id - b.id);+ const homes = new Map(scan.homeable.slice(0, MAX_PER_APPLY).map(row => [Number(row.id), row.home]));+ return (await readFacts(engine, scan.source_id, [...homes.keys()])).map(fact => ({ id: fact.id, value: digest(fact.value), home: homes.get(fact.id)! })).sort((a, b) => a.id - b.id);}export const factsHomeRepair: RepairHandler = {@@ -80,7 +84,8 @@ export const factsHomeRepair: RepairHandler = {const approved = await approvedFacts(engine, scan);const hash = previewHash(hashParts(scope, scan, approved));const item = (facts: ApprovedFact[], key: string): HomeItem[] => facts.length- ? [{ cursor: { phase: 0, id: 1 }, source_id: sourceId, slug: UNATTRIBUTED_MEMORY_SLUG, chars: 0, action: `hold ${facts.length} fact(s)`, facts, hash: key }] : [];+ ? [{ cursor: { phase: 0, id: 1 }, source_id: sourceId, slug: UNATTRIBUTED_MEMORY_SLUG, chars: 0,+ action: `hold ${facts.length} fact(s) on ${[...new Set(facts.map(fact => fact.home))].sort().join(', ')}`, facts, hash: key }] : [];if (opts?.apply) {if (!opts.expect) {throw opError('invalid_params', 'gbrain repair facts-home --apply writes only the set a preview printed.',@@ -107,7 +112,7 @@ export const factsHomeRepair: RepairHandler = {}},render(details) {- return [` each written fact moves in place onto ${UNATTRIBUTED_MEMORY_SLUG} in one commit; check afterwards with ${details.verify}; guide: ${details.docs}`];+ return [` each written fact moves in place onto its holding page, one commit per page; check afterwards with ${details.verify}; guide: ${details.docs}`];},};@@ -117,27 +122,35 @@ const changed = (reason: string, detail: Record<string, unknown> = {}): RepairItasync function homeFacts(ctx: OperationContext, sourceId: string, approved: ApprovedFact[]): Promise<RepairItemOutcome> {const engine = ctx.engine;const scan = await scanFactsHome(engine, sourceId);- const current = new Map((await approvedFacts(engine, scan)).map(fact => [fact.id, fact.value]));- if (approved.some(fact => current.get(fact.id) !== fact.value)) return changed('facts_changed');- const rows = scan.homeable.filter(row => approved.some(fact => fact.id === Number(row.id)));+ const current = new Map((await approvedFacts(engine, scan)).map(fact => [fact.id, `${fact.value}\0${fact.home}`]));+ if (approved.some(fact => current.get(fact.id) !== `${fact.value}\0${fact.home}`)) return changed('facts_changed');const authority = await maintenancePreflight(engine, sourceId);if (!authority) return { applied: false, outcome: 'skipped', reason: 'no_maintenance_authority' };- // Maintenance publishes only to a page that exists, so a source with no holding page yet gets the empty one first,- // as the first fact saved with no entity creates it (a note titled Unattributed memory).- if (!await engine.readPageSnapshot(UNATTRIBUTED_MEMORY_SLUG, { sourceId, includeDeleted: true })) {- const local = { ...ctx, remote: false, sourceId } as OperationContext;- await submitPageMutation(local, { operation: 'put_page', params: { slug: UNATTRIBUTED_MEMORY_SLUG,- request_id: await repairRequestId(local, 'facts-home', { source_id: sourceId, slug: UNATTRIBUTED_MEMORY_SLUG }, 'holding-page'),- content: '---\ntype: note\ntitle: Unattributed memory\n---\n' } });+ // One maintenance publication per holding page; every approved fact was re-checked above, so a changed one writes none.+ const receipts: Array<{ slug: string; facts: number; request_id: string; receipt: Record<string, unknown> }> = [];+ for (const home of [...new Set(approved.map(fact => fact.home))].sort()) {+ const rows = scan.homeable.filter(row => row.home === home && approved.some(fact => fact.id === Number(row.id)));+ const outcome = await homeOnPage(ctx, authority, sourceId, home, rows);+ if ('applied' in outcome) return receipts.length ? { ...outcome, detail: { ...outcome.detail, written: receipts } } : outcome;+ receipts.push(outcome);}- const planned = await planPageFence(engine, sourceId, UNATTRIBUTED_MEMORY_SLUG, rows);+ return { applied: true, outcome: 'held', detail: { facts: receipts.reduce((n, r) => n + r.facts, 0), pages: receipts } };+}++async function homeOnPage(ctx: OperationContext, authority: NonNullable<Awaited<ReturnType<typeof maintenancePreflight>>>, sourceId: string, home: string,+ rows: FactsHomeScan['homeable']): Promise<RepairItemOutcome | { slug: string; facts: number; request_id: string; receipt: Record<string, unknown> }> {+ const engine = ctx.engine;+ // Maintenance publishes only to a page that exists, so a holding page that does not exist yet is created empty first,+ // as the first fact held there creates it (a note titled Unattributed memory).+ await ensurePageForHeldRows(engine, sourceId, home, ctx);+ const planned = await planPageFence(engine, sourceId, home, rows);if (!planned) return changed('holding_page_deleted');const { snapshot, fence } = planned;if ('warnings' in fence) return { applied: false, outcome: 'skipped', reason: 'holding_fence_malformed', detail: { warnings: fence.warnings } };if (fence.rejected.length) return changed('fence_rejected', { rejected: fence.rejected.map(r => ({ fact_id: r.fact_id, class: r.class })) });- const plan = await planFactFenceAdoption(engine, authority, UNATTRIBUTED_MEMORY_SLUG, { content: fence.body, expectedRevision: snapshot.revision,+ const plan = await planFactFenceAdoption(engine, authority, home, { content: fence.body, expectedRevision: snapshot.revision,assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })) });if (plan.kind === 'suppressed') return { applied: false, outcome: 'skipped', reason: 'refused_recently', detail: { request_id: plan.prior.request_id, error_code: plan.prior.error_code } };- const receipt = await submitPlannedFactFenceAdoption(engine, authority, UNATTRIBUTED_MEMORY_SLUG, plan, true);- return { applied: true, outcome: 'held', detail: { facts: fence.assignments.length, request_id: plan.requestId, receipt } };+ const receipt = await submitPlannedFactFenceAdoption(engine, authority, home, plan, true);+ return { slug: home, facts: fence.assignments.length, request_id: plan.requestId, receipt };}diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 9c07b9af11..4d4634c2d3 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -28,6 +28,7 @@ import { isValidSourceId } from '../source-id.ts';import { asciiLower, asciiLowerSql, edgeTrimSql } from '../edge-whitespace.ts';import { ACCESS_ID_RE, hasReaders, MEMBER_PAGE_PREFIX, normalizePrincipal, readersAllow, validIdentity } from '../access/principals.ts';import { ruleCoversSql, validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';+import { holdingSlugSql, UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';@@ -847,11 +848,30 @@ export function privateProvenanceFilterUnderPolicy(factAlias: string): string {/*** A fact is never wider than the page it is about: hide a fact whose entity page (`entity_slug`, looked up in the fact's* own source) the current caller cannot read under the read policy its page reads use, so a member the page's readers- * name keeps the fact and every other remote caller loses it. A fact with no entity page passes. Read sites only; it- * only ever narrows.+ * name keeps the fact and every other remote caller loses it. A fact held on a holding page (GST-2492) is also judged by+ * that page as a page, not as lineage, so a folder's holding page hides its facts exactly as it hides itself. A fact with+ * no entity page passes. Read sites only; it only ever narrows.*/export function privateEntityFilterForCaller(factAlias: string, perCandidate = false): string {- return `NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug = ${factAlias}.entity_slug AND NOT ${privatePagesFilterForCaller('entity_pp')}${perCandidate ? ' OFFSET 0' : ''})`;+ const held = `CASE WHEN ${factAlias}.entity_slug IS NOT NULL AND ${holdingSlugSql(`${factAlias}.source_markdown_slug`)} THEN ${factAlias}.source_markdown_slug END`;+ return `(NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = ${factAlias}.source_id AND entity_pp.slug IN (${factAlias}.entity_slug, ${held}) AND NOT ${privatePagesFilterForCaller('entity_pp')}${perCandidate ? ' OFFSET 0' : ''})${sharedHeldRuledSql(factAlias)})`;+}++/**+ * GST-2492: a fact still held on the shared memory/unattributed page for an entity a folder rule now covers (a rule+ * applied by sync, or a remember planned before the rule, until the held-fact move takes it to the folder's page) reads+ * as that entity's page would: only for a caller who satisfies every covering rule, and for nobody while a pending+ * narrowing covers it. The owner under the opt-in reads it, as it reads every restricted page.+ */+function sharedHeldRuledSql(factAlias: string): string {+ const access = currentCallerAccess();+ if (access.ownerReadsRestricted) return '';+ const satisfied = access.restricted ? access.satisfiedRuleIds : [];+ const ids = satisfied.length && satisfied.every(validQualifiedRuleId) ? [...new Set(satisfied)].sort() : [];+ const array = ids.length ? `ARRAY[${ids.map(id => `'${id}'`).join(', ')}]::text[]` : 'ARRAY[]::text[]';+ return ` AND NOT (${factAlias}.entity_slug IS NOT NULL AND ${factAlias}.source_markdown_slug = '${UNATTRIBUTED_MEMORY_SLUG}'`+ + ` AND (NOT COALESCE(gbrain_access_folder_rules(${factAlias}.source_id, ${factAlias}.entity_slug) <@ ${array}, true)`+ + ` OR gbrain_access_pending_covers(${factAlias}.source_id, ${factAlias}.entity_slug)))`;}/**diff --git a/src/core/trust/release-publish.ts b/src/core/trust/release-publish.tsindex 9dd2783a2d..e997031410 100644--- a/src/core/trust/release-publish.ts+++ b/src/core/trust/release-publish.ts@@ -38,8 +38,8 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { prepareFenceFactAppend } from '../facts/fence-fact-append.ts';import { assertFactNotWithdrawn } from '../facts/single-prepare.ts';import { FENCE_SOURCE_DEFAULT } from '../facts/extract-from-fence.ts';-import { parseFactsFenceFor, UNATTRIBUTED_MEMORY_SLUG, type ParsedFact } from '../facts-fence.ts';-import { holdsInGit } from '../facts/held-fact-move.ts';+import { isHoldingSlug, parseFactsFenceFor, type ParsedFact } from '../facts-fence.ts';+import { holdingHome } from '../facts/held-fact-move.ts';import { materializedPage, segmentedOverCeiling } from '../persistence/segmented-apply.ts';import { claimColumns } from '../facts/typed-claim.ts';import { getWriteGateHold, releaseWriteGateHold, type WriteGateHold } from '../write-gate-store.ts';@@ -110,13 +110,15 @@ export async function submitTrustRelease(engine: BrainEngine, holdId: number, byif (!hold || hold.kind !== 'fact') return null;let target = releaseTarget(hold);let snapshot = target ? await engine.readPageSnapshot(target.slug, { sourceId: hold.source_id, includeDeleted: true }) : null;- // GST-2492 PR 2: on a strict source a fact with no entity, or whose entity has no page, is released onto- // memory/unattributed (a held row names its entity), so it is committed to Git before its database row.- if ((!target || !snapshot && target.mode === 'append') && await holdsInGit(engine, hold.source_id, str(hold.payload.entity_slug))) {- target = { slug: UNATTRIBUTED_MEMORY_SLUG, mode: 'append' };- snapshot = await engine.readPageSnapshot(UNATTRIBUTED_MEMORY_SLUG, { sourceId: hold.source_id, includeDeleted: true });+ // GST-2492 PR 2: on a strict source a fact with no entity, or whose entity has no page, is released onto its holding page+ // (memory/unattributed, or its folder's under a folder rule; a held row names its entity), so it is committed to Git+ // before its database row.+ const home = !target || !snapshot && target.mode === 'append' ? await holdingHome(engine, hold.source_id, str(hold.payload.entity_slug)) : null;+ if (home && 'slug' in home) {+ target = { slug: home.slug, mode: 'append' };+ snapshot = await engine.readPageSnapshot(home.slug, { sourceId: hold.source_id, includeDeleted: true });}- if (!target || !snapshot && target.slug !== UNATTRIBUTED_MEMORY_SLUG) return null;+ if (!target || !snapshot && !isHoldingSlug(target.slug)) return null;const { initializeLocalPersistence, requestPrincipalForContext } = await import('../persistence/page-mutations.ts');const { submissionAuthority } = await import('../persistence/authority.ts');const { admitWrite, getWriteRequest } = await import('../persistence/journal.ts');@@ -190,13 +192,13 @@ export async function prepareTrustReleaseMutation(engine: BrainEngine, row: Writconst hold = await getWriteGateHold(engine, intent.hold_id);if (!current(hold)) throw decidedMeanwhile(intent.hold_id);const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- const firstHolding = !snapshot && row.slug === UNATTRIBUTED_MEMORY_SLUG && row.page_id === null && intent.mode === 'append';+ const firstHolding = !snapshot && isHoldingSlug(row.slug) && row.page_id === null && intent.mode === 'append';if (!firstHolding && (!snapshot || snapshot.page.deleted_at || snapshot.page.id !== row.page_id)) {throw pageIdentityError(Boolean(snapshot && !snapshot.page.deleted_at), `The page h${hold.id} is released into was deleted or recreated; the fact stays held.`);}const p = hold.payload;const fact: NewFact & { valid_from: Date } = {- fact: String(p.fact ?? ''), kind: (str(p.kind) ?? 'fact') as NewFact['kind'], entity_slug: str(p.entity_slug) ?? (row.slug === UNATTRIBUTED_MEMORY_SLUG ? null : row.slug),+ fact: String(p.fact ?? ''), kind: (str(p.kind) ?? 'fact') as NewFact['kind'], entity_slug: str(p.entity_slug) ?? (isHoldingSlug(row.slug) ? null : row.slug),visibility: p.visibility === 'world' ? 'world' : 'private', source: str(p.source) ?? `trust release h${hold.id}`, context: str(p.context),source_session: str(p.source_session), confidence: 1, valid_from: str(p.valid_from) ? new Date(String(p.valid_from)) : new Date(),valid_until: str(p.valid_until) ? new Date(String(p.valid_until)) : null, embedding: null, embedding_model: null, ...claimColumns(p as never),diff --git a/test/fixtures/goldens/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.jsonindex bb0cbce395..642a7dc14f 100644--- a/test/fixtures/goldens/sql-text/facts.json+++ b/test/fixtures/goldens/sql-text/facts.json@@ -151,8 +151,8 @@"number","array<string>"],- "sql": "WITH cur AS ( SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND (NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug = facts.entity_slug AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = entity_pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) ) SELECT entity_slug, dimension, json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values FROM cur GROUP BY entity_slug, dimension HAVING count(DISTINCT value) >= 2 AND count(DISTINCT source) >= 2 ORDER BY entity_slug, dimension",- "textSha256": "d7541bc618e375f4dfe29011fb137d8b97adbe095e6cf365e6a04a7cdc842e85"+ "sql": "WITH cur AS ( SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND (NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND (NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug IN (facts.entity_slug, CASE WHEN facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') THEN facts.source_markdown_slug END) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = entity_pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) AND NOT (facts.entity_slug IS NOT NULL AND facts.source_markdown_slug = 'memory/unattributed' AND (NOT COALESCE(gbrain_access_folder_rules(facts.source_id, facts.entity_slug) <@ ARRAY[]::text[], true) OR gbrain_access_pending_covers(facts.source_id, facts.entity_slug))))) ) SELECT entity_slug, dimension, json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values FROM cur GROUP BY entity_slug, dimension HAVING count(DISTINCT value) >= 2 AND count(DISTINCT source) >= 2 ORDER BY entity_slug, dimension",+ "textSha256": "eca0f11591599ab99416974391928a52c8a4327839fdb2ce7c55f20d0666ae6c"}]},@@ -245,8 +245,8 @@"number","boolean"],- "sql": "SELECT DISTINCT ON (dimension) dimension, value, confidence, source_markdown_slug AS source, valid_from, valid_until AS valid_to, COALESCE(dim_status, 'active') AS status, id AS fact_id FROM facts WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND (NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug = facts.entity_slug AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = entity_pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE($3::timestamptz, now()) AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE($4::timestamptz, now()) AND confidence >= $5 AND ($6::boolean OR dim_status IS NULL OR dim_status = 'active') ORDER BY dimension, valid_from DESC NULLS LAST, confidence DESC, id DESC",- "textSha256": "c4cd121ae13f2d8cf3d07846b51b90968623bfc04bc5ab919afa5cdc3c2f51ab"+ "sql": "SELECT DISTINCT ON (dimension) dimension, value, confidence, source_markdown_slug AS source, valid_from, valid_until AS valid_to, COALESCE(dim_status, 'active') AS status, id AS fact_id FROM facts WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages elig_dp WHERE elig_dp.source_id = facts.source_id AND elig_dp.slug = ANY(ARRAY[facts.source_markdown_slug, facts.entity_slug]) AND elig_dp.deleted_at IS NOT NULL) AND (NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT (((((pp.page_readers IS NULL AND NOT (pp.frontmatter ? 'readable_by'))) AND (pp.folder_rule_ids IS NULL OR COALESCE(gbrain_access_lineage_rules(pp.source_id, pp.folder_rule_ids) <@ ARRAY[]::text[], true)) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = pp.source_id AND (starts_with(pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(pp.id, pp.source_id, pp.type, pp.frontmatter))) AND ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pp.frontmatter ? 'pinned_question', false) AND NOT (pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type IN ('atom', 'question') OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END))))) AND (NOT EXISTS (SELECT 1 FROM pages entity_pp WHERE entity_pp.source_id = facts.source_id AND entity_pp.slug IN (facts.entity_slug, CASE WHEN facts.entity_slug IS NOT NULL AND (facts.source_markdown_slug = 'memory/unattributed' OR facts.source_markdown_slug LIKE '%/memory/unattributed') THEN facts.source_markdown_slug END) AND NOT ((((entity_pp.page_readers IS NULL AND NOT (entity_pp.frontmatter ? 'readable_by'))) AND (entity_pp.folder_rule_ids IS NULL) AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = entity_pp.source_id AND (starts_with(entity_pp.slug, pc.prefix) AND (pc.prefix = '' OR right(pc.prefix, 1) = '/' OR entity_pp.slug = pc.prefix))) AND NOT (SELECT gbrain_access_state_unreadable()) AND ((entity_pp.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (entity_pp.frontmatter ? 'derived_from')) OR NOT gbrain_access_origin_restricted(entity_pp.id, entity_pp.source_id, entity_pp.type, entity_pp.frontmatter))) AND ((COALESCE(entity_pp.frontmatter->>'visibility', CASE WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(entity_pp.frontmatter ? 'pinned_question', false) AND NOT (entity_pp.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(entity_pp.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(entity_pp.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN entity_pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = entity_pp.source_id AND derived_origin.slug = entity_pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (entity_pp.type IN ('atom', 'question') OR (entity_pp.type = 'concept' AND entity_pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = entity_pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN entity_pp.type = 'event' AND entity_pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = entity_pp.source_id AND chronicle_origin.slug = entity_pp.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false) AND NOT (chronicle_origin.frontmatter->>'visibility' IS NULL AND (COALESCE(translate(btrim(chronicle_origin.frontmatter->>'access', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('private','restricted','confidential'), false) OR COALESCE(translate(btrim(chronicle_origin.frontmatter->>'confidentiality', (E'\\u0020\\u0009\\u000a\\u000b\\u000c\\u000d' || CASE WHEN current_setting('server_encoding') = 'UTF8' THEN convert_from(decode('c2a0e19a80e28080e28081e28082e28083e28084e28085e28086e28087e28088e28089e2808ae280a8e280a9e280afe2819fe38080efbbbf', 'hex'), 'UTF8') ELSE '' END)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') IN ('confidential','secret','private','restricted'), false)))) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = entity_pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(entity_pp.frontmatter->'derived_from') = 'array' THEN entity_pp.frontmatter->'derived_from' ELSE jsonb_build_array(entity_pp.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)))) AND NOT (facts.entity_slug IS NOT NULL AND facts.source_markdown_slug = 'memory/unattributed' AND (NOT COALESCE(gbrain_access_folder_rules(facts.source_id, facts.entity_slug) <@ ARRAY[]::text[], true) OR gbrain_access_pending_covers(facts.source_id, facts.entity_slug))))) AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE($3::timestamptz, now()) AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE($4::timestamptz, now()) AND confidence >= $5 AND ($6::boolean OR dim_status IS NULL OR dim_status = 'active') ORDER BY dimension, valid_from DESC NULLS LAST, confidence DESC, id DESC",+ "textSha256": "638794157387c751871b58f546514a40714a959ac39852287c9af89e09929b80"}]},diff --git a/test/folder-holding-page-gst2492.test.ts b/test/folder-holding-page-gst2492.test.tsnew file mode 100644index 0000000000..03898b8e0d--- /dev/null+++ b/test/folder-holding-page-gst2492.test.ts@@ -0,0 +1,445 @@+/**+ * GST-2492 (last PR): the folder-rule holding page on a strict source.+ *+ * 1. Protects: on a source whose pages are canonical in Git, a fact for an entity with no page that a folder access rule+ * covers is held on the holding page of the entity's own folder (partners/alice-example/deal-notes on+ * partners/alice-example/memory/unattributed), committed through the door before its row, with exactly the entity's+ * readers: every prefix rule covering the entity covers that page by path, a pending narrowing too. A rebuild from a+ * clone of HEAD keeps it; the upkeep move takes it into the entity's page once that exists. A folder rule's own apply+ * moves the held facts it starts covering off the shared memory/unattributed (its preview counts them), leaving nothing+ * there but the note "moved". The owner reads every holding page as the product defines (the opt-in on, or named by+ * the rules). A folder under storage.db_only or a path Git ignores gets a database-only holding page, never committed.+ * An exact page rule on the entity refuses git_home_required (facts_lane) and an unreadable access state answers wait,+ * never storage_error. gbrain repair facts-home moves older database-only facts of such entities to that page.+ * 2. Fails when: a ruled entity's fact stays database-only on a strict source, is named on the world-readable page, a+ * caller outside the rules reads or learns of the holding page, a narrowing leaves a held row readable by a member it+ * excludes, the owner is shut out, a database-only folder's holding page is committed, or a refusal reads storage_error.+ * 3. Existing coverage: test/remember-strict-held-gst2492.test.ts (the shared page), test/repair-facts-home-gst2492.test.ts.+ * 4. Real seams: the coordinated write and the write door on PGLite and Postgres (DATABASE_URL), a managed Git checkout, the+ * operation handler as the local CLI calls it, MCP dispatch with member-bound and owner-bound tokens, the access rule CLI+ * (git store), the policy engine (database store), and a rebuild of a fresh database from a clone of HEAD.+ */+import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { performSync } from '../src/commands/sync.ts';+import { runAccessRules } from '../src/commands/access-rules.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { parseFactsFenceFor } from '../src/core/facts-fence.ts';+import { isFactEntityPage, isIdentityEntity } from '../src/core/entities/resolve.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { scanFactsHome } from '../src/core/facts/facts-home.ts';+import { folderRulesAllow, type FolderRule } from '../src/core/access/folder-rules.ts';+import { policySeams, proposeRevision, resumePolicy } from '../src/core/access/policy.ts';+import { identityFor } from '../src/core/access/principals.ts';+import { setOwner, setOwnerReadsRestricted } from '../src/core/access/owner.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { resolveRepairScope, type RepairKind } from '../src/core/repair/core.ts';+import { repairRunner } from '../src/core/repair/registry.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { durableGitRepo, git } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects, type ManagedBrain } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const HOLD = 'memory/unattributed';+const ENTITY = 'partners/alice-example/deal-notes';+const FOLDER_HOLD = 'partners/alice-example/memory/unattributed';+const page = (title: string, extra = '') => `---\ntype: note\ntitle: ${title}\n${extra}---\n\nNotes about ${title}.\n`;+const gitRepo = (ignored = '') => ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), `${ignored}\n`); durableGitRepo(root, ['.gitignore']); };+const call = (ctx: OperationContext, name: string, params: Record<string, unknown>) =>+ operationsByName[name]!.handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, any>>;+const remember = (ctx: OperationContext, fact: string, entity: string) => call(ctx, 'remember', { fact, entity, provenance: 'chat 2026-11-12' });+const head = (root: string, file: string) => { try { return git(root, 'show', `HEAD:${file}`); } catch { return ''; } };+const everCommitted = (root: string, path: string) => git(root, 'log', '--all', '--format=%H', '--', path).trim() !== '';+const factRows = (engine: BrainEngine, claim: string) => engine.executeRaw<{ id: number; entity_slug: string | null; source_markdown_slug: string | null; row_num: number | null }>(+ `SELECT id::int AS id, entity_slug, source_markdown_slug, row_num FROM facts WHERE source_id='default' AND fact=$1 AND expired_at IS NULL ORDER BY id`, [claim]);+const rule = (id: string, prefix: string, readers: string[]): FolderRule => ({ id, prefix, readable_by: readers.map(r => (r.includes(':') ? r : `member:${r}`)).sort() });+const caught = <T>(p: Promise<T>) => p.then(() => null, (error: Record<string, any>) => error);++/** A fresh database indexed from a clone of HEAD, with the facts step run: the active rows of each claim. */+async function rebuild(root: string, databaseUrl: string | undefined, claims: string[]) {+ const home = mkdtempSync(join(tmpdir(), 'gst2492-folder-rebuild-'));+ try {+ const clone = join(home, 'content');+ git(home, 'clone', '--quiet', root, clone);+ const fresh = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await fresh.engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [clone]);+ await performSync(fresh.engine, { sourceId: 'default', repoPath: clone, noPull: true, noEmbed: true } as never);+ await runExtractFacts(fresh.engine, { sourceId: 'default' });+ const out: Record<string, Array<{ entity_slug: string | null; source_markdown_slug: string | null }>> = {};+ for (const claim of claims) out[claim] = (await factRows(fresh.engine, claim)).map(({ entity_slug, source_markdown_slug }) => ({ entity_slug, source_markdown_slug }));+ return out;+ } finally { await fresh.close(); }+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/** Members alice-example, bob-example and carol-example (bob and alice in group team-a), each with a remote token. */+async function members(engine: BrainEngine): Promise<(who: string, op: string, params: Record<string, unknown>) => Promise<{ isError: boolean; text: string; body: Record<string, any> }>> {+ const tokens: Record<string, string> = {};+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1) ON CONFLICT DO NOTHING', [id]);+ await engine.executeRaw("INSERT INTO access_groups (id) VALUES ('team-a') ON CONFLICT DO NOTHING");+ for (const m of ['alice-example', 'bob-example']) await engine.executeRaw("INSERT INTO access_group_members (group_id, member_id) VALUES ('team-a', $1) ON CONFLICT DO NOTHING", [m]);+ for (const [name, member] of [['alice', 'alice-example'], ['bob', 'bob-example'], ['carol', 'carol-example'], ['unbound', null]] as const) {+ const minted = await mintLegacyToken(engine, { name: `${name}-${randomUUID().slice(0, 6)}`, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: ['default'] });+ tokens[name] = minted.token;+ if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ }+ __resetPrivateVisibilityCacheForTests();+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ return async (who, op, params) => {+ const auth = await provider.verifyAccessToken(tokens[who]!) as unknown as AuthInfo;+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, 'default');+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'],+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });+ const text = out.content.map(c => c.text).join('\n');+ let body: Record<string, any> = {};+ try { body = JSON.parse(out.content[0]!.text); } catch { /* not JSON */ }+ return { isError: out.isError === true, text, body };+ };+}+type Reader = Awaited<ReturnType<typeof members>>;++/** Whether `who` reads page `slug` (get_page) and finds `claim` by keyword search. */+async function reads(as: Reader, who: string, slug: string, claim: string) {+ const got = await as(who, 'get_page', { slug });+ const found = await as(who, 'search', { query: claim, match: 'keyword', fields: 'full', limit: 20 });+ return { page: !got.isError && got.text.includes(slug), fact: JSON.stringify(found.body).includes(claim) };+}++async function cli(engine: BrainEngine, args: string[]): Promise<Record<string, 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), true); } finally { spy.mockRestore(); }+ return JSON.parse(lines.join('\n'));+}++describe('a folder holding page reads the entity column of its own folder only', () => {+ const row = (entity: string) => ['## Facts', '', '<!--- gbrain:facts:begin -->',+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | entity |',+ '|---|---|---|---|---|---|---|---|---|---|---|', `| 1 | The deal closes in May. | fact | 1.0 | world | medium | 2026-11-12 | | chat | | ${entity} |`, '<!--- gbrain:facts:end -->', ''].join('\n');+ test('an entity of the folder parses; one of another folder is a fence problem', () => {+ expect(parseFactsFenceFor(row(ENTITY), { slug: FOLDER_HOLD })).toMatchObject({ warnings: [], facts: [{ entity: ENTITY }] });+ expect(parseFactsFenceFor(row('people/bob-example'), { slug: FOLDER_HOLD }).warnings.join(' ')).toContain('invalid entity');+ expect(parseFactsFenceFor(row('people/bob-example'), { slug: HOLD })).toMatchObject({ warnings: [], facts: [{ entity: 'people/bob-example' }] });+ });+ test('a holding page under an entity directory is never an entity page itself', () => {+ expect(isIdentityEntity('people/memory/unattributed')).toBe(false);+ expect(isFactEntityPage('deals/memory/unattributed', null)).toBe(false);+ expect(isIdentityEntity('people/alice-example')).toBe(true);+ });+});++for (const backend of testBackends()) describe(`[${backend}] the folder-rule holding page on a strict source (GST-2492)`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ afterEach(() => { policySeams.afterInstall = undefined; });+ const strict = (run: (brain: ManagedBrain) => Promise<void>, ignored = '') => managedBrain(async brain => {+ await brain.engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);+ await run(brain);+ }, { databaseUrl, setup: gitRepo(ignored) });+ const rules = (engine: BrainEngine, list: FolderRule[], approved = false) => proposeRevision(engine, 'default', list, { origin: 'cli', store: 'database', approved });++ test('a ruled entity is held on its folder\'s page in Git before the reply; a rebuild keeps it; the move takes it into the page', () => strict(async ({ engine, ctx, root }) => {+ await rules(engine, [rule('partners', 'partners/', ['alice-example'])]);+ const claim = 'The deal with acme-example closes in May.';+ const saved = await remember(ctx, claim, ENTITY);+ expect(saved).toMatchObject({ status: 'inserted', page: FOLDER_HOLD, persistence: { mode: 'filesystem' }, write_through: { written: true, held_for: ENTITY } });+ expect(head(root, `${FOLDER_HOLD}.md`).split('\n').find(line => line.includes(claim))).toContain(ENTITY);+ expect(head(root, `${HOLD}.md`)).not.toContain(claim);+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: ENTITY, source_markdown_slug: FOLDER_HOLD }]);+ expect((await rebuild(root, databaseUrl, [claim]))[claim]).toEqual([{ entity_slug: ENTITY, source_markdown_slug: FOLDER_HOLD }]);+ await call(ctx, 'put_page', { slug: ENTITY, content: page('Deal notes') });+ await settleManagedGitEffects(engine);+ expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved).toBe(1);+ await settleManagedGitEffects(engine);+ expect(head(root, `${ENTITY}.md`)).toContain(claim);+ expect(head(root, `${FOLDER_HOLD}.md`)).not.toContain(claim);+ expect(await factRows(engine, claim)).toMatchObject([{ id: Number(saved.id), entity_slug: ENTITY, source_markdown_slug: ENTITY }]);+ expect((await rebuild(root, databaseUrl, [claim]))[claim]).toEqual([{ entity_slug: ENTITY, source_markdown_slug: ENTITY }]);+ }), 300_000);++ test('the holding page has exactly the entity\'s would-be readers under three nested rules, and reads as nobody while a rule is pending', () => strict(async ({ engine, ctx }) => {+ const as = await members(engine);+ const nested = [rule('partners', 'partners/', ['group:team-a', 'carol-example']), rule('alice', 'partners/alice-example/', ['alice-example', 'bob-example']),+ rule('deals', 'partners/alice-example/deals/', ['alice-example'])];+ await rules(engine, nested);+ const entity = 'partners/alice-example/deals/q3-plan';+ const holding = 'partners/alice-example/deals/memory/unattributed';+ const claim = 'The q3 plan doubles the budget.';+ expect(await remember(ctx, claim, entity)).toMatchObject({ page: holding, write_through: { held_for: entity } });+ await call(ctx, 'put_page', { slug: 'partners/alice-example/deals/probe', content: page('Probe') });+ const groups: Record<string, string[]> = { 'alice-example': ['team-a'], 'bob-example': ['team-a'], 'carol-example': [] };+ for (const [who, member] of [['alice', 'alice-example'], ['bob', 'bob-example'], ['carol', 'carol-example']] as const) {+ const wouldRead = folderRulesAllow(entity, nested, identityFor(member, groups[member]!));+ const probe = await as(who, 'get_page', { slug: 'partners/alice-example/deals/probe' });+ expect(!probe.isError).toBe(wouldRead);+ expect(await reads(as, who, holding, claim)).toEqual({ page: wouldRead, fact: wouldRead });+ }+ // alice satisfies all three, bob two of three, carol only the outermost.+ expect([true, false, false]).toEqual(['alice-example', 'bob-example', 'carol-example'].map(m => folderRulesAllow(entity, nested, identityFor(m, groups[m]!))));++ policySeams.afterInstall = () => { throw new Error('interrupted'); };+ await expect(rules(engine, [...nested, rule('acme', 'clients/acme-example/', ['alice-example'])])).rejects.toThrow('interrupted');+ policySeams.afterInstall = undefined;+ const pending = 'The acme-example brief is due Friday.';+ expect(await remember(ctx, pending, 'clients/acme-example/brief')).toMatchObject({ page: 'clients/acme-example/memory/unattributed' });+ await call(ctx, 'put_page', { slug: 'clients/acme-example/probe', content: page('Probe') });+ for (const who of ['alice', 'bob', 'carol']) {+ expect((await as(who, 'get_page', { slug: 'clients/acme-example/probe' })).isError).toBe(true);+ expect(await reads(as, who, 'clients/acme-example/memory/unattributed', pending)).toEqual({ page: false, fact: false });+ }+ await resumePolicy(engine, 'default');+ for (const who of ['alice', 'bob', 'carol']) {+ const wouldRead = who === 'alice';+ expect(!(await as(who, 'get_page', { slug: 'clients/acme-example/probe' })).isError).toBe(wouldRead);+ expect(await reads(as, who, 'clients/acme-example/memory/unattributed', pending)).toEqual({ page: wouldRead, fact: wouldRead });+ }+ }), 300_000);++ test('a caller who cannot read the folder gets the answer of a page that does not exist, on every read path', () => strict(async ({ engine, ctx }) => {+ const as = await members(engine);+ await rules(engine, [rule('partners', 'partners/', ['alice-example'])]);+ const claim = 'The acme-example deal has a break fee.';+ expect(await remember(ctx, claim, ENTITY)).toMatchObject({ page: FOLDER_HOLD });+ const missing = 'partners/alice-example/nothing-here';+ for (const who of ['bob', 'unbound']) {+ const held = await as(who, 'get_page', { slug: FOLDER_HOLD });+ const none = await as(who, 'get_page', { slug: missing });+ expect(held.isError).toBe(true);+ expect(held.text.replaceAll(FOLDER_HOLD, '<slug>')).toBe(none.text.replaceAll(missing, '<slug>'));+ for (const [op, params] of [['search', { query: claim, match: 'keyword', fields: 'full' }], ['query', { query: claim }], ['recall', { query: 'acme-example deal break fee' }],+ ['list_pages', { slug_prefix: 'partners/' }], ['find_pages', { pattern: 'partners/**' }], ['find_pages', { pattern: 'unattributed' }]] as const) {+ const out = await as(who, op, params as Record<string, unknown>);+ expect(out.text).not.toContain(claim);+ expect(out.text).not.toContain(FOLDER_HOLD);+ }+ }+ const alice = await as('alice', 'find_pages', { pattern: 'partners/**' });+ expect(alice.text).toContain(FOLDER_HOLD);+ expect((await reads(as, 'alice', FOLDER_HOLD, claim)).fact).toBe(true);+ }), 300_000);++ test('a raw-only rule (covers_derived false) still hides the held facts on its folder\'s page, as the entity\'s own page would', () => strict(async ({ engine, ctx }) => {+ const as = await members(engine);+ await rules(engine, [{ ...rule('partners', 'partners/', ['alice-example']), covers_derived: false }]);+ const claim = 'The acme-example deal has a side letter.';+ expect(await remember(ctx, claim, ENTITY)).toMatchObject({ page: FOLDER_HOLD });+ for (const who of ['bob', 'unbound']) {+ expect(await reads(as, who, FOLDER_HOLD, claim)).toEqual({ page: false, fact: false });+ for (const [op, params] of [['query', { query: claim }], ['recall', { query: 'acme-example deal side letter' }]] as const) {+ expect((await as(who, op, params as Record<string, unknown>)).text).not.toContain(claim);+ }+ }+ expect(await reads(as, 'alice', FOLDER_HOLD, claim)).toEqual({ page: true, fact: true });+ }), 300_000);++ test('a rule applied without the CLI edit keeps a shared held fact row from non-readers until the move; resume moves it', () => strict(async ({ engine, ctx }) => {+ const as = await members(engine);+ const entity = 'clients/acme-example/brief';+ const claim = 'The acme-example brief has a hidden clause.';+ expect(await remember(ctx, claim, entity)).toMatchObject({ page: HOLD });+ policySeams.afterInstall = () => { throw new Error('interrupted'); };+ await expect(rules(engine, [rule('clients', 'clients/acme-example/', ['alice-example'])])).rejects.toThrow('interrupted');+ policySeams.afterInstall = undefined;+ __resetPrivateVisibilityCacheForTests();+ const recalls = async (who: string, text: string, query: string) => JSON.stringify((await as(who, 'recall', { query, question: query })).body.facts ?? []).includes(text);+ // The shared page's body keeps the row until the move; its fact row reads as the entity's page would (pending: nobody).+ for (const who of ['alice', 'bob', 'unbound']) expect([who, await recalls(who, claim, 'acme-example brief clause')]).toEqual([who, false]);+ const resumed = await cli(engine, ['resume', '--source', 'default', '--json']);+ expect(resumed.held_facts).toEqual({ moved: 1, unmovable: [] });+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: entity, source_markdown_slug: 'clients/acme-example/memory/unattributed' }]);+ __resetPrivateVisibilityCacheForTests();+ const late = 'The acme-example brief names a second clause.';+ await call(ctx, 'put_page', { slug: 'notes/acme-example-late', content: page('Late') });+ expect(await remember(ctx, late, 'clients/acme-example/terms')).toMatchObject({ page: 'clients/acme-example/memory/unattributed' });+ const other = 'The beta-example plan has a hidden clause.';+ expect(await remember(ctx, other, 'clients/beta-example/plan')).toMatchObject({ page: HOLD });+ await rules(engine, [rule('clients', 'clients/acme-example/', ['alice-example']), rule('beta', 'clients/beta-example/', ['alice-example'])]);+ __resetPrivateVisibilityCacheForTests();+ expect(await recalls('bob', other, 'beta-example plan clause')).toBe(false);+ expect(await recalls('unbound', other, 'beta-example plan clause')).toBe(false);+ expect(await recalls('alice', other, 'beta-example plan clause')).toBe(true);+ expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved).toBe(1);+ expect(await reads(as, 'bob', 'clients/beta-example/memory/unattributed', other)).toEqual({ page: false, fact: false });+ expect((await as('bob', 'get_page', { slug: HOLD })).text).not.toContain('beta-example');+ }), 300_000);++ test('a folder rule\'s own apply moves the held facts it covers off the shared page, and its preview counts them', () => strict(async ({ engine, ctx, root }) => {+ const as = await members(engine);+ const entity = 'clients/acme-example/brief';+ const holding = 'clients/acme-example/memory/unattributed';+ const claim = 'The acme-example brief names a new budget.';+ const kept = 'The garden plan adds two raised beds.';+ expect(await remember(ctx, claim, entity)).toMatchObject({ page: HOLD });+ await remember(ctx, kept, 'notes/garden-plan');+ await settleManagedGitEffects(engine);+ expect(head(root, `${HOLD}.md`)).toContain(claim);+ expect((await reads(as, 'bob', HOLD, claim)).fact).toBe(true);+ const preview = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--source', 'default', '--json']);+ expect(preview.held_facts_moving).toEqual([{ fact_id: expect.any(Number), entity_slug: entity, to: holding }]);+ expect(head(root, `${HOLD}.md`)).toContain(claim);+ const applied = await cli(engine, ['rule', 'add', '--prefix', 'clients/acme-example/', '--readers', 'alice-example', '--source', 'default', '--yes', '--expect', String(preview.expect), '--json']);+ expect(applied).toMatchObject({ state: 'applied', held_facts: { moved: 1, unmovable: [] } });+ await settleManagedGitEffects(engine);+ const shared = head(root, `${HOLD}.md`);+ expect(shared).not.toContain(claim);+ expect(shared).not.toContain('clients/acme-example');+ expect(shared).toContain(kept);+ expect(head(root, `${holding}.md`)).toContain(claim);+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: entity, source_markdown_slug: holding }]);+ for (const who of ['bob', 'unbound']) {+ expect(await reads(as, who, holding, claim)).toEqual({ page: false, fact: false });+ const sharedPage = await as(who, 'get_page', { slug: HOLD });+ expect(sharedPage.text).not.toContain(claim);+ expect(sharedPage.text).not.toContain('clients/acme-example');+ }+ expect(await reads(as, 'alice', holding, claim)).toEqual({ page: true, fact: true });+ expect((await rebuild(root, databaseUrl, [claim, kept]))).toEqual({ [claim]: [{ entity_slug: entity, source_markdown_slug: holding }],+ [kept]: [{ entity_slug: 'notes/garden-plan', source_markdown_slug: HOLD }] });+ }), 300_000);++ test('the owner reads every holding page before and after a re-home: with the opt-in on, and off where the rules name the owner', () => strict(async ({ engine, ctx }) => {+ const as = await members(engine);+ await setOwner(engine, 'carol-example');+ __resetPrivateVisibilityCacheForTests();+ const pages: Array<[string, string, string]> = [['partners/alice-example/deal-notes', FOLDER_HOLD, 'The deal notes mention a pilot.'],+ ['clients/acme-example/brief', 'clients/acme-example/memory/unattributed', 'The brief asks for a pilot.']];+ await rules(engine, [rule('partners', 'partners/', ['alice-example'])]);+ for (const [entity, , claim] of pages) await remember(ctx, claim, entity);+ const ownerReads = async () => Promise.all(pages.map(async ([, holding, claim]) => reads(as, 'carol', holding, claim)));+ const optIn = async (on: boolean) => { await setOwnerReadsRestricted(engine, on, { remote: false }); __resetPrivateVisibilityCacheForTests(); };+ // Before the re-home: the partners fact is on its folder's page, the clients fact on the shared one.+ await optIn(true);+ expect(await ownerReads()).toEqual([{ page: true, fact: true }, { page: false, fact: true }]);+ expect((await as('carol', 'get_page', { slug: HOLD })).text).toContain(pages[1]![2]);+ await optIn(false);+ expect((await ownerReads())[0]).toEqual({ page: false, fact: false });+ await rules(engine, [rule('partners', 'partners/', ['alice-example']), rule('clients', 'clients/', ['alice-example'])]);+ expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved).toBe(1);+ // After: both on their folders' pages. The opt-in on reads both; off, the owner reads them once the rules name it.+ await optIn(true);+ expect(await ownerReads()).toEqual([{ page: true, fact: true }, { page: true, fact: true }]);+ await optIn(false);+ expect(await ownerReads()).toEqual([{ page: false, fact: false }, { page: false, fact: false }]);+ await rules(engine, [rule('partners', 'partners/', ['alice-example', 'carol-example']), rule('clients', 'clients/', ['alice-example', 'carol-example'])], true);+ __resetPrivateVisibilityCacheForTests();+ expect(await ownerReads()).toEqual([{ page: true, fact: true }, { page: true, fact: true }]);+ // The local CLI (the host's owner) reads every holding page whatever the rules say.+ for (const [, holding, claim] of pages) expect(JSON.stringify(await call(ctx, 'get_page', { slug: holding }))).toContain(claim);+ }), 300_000);++ test('an exact page rule refuses git_home_required (facts_lane) and an unreadable access state answers wait, locally and over MCP', () => strict(async ({ engine, ctx, root }) => {+ const as = await members(engine);+ await rules(engine, [rule('secret-plan', 'notes/secret-plan', ['alice-example'])]);+ const claim = 'The secret plan has a codename.';+ const local = await caught(remember(ctx, claim, 'notes/secret-plan'));+ expect({ code: local!.code, canonical: local!.canonical, reason: local!.reason }).toEqual({ code: 'invalid_params', canonical: 'git_home_required', reason: 'facts_lane' });+ expect(local!.fix).toMatchObject({ mcp: { tool: 'put_page', arguments: { slug: 'notes/secret-plan' } }, ask_user: true });+ const remote = await as('alice', 'remember', { fact: claim, entity: 'notes/secret-plan', provenance: 'chat 2026-11-12', share: true, request_id: randomUUID() });+ expect(remote.isError).toBe(true);+ expect(remote.body).toMatchObject({ error: 'invalid_params', code: 'git_home_required', reason: 'facts_lane', fix: { mcp: { tool: 'put_page' }, next: 'ask_user' } });+ expect(remote.text).not.toContain('storage_error');+ expect(await factRows(engine, claim)).toEqual([]);+ expect(head(root, `${HOLD}.md`)).not.toContain(claim);++ await engine.executeRaw('CREATE OR REPLACE FUNCTION gbrain_access_state_unreadable() RETURNS boolean LANGUAGE sql STABLE AS $fn$ SELECT true $fn$');+ const unreadable = 'The kitchen remodel starts in March.';+ const waited = await caught(remember(ctx, unreadable, 'notes/kitchen-remodel'));+ expect({ code: waited!.code, canonical: waited!.canonical }).toEqual({ code: 'unavailable', canonical: 'access_policy_pending' });+ expect(waited!.fix).toMatchObject({ actor: 'provider' });+ const overMcp = await dispatchToolCall(engine, 'remember', { fact: unreadable, entity: 'notes/kitchen-remodel', provenance: 'chat 2026-11-12', request_id: randomUUID() },+ { remote: true, transport: 'stdio', sourceId: 'default' });+ const body = JSON.parse(overMcp.content[0]!.text);+ expect(overMcp.isError).toBe(true);+ expect(body).toMatchObject({ error: 'unavailable', code: 'access_policy_pending' });+ expect(JSON.stringify(body)).toContain('"next":"wait"');+ expect(await factRows(engine, unreadable)).toEqual([]);+ }), 300_000);++ test('a folder under storage.db_only or a path Git ignores gets a database-only holding page that is never committed', () => strict(async ({ engine, ctx, root }) => {+ writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - partners/\n');+ git(root, 'add', 'gbrain.yml'); git(root, 'commit', '-q', '-m', 'storage');+ await rules(engine, [rule('partners', 'partners/', ['alice-example']), rule('clients', 'clients/', ['alice-example'])]);+ for (const [entity, holding, claim] of [[ENTITY, FOLDER_HOLD, 'The deal notes are kept out of Git.'],+ ['clients/acme-example/brief', 'clients/acme-example/memory/unattributed', 'The brief is kept out of Git.']] as const) {+ const notices: Array<{ code: string; why?: string }> = [];+ const saved = await remember({ ...ctx, emitNotice: (n: { code: string; why?: string } | null | undefined) => { if (n) notices.push(n); } } as OperationContext, claim, entity);+ expect(saved).toMatchObject({ status: 'inserted', page: holding, persistence: { mode: 'database' }, write_through: { written: false, skipped: 'db_only', held_for: entity } });+ expect(notices.find(n => n.code === 'entity_page_missing')!.why).toContain('database only');+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: entity, source_markdown_slug: holding, row_num: 1 }]);+ const second = await remember(ctx, `${claim} Again.`, entity);+ expect(second).toMatchObject({ page: holding });+ }+ await settleManagedGitEffects(engine);+ expect(everCommitted(root, 'partners')).toBe(false);+ expect(everCommitted(root, 'clients')).toBe(false);+ const scan = await scanFactsHome(engine, 'default');+ expect(scan.homeable).toEqual([]);+ expect(scan.rows).toEqual([]);+ }, 'clients/'), 300_000);++ test('the background fact writers hold a ruled entity\'s fact on its folder\'s page; gbrain repair facts-home moves older ones there', () => strict(async ({ engine, ctx, root }) => {+ await rules(engine, [rule('partners', 'partners/', ['alice-example']), rule('secret-plan', 'notes/secret-plan', ['alice-example'])]);+ const background = 'The deal notes were extracted from mail.';+ await writeSingleFact(engine, 'default', { fact: background, entity: ENTITY, provenance: 'mail 2026-11-12', remote: false } as never);+ await settleManagedGitEffects(engine);+ expect(await factRows(engine, background)).toMatchObject([{ entity_slug: ENTITY, source_markdown_slug: FOLDER_HOLD }]);+ expect(head(root, `${FOLDER_HOLD}.md`)).toContain(background);+ // Older database-only facts: one for the ruled entity, one for an entity an exact page rule names.+ const older = 'The deal notes predate the rule.';+ const pageRuled = 'The secret plan predates the rule.';+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try {+ for (const [claim, entity] of [[older, 'partners/alice-example/old-notes'], [pageRuled, 'notes/secret-plan']]) {+ await engine.insertFact({ fact: claim, kind: 'fact', entity_slug: entity, visibility: 'world', source: 'legacy import' } as never, { source_id: 'default' });+ }+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+ const logger = { info() {}, warn() {}, error() {} };+ const run = async (opts: { apply?: boolean; expect?: string } = {}) => (await repairRunner(engine, { apply: opts.apply === true, logger }))+ .run('facts-home' as RepairKind, await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default', expect: opts.expect }) as Promise<Record<string, any>>;+ const preview = await run();+ expect(preview.listing.map((entry: { class: string; detail: string }) => [entry.class, entry.detail.includes(FOLDER_HOLD) || entry.detail.includes('page rule')]))+ .toEqual(expect.arrayContaining([['entity_page_missing', true], ['folder_restricted', true]]));+ expect((await run({ apply: true, expect: preview.preview_hash })).applied).toBe(1);+ await settleManagedGitEffects(engine);+ expect(await factRows(engine, older)).toMatchObject([{ entity_slug: 'partners/alice-example/old-notes', source_markdown_slug: FOLDER_HOLD }]);+ expect(head(root, `${FOLDER_HOLD}.md`)).toContain(older);+ expect(await factRows(engine, pageRuled)).toMatchObject([{ row_num: null }]);+ const after = await scanFactsHome(engine, 'default');+ expect(after.rows.map(r => [r.group, r.reason])).toEqual([['folder_restricted', 'page_rule']]);+ expect((await rebuild(root, databaseUrl, [older, background]))).toEqual({ [older]: [{ entity_slug: 'partners/alice-example/old-notes', source_markdown_slug: FOLDER_HOLD }],+ [background]: [{ entity_slug: ENTITY, source_markdown_slug: FOLDER_HOLD }] });+ }), 300_000);++ test('a source that is not strict, and a brain with no Git repository, keep a ruled entity\'s fact database-only as before', async () => {+ await managedBrain(async ({ engine, ctx, root }) => {+ await rules(engine, [rule('partners', 'partners/', ['alice-example'])]);+ const claim = 'The deal notes stay in the database here.';+ const saved = await remember(ctx, claim, ENTITY);+ expect(saved.persistence).toEqual({ mode: 'database' });+ expect(saved.write_through).not.toHaveProperty('held_for');+ expect(existsSync(join(root, `${FOLDER_HOLD}.md`))).toBe(false);+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: ENTITY, source_markdown_slug: null, row_num: null }]);+ }, { databaseUrl, setup: gitRepo() });+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await rules(engine, [rule('partners', 'partners/', ['alice-example'])]);+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default', remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as OperationContext;+ const claim = 'The deal notes live in a brain with no repository.';+ const saved = await remember(ctx, claim, ENTITY);+ expect(saved).toMatchObject({ status: 'inserted' });+ expect(saved).not.toHaveProperty('page');+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: ENTITY, source_markdown_slug: null, row_num: null }]);+ } finally { await close(); }+ }, 300_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 92191556a3..22cb9a8725 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -123,6 +123,7 @@ test/fence-first-generation-8819.test.tstest/fence-repair-receipts.test.tstest/fenced-embed-reuse-6961.test.tstest/file-drift-soft-delete-hold-release-gbra133.test.ts+test/folder-holding-page-gst2492.test.tstest/forecast-journal.test.tstest/frontmatter-reserved-keys-6454.test.tstest/g4-forget-fence-edit.test.tsdiff --git a/test/remember-strict-held-gst2492.test.ts b/test/remember-strict-held-gst2492.test.tsindex b493a0f96b..50ea81d2c5 100644--- a/test/remember-strict-held-gst2492.test.ts+++ b/test/remember-strict-held-gst2492.test.ts@@ -232,14 +232,14 @@ for (const backend of testBackends()) describe(`[${backend}] a strict source holexpect(rebuilt[claim]).toEqual([{ entity_slug: secret, source_markdown_slug: secret, active: true }]);}), 240_000);- test('an entity under a folder access rule is not held on the world-readable page', () => strict(async ({ engine, ctx, root }) => {+ test('an entity under a folder access rule is not held on the world-readable page but on its folder\'s', () => strict(async ({ engine, ctx, root }) => {await engine.executeRaw(`INSERT INTO access_policy_state(source_id) VALUES('default') ON CONFLICT DO NOTHING`);await engine.executeRaw(`INSERT INTO access_rules(source_id,rule_id,prefix,readable_by,revision) VALUES('default','r1','secret/',ARRAY['member:alice-example'],1)`);const claim = 'The secret plan has a codename.';const saved = await remember(ctx, claim, 'secret/plan-x');- expect(saved.write_through).not.toHaveProperty('held_for');- expect(saved.persistence).toEqual({ mode: 'database' });+ expect(saved).toMatchObject({ page: 'secret/memory/unattributed', write_through: { written: true, held_for: 'secret/plan-x' } });expect(head(root, HOLD_FILE)).not.toContain(claim);+ expect(lineOf(head(root, 'secret/memory/unattributed.md'), claim)).toContain('secret/plan-x');}), 180_000);test('a segmented holding page reads its entity column: forget strikes the row and a rebuild keeps the rest', () => strict(async ({ engine, ctx, root }) => {diff --git a/test/repair-facts-home-gst2492.test.ts b/test/repair-facts-home-gst2492.test.tsindex 0514d2a384..01bc03f703 100644--- a/test/repair-facts-home-gst2492.test.ts+++ b/test/repair-facts-home-gst2492.test.ts@@ -110,7 +110,7 @@ for (const backend of testBackends()) describe(`[${backend}] gbrain repair factsawait seeded(b);const before = { head: git(root, 'rev-parse', 'HEAD'), pageless: await factRow(engine, PAGELESS), subjectless: await factRow(engine, SUBJECTLESS) };const preview = await repair(engine);- expect(classes(preview)).toEqual(['cannot_render', 'entity_page_exists', 'entity_page_missing', 'folder_restricted', 'held_over_30_days', 'no_entity']);+ expect(classes(preview)).toEqual(['cannot_render', 'entity_page_exists', 'entity_page_missing', 'entity_page_missing', 'held_over_30_days', 'no_entity']);const old = preview.listing.find((entry: { class: string }) => entry.class === 'held_over_30_days');expect(old.detail).toContain('people/dana-example');expect(git(root, 'rev-parse', 'HEAD')).toBe(before.head);@@ -125,8 +125,10 @@ for (const backend of testBackends()) describe(`[${backend}] gbrain repair factsexpect(lineOf(file, PAGELESS)).toContain('notes/kitchen-remodel');expect(lineOf(file, SUBJECTLESS)).toContain(SUBJECTLESS);for (const text of [PAGED, UNRENDERABLE, RESTRICTED, 'secret/project-x']) expect(file).not.toContain(text);- expect(await factRow(engine, RESTRICTED)).toMatchObject({ row_num: null });- expect(classes(await repair(engine))).toEqual(['cannot_render', 'entity_page_exists', 'folder_restricted', 'held_over_30_days']);+ // An entity under a folder access rule is held on its folder's holding page, never on the shared one.+ expect(await factRow(engine, RESTRICTED)).toMatchObject({ entity_slug: 'secret/project-x', source_markdown_slug: 'secret/memory/unattributed' });+ expect(lineOf(head(root, 'secret/memory/unattributed.md'), RESTRICTED)).toContain('secret/project-x');+ expect(classes(await repair(engine))).toEqual(['cannot_render', 'entity_page_exists', 'held_over_30_days']);expect(await rebuild(root, databaseUrl, [PAGELESS, SUBJECTLESS])).toEqual({ [PAGELESS]: 'notes/kitchen-remodel', [SUBJECTLESS]: null });}), 240_000);diff --git a/test/strict-background-writers-gst2492.test.ts b/test/strict-background-writers-gst2492.test.tsindex 398748fb78..3f2a70fb6e 100644--- a/test/strict-background-writers-gst2492.test.ts+++ b/test/strict-background-writers-gst2492.test.ts@@ -149,20 +149,21 @@ for (const backend of testBackends()) describe(`[${backend}] background fact wriexpect(await outsideGit(engine)).toBe(0);}));- test('an entity under a folder access rule is never named on the holding page: its fact stays database-only, or is refused as before', () => brain(true, async ({ engine, ctx, root }) => {+ test('an entity under a folder access rule is never named on the shared holding page: its fact is held on its folder\'s', () => brain(true, async ({ engine, ctx, root }) => {await engine.executeRaw(`INSERT INTO access_policy_state(source_id) VALUES('default') ON CONFLICT DO NOTHING`);await engine.executeRaw(`INSERT INTO access_rules(source_id,rule_id,prefix,readable_by,revision) VALUES('default','r1','secret/',ARRAY['member:alice-example'],1)`);__resetPrivateVisibilityCacheForTests();const before = 'The acquisition target is acme-example.';await writeSingleFact(engine, 'default', { fact: before, entity: 'secret/project-x', provenance: 'probe', remote: false } as never);- expect(await factRows(engine, before)).toMatchObject([{ entity_slug: 'secret/project-x', row_num: null, active: true }]);+ expect(await factRows(engine, before)).toMatchObject([{ entity_slug: 'secret/project-x', source_markdown_slug: 'secret/memory/unattributed', row_num: 1, active: true }]);await seedHoldingPage(ctx);await settleManagedGitEffects(engine);const after = 'The acquisition closes in the third quarter.';- const refused = await writeSingleFact(engine, 'default', { fact: after, entity: 'secret/project-x', provenance: 'probe', remote: false } as never).then(() => null, (error: { code?: string }) => error.code);- expect(refused).toBe('git_home_required');- expect(await factRows(engine, after)).toEqual([]);+ await writeSingleFact(engine, 'default', { fact: after, entity: 'secret/project-x', provenance: 'probe', remote: false } as never);+ expect(await factRows(engine, after)).toMatchObject([{ entity_slug: 'secret/project-x', source_markdown_slug: 'secret/memory/unattributed', active: true }]);+ await settleManagedGitEffects(engine);for (const text of [before, after, 'secret/project-x']) expect(head(root, HOLD_FILE)).not.toContain(text);+ for (const text of [before, after]) expect(head(root, 'secret/memory/unattributed.md')).toContain(text);}));test('a source that is not strict keeps these facts database-only, as before', () => brain(false, async ({ engine, ctx, root }) => {