Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Strict sources keep a fact for a pageless entity in Git (GST-2492)

garrytan980fa2ed56e6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e7c4557e6..9c0f497bd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,15 @@ identifiers and attribution are available in the pre-removal Git revision
- Docs: `docs/guides/entity-scoped-facts.md`, the `remember` section of `docs/mcp/TOOL_REFERENCE.md` and `docs/protocol/MEMORY_VERBS_v1.md` describe the reply. One behavior-change row discloses the reply change after an upgrade.
- Tests: `test/remember-pageless-entity-gst2446.test.ts` runs on PGLite and Postgres against a Git checkout, a content folder with no Git and a source with no checkout, single and batch, through the operation handler and through MCP dispatch. It also pins that the fact reaches the page's Facts table and its committed file once the page is created.
+**On a source whose pages are canonical in Git, a fact saved for an entity with no page is now committed to Git.** Until now such a fact lived only in the database, so rebuilding the brain from its Git repository lost it. `remember` now writes it into `memory/unattributed` as a row whose new `entity` column names the entity, committed before the database row, and moves it into the entity's page once that page exists. Other sources and brains with no Git repository behave as before.
+
+- The reply, each batch item and the write receipt say where the fact is: `page: "memory/unattributed"`, `persistence: {mode: "filesystem"}`, `write_through: {written: true, held_for: "<entity>"}`, and the `entity_page_missing` notice says the fact is saved and committed and when it moves.
+- The `extract_facts` maintenance phase moves held facts into a new entity page in one commit: the fact keeps its id, provenance and embedding, and the held row is struck (`moved to <entity>`, or `moved` with no entity named when the page is restricted). A page kept out of Git does not take the fact; the run warns `HELD_FACT_UNMOVABLE` and the fact stays held.
+- `forget` strikes a held fact's own row; `remember … replaces` supersedes a held fact from `memory/unattributed` or from the entity's page.
+- A client bound to slug prefixes may save a held fact for an entity inside its prefixes; a fact with no entity is still refused for it.
+- Only `memory/unattributed` reads the `entity` column, and an invalid entity cell makes its fence malformed. Every other page parses exactly as before. An older gbrain holds a `memory/unattributed` file that carries the column as a malformed fence, so upgrade every host of a strict source together.
+- Tests: `test/remember-strict-held-gbra449.test.ts` on PGLite and Postgres: the commit before the reply (handler, batch, MCP), rebuilds from a clone of HEAD, the move (one commit, interrupted after its commit and replayed), restricted and database-only pages, forget, both supersede paths, a prefix-bound client, duplicates and the fence column.
+
## [0.60.678.0] - 2026-11-11
**Pushes from an unmanaged checkout now scan every commit they publish for secrets, not only the files they just wrote.** Four gbrain pushes from a checkout that is not a managed worktree carried earlier local commits to the remote unscanned: the access-policy commit, the durability-scaffolding commit, `gbrain sources push` (which scanned only its own staged files, then pushed the whole branch tip, even with nothing new to commit) and the first push of `gbrain bootstrap repo` after the remote branch was gone (which scanned only the current tree). A credential a script committed with plain `git commit`, including one a later commit removed or one in a commit message, went out with them. Each now runs the range scan managed publishes use over what the remote lacks (the whole history when the remote has no such branch) and refuses `publish_secret_found` or `publish_scan_unreadable`, with nothing pushed and the local commits kept. `gbrain sources push` pushes the exact commit it scanned, leased on the remote tip it read, so a remote rewound in between is scanned again. An allowlist edit that `gbrain sources push` or `gbrain bootstrap repo` commits itself, after scanning it, still publishes; one a script committed is left to the user. Remoteless checkouts, managed worktrees and repo-less brains are unchanged, and the policy command's retry hint keeps `--scan-secrets`.
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 3d6fdeac6f..d2b6c2966e 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -21,4 +21,6 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/commands/doctor/checks/fact-bulk-dates.ts` — `fact_bulk_dates` (wave check, #7247): `findBulkFactDays` over the scoped sources (remote callers: their permitted sources); warns per day with fact and entity counts, top source tags and `dated_claims`, says the dates record loading, not occurrence, and names the `gbrain repair fact-claim-dates --source <id>` preview. Read-only.
- `src/core/repair/fact-claim-dates.ts` — `gbrain repair fact-claim-dates --source <id> [--day YYYY-MM-DD]` (#7247), explicit-only, preview-bound, destructive (`--yes`). Candidates: active facts on a bulk day (`findBulkFactDays`, or `--day`) whose claim has exactly one earlier ISO date (`claimDate`). A fence row's `valid_from` cell is rewritten in the page's one fence section and published by revision-bound `put_page` (the facts row is re-projected); a database-only fact is updated in one `maintenanceTransaction` on an unmanaged brain and counted `database_only_managed` on a managed one. Pages with an unparsed, split or segmented fence, or a rewrite that does not read back as the planned rows, are listed and kept. The hash binds revisions, row numbers and new dates; a fresh apply recomputes the plan and refuses `preview_changed` on any difference. Test: `test/repair-fact-claim-dates-7247.test.ts`.
-- `src/core/facts/fence-fact-append.ts` — `prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier, mode?, supersede? | rowNum }, signal)`: the one way a coordinator preparer puts a single fact into the facts fence of the request's page (`row.slug`); remember uses it, and so does a managed owner release of a held fact (`trust/release-publish.ts`, the `trust_release` operation: append for a held fact with an entity slug, index-existing for a hold naming `payload.row_num`, whose cell fields the owner previewed and the request binds: a moved cell refuses `preview_changed`). It returns `{ prepared, rowNum, fencesNormalized, apply(tx) }`: `prepared` is the page write to compose (its `file`, `exclusiveSources`, `validate`; null in index-existing), and `apply` runs in the publication transaction after the coordinator published the file, writing the page row (tier kept, `trust/fence-append.ts`) and then the facts row with `row_num` and `source_markdown_slug`, so a facts row never precedes its fence row in Git. `append` (default) normalizes the stored fence (#6188), renders the row with `fenceRowOf` (`unfenced-facts.ts`, the one renderer) at one past the highest row number in the fence and among the page's facts rows (#6696 C9), strikes `supersede.rowNum` when given, and prepares the page write `unprojected` (`preparePageMutation` option: the helper writes the facts row, so the page publishes without canonical projection whatever the operation) under `withPendingFenceRows` at `pendingTier`. `index-existing` takes a row the file already holds (a fence-guard hold's `payload.row_num`): the cell must pass `fenceCellReadBackProblem` against the fact, else it refuses `fence_row_changed` (reason `row_missing` / `struck` / `empty` / `visibility` / `text`) and writes nothing; otherwise the facts row derives from the cell (`extractFactsFromFenceText`, what a re-import projects) with the caller's embedding and session, and no file changes; the caller's observedRevision is `snapshot.revision`, which the coordinator re-checks under the page lock. An occupied row number fails the insert with `storage_error` naming the occupant. Tests: `test/fence-fact-append.test.ts` (PGLite and Postgres: append, supersede, index-existing from a real fence-guard hold, each refusal, and remember's fence row byte for byte against the earlier construction).
+- `src/core/facts/fence-fact-append.ts` — `prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier, mode?, supersede? | rowNum }, signal)`: the one way a coordinator preparer puts a single fact into the facts fence of the request's page (`row.slug`); remember uses it, and so does a managed owner release of a held fact (`trust/release-publish.ts`, the `trust_release` operation: append for a held fact with an entity slug, index-existing for a hold naming `payload.row_num`, whose cell fields the owner previewed and the request binds: a moved cell refuses `preview_changed`). It returns `{ prepared, rowNum, fencesNormalized, apply(tx) }`: `prepared` is the page write to compose (its `file`, `exclusiveSources`, `validate`; null in index-existing), and `apply` runs in the publication transaction after the coordinator published the file, writing the page row (tier kept, `trust/fence-append.ts`) and then the facts row with `row_num` and `source_markdown_slug`, so a facts row never precedes its fence row in Git. `append` (default) normalizes the stored fence (#6188), renders the row with `fenceRowOf` (`unfenced-facts.ts`, the one renderer) at one past the highest row number in the fence and among the page's facts rows (#6696 C9), strikes `supersede.rowNum` when given, and prepares the page write `unprojected` (`preparePageMutation` option: the helper writes the facts row, so the page publishes without canonical projection whatever the operation) under `withPendingFenceRows` at `pendingTier`. `index-existing` takes a row the file already holds (a fence-guard hold's `payload.row_num`): the cell must pass `fenceCellReadBackProblem` against the fact, else it refuses `fence_row_changed` (reason `row_missing` / `struck` / `empty` / `visibility` / `text`) and writes nothing; otherwise the facts row derives from the cell (`extractFactsFromFenceText`, what a re-import projects) with the caller's embedding and session, and no file changes; the caller's observedRevision is `snapshot.revision`, which the coordinator re-checks under the page lock. An occupied row number fails the insert with `storage_error` naming the occupant. Tests: `test/fence-fact-append.test.ts` (PGLite and Postgres: append, supersede, index-existing from a real fence-guard hold, each refusal, and remember's fence row byte for byte against the earlier construction). GBRA-449: `prepareFenceRowRetirement` strikes one or several rows of another page as a companion (a forgotten held row reads back `forgotten:`; `dropEntity` blanks the struck row's `entity` cell).
+- `src/core/facts/held-fact-move.ts` — GBRA-449 `moveHeldFacts(engine, sourceId)`, run by the extract_facts phase: facts a strict source held on `memory/unattributed` (an `entity` cell naming a page that did not exist) move into that page once it exists, one `managed_maintenance_move_held_fact` publication per entity (the fact-fence adoption preparer in `persistence/prepared-maintenance.ts`, plus the holding rows struck as a companion, the belief ledger told the rows transferred). A row that cannot move (a database-only target, a malformed fence, a duplicate claim, a prior refusal) stays held and is reported `held_fact_unmovable`.
+- `src/core/page-slug-grammar.ts` — `OP_PAGE_SLUG_RE` / `isOpPageSlug`, the page slug grammar operations accept (moved out of `ops/context.ts` so `facts-fence.ts` can validate the `entity` cell of `memory/unattributed` without importing the operations layer).
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index d4b0b1db1a..4f899700ee 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -98,7 +98,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op, which also records `distinct` decisions (`distinct_from`); every decision publishes through the page door (Git first on a repository source, the database on a repo-less one) under `persistence/publication-guard.ts`, with the revision it read. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).
-- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, vis... (line truncated to 2000 chars)
+- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; #6385: cells are read by the column the header names (`factsHeaderLayout`, `FACTS_FENCE_COLUMNS`), so an unknown, repeated or missing required header column is one `FACTS_TABLE_MALFORMED` and no rows, a header in canonical order keeps the positional typed tail, and `factsRowProblem` lets a row leave off only trailing optional columns and refuses a non-empty cell past the layout; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `upsertFactRow` throws `FenceRewriteRefusal` (fence-shared.ts) when the fence it starts from parses with warnings (#6385 R12): it re-renders the parsed rows, so a rewrite would delete the rows the parser skipped. `restoreHiddenFactRows(incoming, existing)` is the row-level, vis... (line truncated to 2000 chars) GBRA-449: `parseFactsFenceFor(body, { slug, reader })` reads the optional `entity` column only on `memory/unattributed` (`HOLDING_FACTS_COLUMNS`; a cell must be a page slug other than the holding page, else `FACTS_TABLE_MALFORMED`), and `reader: true` tolerates it where only the body is known (withdrawal overlay, remote strip); `parseFactsFence(body)` and every other page parse as before.
- `src/core/facts/attribution.ts` — speaker attribution's one dedup rule: `attributionCompatible(a, b)` is false only for two different known speakers (`user`, `assistant`, `other`); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: `findCandidateDuplicates` (`attributedTo` option, SQL pre-limit), `decideSingleFact` exact and cosine matches, capture exact/near matches, hot-memory collapse (`collapseHotFacts` splits a fingerprint group by speaker when it holds two), fence reindex (`duplicateActiveFenceRows`) and the managed batch key (`facts-prepare.ts`). `facts.attributed_to` (migration v215) is written by the extractor (`facts.attribution`, default on per `docs/eval/decisions/p2-e3-heldout/`; `false` opts out), carried in the fence's 15th cell (only on rows that have it), returned by `recall` and hot memory, rendered `(assistant said)` in context packs, and kept out of `consolidate` (takes are the user's own). Pinned by `test/facts/speaker-attribution.test.ts`.
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`, and the rewrite guard (#6385 R12) `assertFenceRewritable` / `FenceRewriteRefusal` that `upsertFactRow`, `upsertTakeRow`, `supersedeRow` and `mergePhantomFenceRows` throw when their input fence parses with warnings (the message names the fence only; the warnings, which embed row text, stay on the error). `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. `escapeFenceCell` also encodes fence-marker text (`gbrain:facts:begin` and the three siblings) by lengthening the ampersand run before `#58;` (`gbrain:X` → `gbrain&#58;X`, a literal `gbrain&#58;X` → `gbrain&amp;#58;X`), and `decodeFenceCell` (the decoder `parseRowCells` and `fence-repair/raw-rows.ts` share) removes exactly one level, so a claim that quotes a marker never becomes a live marker and a literal entity round-trips byte-identically; the lexical fail-closed privacy rule is unchanged. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
diff --git a/docs/guides/entity-scoped-facts.md b/docs/guides/entity-scoped-facts.md
index 93df561f7a..f2ab196f7e 100644
--- a/docs/guides/entity-scoped-facts.md
+++ b/docs/guides/entity-scoped-facts.md
@@ -110,7 +110,17 @@ each item of an `items` batch says the same for itself. If the brain's pages
are in a Git repository, the reply also carries an `entity_page_missing`
notice with the `put_page` call that creates the page. Once the page exists,
the next maintenance cycle (`gbrain dream`) can move the facts saved for that
-entity into the page's Facts table and its file. A brain with no Git
+entity into the page's Facts table and its file. On a source whose pages are
+canonical in Git (`canonical: git`), the fact is not left in the database
+alone: it is committed to Git as a row of `memory/unattributed` whose `entity`
+column names the entity, before the reply returns. The reply then names
+`page: memory/unattributed`, `persistence: {"mode": "filesystem"}` and
+`write_through: {"written": true, "held_for": "<entity>"}`. Once the entity
+has a page, the next maintenance cycle moves the row into it in one commit
+and strikes the held row (`moved to <entity>`, or just `moved` when the page
+is restricted); a page kept out of Git does not take it, and the run warns
+`HELD_FACT_UNMOVABLE`. Forgetting or replacing a held fact strikes its row
+too. A brain with no Git
repository gets no notice: there the database is the record, and the fact is
as safe as everything else in it.
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index 7188892e81..e84bfb3c65 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -372,7 +372,7 @@ MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filt
## `remember`
-MEMORY VERB (v1): save one fact to durable agent memory — the protocol write verb. provenance is REQUIRED (free text, e.g. "conversation 2026-06-12", "user said in chat", "import: notes.md"). Set `entity` whenever the fact is about a specific person/company/project — entity-scoped recall will not find it otherwise. ttl accepts duration shorthand ("30d", "12h") or an absolute ISO 8601 timestamp; ISO-8601 durations like "P30D" are rejected with a fix. visibility defaults to "world" (readable by every agent connected to this brain; pass "private" for local-CLI-only facts). A credential bound to a member, the brain owner's included, saves on its own member page as "private" by default; pass share: true to share a fact with everyone who reads the source. Response: branch on `status` (inserted|duplicate|superseded), never on `status_text` (human rendering only). On duplicate, `id` is the EXISTING fact's id. `page` names the page whose Facts table now holds the fact, and is absent when the fact is on no page: `remember` never creates a page, so a fact whose `entity` slug has no page is stored in the database only (`persistence: {mode: "database"}`, `write_through: {written: false, skipped: "entity_page_missing"}`) and still recalls. Each `items` entry carries its own `page`, `persistence` and `write_through`. Where the brain's pages are in a Git repository, that reply also carries an `entity_page_missing` notice with the `put_page` call that creates the page; the next maintenance cycle can then move the entity's facts into the page. For bulk extraction from a raw transcript use extract_facts instead.
+MEMORY VERB (v1): save one fact to durable agent memory — the protocol write verb. provenance is REQUIRED (free text, e.g. "conversation 2026-06-12", "user said in chat", "import: notes.md"). Set `entity` whenever the fact is about a specific person/company/project — entity-scoped recall will not find it otherwise. ttl accepts duration shorthand ("30d", "12h") or an absolute ISO 8601 timestamp; ISO-8601 durations like "P30D" are rejected with a fix. visibility defaults to "world" (readable by every agent connected to this brain; pass "private" for local-CLI-only facts). A credential bound to a member, the brain owner's included, saves on its own member page as "private" by default; pass share: true to share a fact with everyone who reads the source. Response: branch on `status` (inserted|duplicate|superseded), never on `status_text` (human rendering only). On duplicate, `id` is the EXISTING fact's id. `page` names the page whose Facts table now holds the fact, and is absent when the fact is on no page: `remember` never creates a page, so a fact whose `entity` slug has no page is stored in the database only (`persistence: {mode: "database"}`, `write_through: {written: false, skipped: "entity_page_missing"}`) and still recalls; on a source canonical in Git it is instead committed as a row of memory/unattributed naming the entity (`page: "memory/unattributed"`, `write_through: {written: true, held_for: "<entity>"}`) until maintenance moves it into the entity's page. Each `items` entry carries its own `page`, `persistence` and `write_through`. Where the brain's pages are in a Git repository, that reply also carries an `entity_page_missing` notice with the `put_page` call that creates the page; the next maintenance cycle can then move the entity's facts into the page. For bulk extraction from a raw transcript use extract_facts instead.
| Parameter | Type | Guidance |
| --- | --- | --- |
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 4d07990ba4..fb91e0e04c 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -424,6 +424,10 @@ Optional response fields; clients must ignore any they do not know.
has no page to take the fact. `no_repo_configured`: the source has no
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.
A fact saved for an entity with no page is stored and recalled like any
other. Where the source's pages are in Git, the reply also carries one
diff --git a/llms-full.txt b/llms-full.txt
index acfc7b8790..888161ef15 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7977,6 +7977,10 @@ Optional response fields; clients must ignore any they do not know.
has no page to take the fact. `no_repo_configured`: the source has no
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.
A fact saved for an entity with no page is stored and recalled like any
other. Where the source's pages are in Git, the reply also carries one
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 247e756eb1..fa42191c7f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -48,5 +48,5 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/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 1735 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-2446 remember_pageless_reply_gst2446 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the merge onto master dbf51462: 1734 + 1
+src/core/behavior-change-notice.ts 1736 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-2446 remember_pageless_reply_gst2446 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the merge onto master dbf51462: 1734 + 1; +1 GBRA-449 strict_held_facts_gbra449 row (since TBD until the merge slot; rows are data and cannot move): 1735 + 1
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 move
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 330a5e7186..6dfb5680ae 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1536,6 +1536,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.676.0', id: 'write_capacity_low_saved_gst2107', text: 'The `write_capacity_low` notice a write receipt carries now opens with "This write was saved" and its fix is the read-only `gbrain doctor --only persistence_capacity --json` (actor agent) instead of a `gbrain config set` cap raise for the user, so an agent reading the end of a successful write no longer reports it as refused. The one-more-year value doctor, the notice snapshot and `/metrics` recommend now uses the 7-day mean rate, so one bulk day is no longer projected for a year; days-to-exhaustion still uses the larger of the mean and the last 24 hours. A `write_quota_exhausted`, `write_quota_insufficient` or background-pause refusal names the same value doctor does instead of sizing the year from the latest 1,000 admissions.' },
{ since: '0.60.676.0', id: 'ingest_backfill_409_recovery_gst2112', text: 'A `revision_backfill_pending` refusal (a write to a page the revision backfill has not reached, including the 409 a webhook capture to such a page gets from `POST /ingest`) now names the command that resumes the backfill, `gbrain apply-migrations --force-schema` on the brain host, instead of `gbrain apply-migrations --yes`, which does not resume it once the schema is current. A capture answered 409 stores and queues nothing, so its sender sends it again after the backfill; an `ingest_capture` job already queued for such a page goes straight to dead and is re-run with `gbrain jobs retry <id>`.' },
{ since: '0.60.678.0', id: 'unmanaged_push_history_scan_8902', text: 'Four pushes from a checkout that is not a managed worktree now scan every local commit they publish for secrets, not only what they just wrote: the access-policy commit (`gbrain access rule` and the other policy writers), the durability-scaffolding commit of `gbrain sources harden`, `gbrain sources push`, and the first push of `gbrain bootstrap repo` (the whole history, since the remote has no such branch yet). A credential that a commit made with plain `git commit` added, even one a later commit removed, or one in a commit message, now refuses `publish_secret_found` naming the file, line, rule and commit (never the value), and nothing is pushed; history the scan cannot read in full refuses `publish_scan_unreadable`. The local commits stay where they are. `gbrain sources push` now pushes the exact commit it scanned, leased on the remote tip it read, and an allowlist (`.gbrain-scan-allow`) edit it commits itself still publishes; one a script committed is left for the user to review and push. Remove the value from the unpublished commits, or allowlist a false positive by fingerprint, then rerun.' },
+ { since: 'TBD', id: 'strict_held_facts_gbra449', text: 'On a source whose pages are canonical in Git (`canonical: git`), a `remember` whose `entity` slug has no page no longer stores the fact in the database alone, where a rebuild from Git would lose it: it is committed as a row of `memory/unattributed` with a new `entity` column naming the entity, and the reply reads `page: memory/unattributed`, `persistence.mode: filesystem` and `write_through: {written: true, held_for: <entity>}`. Once the entity has a page, the extract_facts maintenance phase moves the row into it in one commit (same fact id) and strikes the held row; forget and replaces strike it too. A gbrain older than this one cannot read a `memory/unattributed` file that carries the `entity` column: it holds the file as a malformed fence, so upgrade every host of a strict source together. Other sources and brains with no Git repository are unchanged.' },
{ since: 'TBD', id: 'remember_pageless_reply_gst2446', text: 'A `remember` whose `entity` slug has no page still saves to the database, and its reply now says so: it no longer carries `page` (it used to name the entity slug, a page that does not exist), and where the source has a checkout `write_through.skipped` reads `entity_page_missing` instead of `no_repo_configured`, in the reply and in the write receipt. Each `items` entry of a batch now carries `persistence` and `write_through`, as the single form does. Where the source\'s pages are in Git, the reply adds one `entity_page_missing` notice with the `put_page` call that creates the page. What is stored is unchanged.' },
];
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index c52f0ee742..e8ed16e9f9 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -82,6 +82,7 @@ import {
} from '../facts/supersede-resolve.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.ts';
+import { moveHeldFacts } from '../facts/held-fact-move.ts';
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { factsFenceView } from '../facts-fence.ts';
import { fenceReadOf, publishFenceGeneration, readFenceBlocks, FACT_FENCE_KIND, type FenceRead } from '../generations/fence.ts';
@@ -405,7 +406,7 @@ interface FenceReconcilePlan {
async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: string, sourceId: string, warnings: string[], managed: boolean): Promise<FenceReconcilePlan | null> {
// A segmented page's view and fence text come from its fences rows: only runs changed since their row was written are read.
const segmented = isSegmentedPage(page) ? await incrementalFactsFence(db, page) : null;
- const view = segmented?.view ?? factsFenceView(page);
+ const view = segmented?.view ?? factsFenceView({ ...page, slug });
// #6686: a lone fence below the timeline sentinel that parses cleanly is the page's fence, read where the writers
// edit it; one that does not parse keeps the #3625 guard below.
const below = !view.sections.body && view.sections.timeline ? view.timeline : null;
@@ -725,6 +726,8 @@ export interface ExtractFactsResult {
legacyPages: string[];
/** Unfenced rows this run appended to their page's fence and stamped with a row number (#5299). */
unfencedRowsFenced: number;
+ /** GBRA-449: facts held on memory/unattributed this run moved into their new entity page (present only when it moved any). */
+ heldFactsMoved?: number;
/** Active fence-owned rows expired because their page was soft-deleted. */
factsExpiredForDeletedPages: number;
guardTriggered: boolean;
@@ -840,6 +843,14 @@ export async function runExtractFacts(
} catch (e) {
result.warnings.push(`FACTS_FENCE_FAILED: ${(e instanceof Error ? e.message : String(e)).slice(0, 300)}`);
}
+ // GBRA-449: facts a strict source held on memory/unattributed move into their entity page once it exists.
+ try {
+ const held = await moveHeldFacts(engine, sourceId);
+ if (held.moved) result.heldFactsMoved = held.moved;
+ for (const row of held.unmovable) result.warnings.push(`HELD_FACT_UNMOVABLE: ${row.slug} facts ${row.fact_ids.join(',')} (${row.reason})`);
+ } catch (e) {
+ result.warnings.push(`HELD_FACT_UNMOVABLE: ${(e instanceof Error ? e.message : String(e)).slice(0, 300)}`);
+ }
}
// ── Empty-fence guard (per page, #6278) ─────────────────────────
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2afe7f15c0..aa9a07ad7c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -1022,7 +1022,7 @@ export const NOTICE_CODES = {
access_policy_pending: { kind: 'degraded', summary: 'A read touched a source whose folder rules are being narrowed or whose policy file does not validate: pages under the affected prefixes read as nobody until the brain host finishes it, so a missing page there is not proof the brain has nothing on it; the fix shows the policy state, then the host runs gbrain access resume --source <id> (database store); a git store finishes with gbrain sync --source <id> --no-pull.' },
degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },
facts_calibration_unmeasured: { kind: 'info', summary: 'recall --question ranked facts with semantic matching on an embedding model whose fact admission floors were never measured (`facts_calibration: {status: "unmeasured", model_key}`); a short facts list is weaker evidence of "nothing matched". Once per brain per session; the fix is the read-only `gbrain doctor --only fact_admission_floors --json`.' },
- entity_page_missing: { kind: 'info', summary: 'remember saved a fact for an entity that has no page, on a source whose pages are in Git: the fact is stored in the database only (`write_through.skipped: entity_page_missing`, no `page` in the reply) until the page exists. The fix is the put_page call that creates the page; the next maintenance cycle can then move the entity\'s facts into its Facts table.' },
+ entity_page_missing: { kind: 'info', summary: 'remember saved a fact for an entity that has no page, on a source whose pages are in Git: the fact is stored in the database only (`write_through.skipped: entity_page_missing`, no `page` in the reply) until the page exists. The fix is the put_page call that creates the page; the next maintenance cycle can then move the entity\'s facts into its Facts table. On a source canonical in Git the fact is committed instead, held on memory/unattributed (`write_through.held_for`) until the page exists.' },
private_fact_not_pushed: { kind: 'info', summary: 'remember saved a private fact: only local CLI recall reads it, and session hooks never push it into a new agent session.' },
local_transcripts: { kind: 'info', summary: 'The brain host keeps recent session transcripts that page reads never return and this connection cannot read; the fix is the CLI read (`gbrain transcripts recent --json`).' },
synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index 207c8afdb6..1fddafb794 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -49,6 +49,22 @@ import {
assertFenceRewritable,
} from './fence-shared.ts';
import { findLineOutsideFencedCode, locateOutsideCode, protectedRegions, unclosedCodeFenceStart } from './fence-scan.ts';
+import { isOpPageSlug } from './page-slug-grammar.ts';
+
+/**
+ * The page a fact saved without an entity is a row of (GBRA-190 G4, D3). On a strict source it also holds a fact whose
+ * entity has no page yet (GBRA-449): such a row names the entity in its `entity` cell, a column no other page accepts.
+ */
+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.
+ */
+export interface FactsFenceParseOpts { slug?: string | null; reader?: boolean }
+const readsEntity = (opts?: FactsFenceParseOpts): boolean => opts?.reader === true || opts?.slug === UNATTRIBUTED_MEMORY_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.
@@ -130,6 +146,8 @@ export interface ParsedFact {
* the cell on rewrite.
*/
attributedTo?: FactAttribution;
+ /** GBRA-449: on `memory/unattributed` only, the entity a held row is about (its page does not exist yet). */
+ entity?: string;
}
export interface FactsFenceParseResult {
@@ -172,9 +190,11 @@ export const FACTS_FENCE_COLUMNS = [
'#', 'claim', 'kind', 'confidence', 'visibility', 'notability', 'valid_from', 'valid_until', 'source', 'context',
'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to',
] as const;
-export type FactsFenceColumn = typeof FACTS_FENCE_COLUMNS[number];
+/** GBRA-449: `memory/unattributed`'s columns, the canonical ones then `entity`; every other page keeps FACTS_FENCE_COLUMNS. */
+export const HOLDING_FACTS_COLUMNS = [...FACTS_FENCE_COLUMNS, 'entity'] as const;
+export type FactsFenceColumn = typeof HOLDING_FACTS_COLUMNS[number];
/** Columns a header may leave out, and a row may omit at its end. */
-export const FACTS_OPTIONAL_COLUMNS: ReadonlySet<string> = new Set(['context', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to']);
+export const FACTS_OPTIONAL_COLUMNS: ReadonlySet<string> = new Set(['context', 'claim_metric', 'claim_value', 'claim_unit', 'claim_period', 'attributed_to', 'entity']);
/**
* #6385: the column each cell of a row is read as, from the header cells, or
@@ -184,18 +204,19 @@ export const FACTS_OPTIONAL_COLUMNS: ReadonlySet<string> = new Set(['context', '
* meaning (a 14-cell typed row under the 10-column header); any other header
* is the whole layout.
*/
-export function factsHeaderLayout(headerCells: readonly string[]): { layout: FactsFenceColumn[]; named: number } | { problem: string } {
+export function factsHeaderLayout(headerCells: readonly string[], columns: readonly FactsFenceColumn[] = FACTS_FENCE_COLUMNS):
+ { layout: FactsFenceColumn[]; named: number } | { problem: string } {
const names = headerCells.map(cell => cell.trim().toLowerCase());
const seen = new Set<string>();
for (const name of names) {
- if (!(FACTS_FENCE_COLUMNS as readonly string[]).includes(name)) return { problem: `unsupported header column "${name}"` };
+ if (!(columns as readonly string[]).includes(name)) return { problem: `unsupported header column "${name}"` };
if (seen.has(name)) return { problem: `duplicate header column "${name}"` };
seen.add(name);
}
- const missing = FACTS_FENCE_COLUMNS.find(column => !FACTS_OPTIONAL_COLUMNS.has(column) && !seen.has(column));
+ const missing = columns.find(column => !FACTS_OPTIONAL_COLUMNS.has(column) && !seen.has(column));
if (missing) return { problem: `header has no "${missing}" column` };
- const canonical = names.every((name, i) => name === FACTS_FENCE_COLUMNS[i]);
- return { layout: canonical ? [...FACTS_FENCE_COLUMNS] : names as FactsFenceColumn[], named: names.length };
+ const canonical = names.every((name, i) => name === columns[i]);
+ return { layout: canonical ? [...columns] : names as FactsFenceColumn[], named: names.length };
}
/**
@@ -231,6 +252,11 @@ function parseForgottenFromContext(context: string | undefined): boolean {
* `FACTS_TABLE_MALFORMED` sync-failures entries.
*/
export function parseFactsFence(body: string): FactsFenceParseResult {
+ return parseFactsFenceFor(body);
+}
+
+/** parseFactsFence for a known page: `memory/unattributed` also reads its `entity` column (GBRA-449). */
+export function parseFactsFenceFor(body: string, opts?: FactsFenceParseOpts): FactsFenceParseResult {
const { beginIdx, endIdx } = locateOutsideCode(body, FACTS_FENCE_BEGIN, FACTS_FENCE_END);
const warnings: string[] = [];
@@ -266,7 +292,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
const lower = cells.map(c => c.toLowerCase());
if (lower.includes('claim') && lower.includes('kind')) {
sawHeader = true;
- const header = factsHeaderLayout(cells);
+ const header = factsHeaderLayout(cells, readsEntity(opts) ? HOLDING_FACTS_COLUMNS : FACTS_FENCE_COLUMNS);
if ('problem' in header) {
warnings.push(`FACTS_TABLE_MALFORMED: ${header.problem}`);
return { facts: [], warnings };
@@ -299,7 +325,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
const visibilityRaw = cell('visibility'), notabilityRaw = cell('notability');
const validFromRaw = cell('valid_from'), validUntilRaw = cell('valid_until'), sourceRaw = cell('source'), contextRaw = cell('context');
const claimMetricRaw = cell('claim_metric'), claimValueRaw = cell('claim_value'), claimUnitRaw = cell('claim_unit');
- const claimPeriodRaw = cell('claim_period'), attributedToRaw = cell('attributed_to');
+ const claimPeriodRaw = cell('claim_period'), attributedToRaw = cell('attributed_to'), entityRaw = cell('entity');
const rowNum = parseInt(rowNumStr, 10);
if (!Number.isFinite(rowNum) || rowNum <= 0) {
@@ -352,6 +378,13 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
continue;
}
+ // GBRA-449: a held row's entity is a page slug; any other cell is a fence problem, so the page is held, never misfiled.
+ const entity = entityRaw.trim();
+ if (entity && (!isOpPageSlug(entity) || entity === UNATTRIBUTED_MEMORY_SLUG)) {
+ warnings.push(`FACTS_TABLE_MALFORMED: invalid entity "${entity}" in row ${rowNumStr} (expected a page slug such as people/alice-example)`);
+ continue;
+ }
+
const { text: claimText, struck } = stripStrikethrough(claimRaw);
const context = parseStringCell(contextRaw);
const supersededBy = parseSupersededByFromContext(context);
@@ -377,6 +410,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
claimUnit: parseStringCell(claimUnitRaw),
claimPeriod: parseStringCell(claimPeriodRaw),
...(attributedTo ? { attributedTo: attributedTo as FactAttribution } : {}),
+ ...(entity ? { entity } : {}),
});
}
@@ -457,13 +491,15 @@ export function renderFactsTable(facts: ParsedFact[]): string {
);
// Speaker attribution widens the header to 15; only rows that carry it
// are written 15 cells wide (typed cells padded), others keep their width.
- const anyAttributed = facts.some(f => f.attributedTo !== undefined);
+ // GBRA-449: a held row (memory/unattributed) names its entity in a 16th column, after attributed_to.
+ const anyEntity = facts.some(f => f.entity !== undefined);
+ const anyAttributed = anyEntity || facts.some(f => f.attributedTo !== undefined);
const wide = anyTyped || anyAttributed;
const header = wide
- ? `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |${anyAttributed ? ' attributed_to |' : ''}`
+ ? `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |${anyAttributed ? ' attributed_to |' : ''}${anyEntity ? ' entity |' : ''}`
: `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |`;
const separator = wide
- ? `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|${anyAttributed ? '---------------|' : ''}`
+ ? `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|${anyAttributed ? '---------------|' : ''}${anyEntity ? '--------|' : ''}`
: `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|`;
const rows = facts.map(f => {
const claimCell = f.active ? f.claim : `~~${f.claim}~~`;
@@ -471,6 +507,7 @@ export function renderFactsTable(facts: ParsedFact[]): string {
if (!wide) return base;
const valueCell = f.claimValue === undefined ? '' : String(f.claimValue);
const typed = `${base} ${escapeFenceCell(f.claimMetric ?? '')} | ${escapeFenceCell(valueCell)} | ${escapeFenceCell(f.claimUnit ?? '')} | ${escapeFenceCell(f.claimPeriod ?? '')} |`;
+ if (f.entity) return `${typed} ${f.attributedTo ?? ''} | ${escapeFenceCell(f.entity)} |`;
return f.attributedTo ? `${typed} ${f.attributedTo} |` : typed;
});
// #4615: the leading double-'' emits a BLANK LINE between the begin marker
@@ -609,8 +646,8 @@ export type NewFactRow = Omit<ParsedFact, 'rowNum' | 'active' | 'supersededBy' |
* the same row. Throws `FenceRewriteRefusal` when the existing fence does
* not parse cleanly: re-rendering it would drop the rows the parser skipped.
*/
-export function upsertFactRow(body: string, newRow: NewFactRow): { body: string; rowNum: number } {
- const parsed = parseFactsFence(body);
+export function upsertFactRow(body: string, newRow: NewFactRow, opts?: FactsFenceParseOpts): { body: string; rowNum: number } {
+ const parsed = parseFactsFenceFor(body, opts);
assertFenceRewritable('facts', parsed);
const { facts } = parsed;
const nextRowNum = newRow.rowNum
@@ -639,6 +676,7 @@ function factRow(newRow: NewFactRow, rowNum: number): ParsedFact {
claimUnit: newRow.claimUnit,
claimPeriod: newRow.claimPeriod,
...(newRow.attributedTo ? { attributedTo: newRow.attributedTo } : {}),
+ ...(newRow.entity ? { entity: newRow.entity } : {}),
};
}
@@ -651,13 +689,14 @@ function factRow(newRow: NewFactRow, rowNum: number): ParsedFact {
* (O(N × M): minutes on a fence of thousands of rows). The page it returns is
* the page the one-row-at-a-time calls leave.
*/
-export function factsFenceEditor<T extends { compiled_truth: string; timeline: string }>(page: T, section: 'compiled_truth' | 'timeline') {
+export function factsFenceEditor<T extends { compiled_truth: string; timeline: string; slug?: string }>(page: T, section: 'compiled_truth' | 'timeline') {
+ const opts = { slug: page.slug };
let current = page;
let rows: ParsedFact[] | null = null;
return {
append(newRow: NewFactRow & { rowNum: number }): void {
if (!rows) {
- const parsed = parseFactsFence(current[section]);
+ const parsed = parseFactsFenceFor(current[section], opts);
assertFenceRewritable('facts', parsed);
rows = parsed.facts;
}
@@ -672,7 +711,7 @@ export function factsFenceEditor<T extends { compiled_truth: string; timeline: s
rows = rows.map(struck);
return;
}
- const found = parseFactsFence(current[key]).facts;
+ const found = parseFactsFenceFor(current[key], opts).facts;
if (!found.some(f => f.rowNum === rowNum)) continue;
current = { ...current, [key]: replaceOrInsertFactsFence(current[key], renderFactsTable(found.map(struck))) };
return;
@@ -766,8 +805,9 @@ export interface FactsFenceView {
timelineMarker: boolean;
}
-export function factsFenceView(page: { compiled_truth: string | null; timeline?: string | null }): FactsFenceView {
- return { body: parseFactsFence(page.compiled_truth ?? ''), timeline: parseFactsFence(page.timeline ?? ''), sections: factsFenceSections(page),
+export function factsFenceView(page: { compiled_truth: string | null; timeline?: string | null; slug?: string }): FactsFenceView {
+ const opts = { slug: page.slug };
+ return { body: parseFactsFenceFor(page.compiled_truth ?? '', opts), timeline: parseFactsFenceFor(page.timeline ?? '', opts), sections: factsFenceSections(page),
timelineMarker: timelineHasGenuineFactsFenceMarker(page.timeline ?? '') };
}
@@ -807,9 +847,9 @@ export function factsFenceSection(page: { compiled_truth: string | null; timelin
* #6686: strike fence row `rowNum` as superseded by row `by` in whichever section's fence holds it (a split page can
* hold the old row in the other section than the one the new row went to); a page without the row is returned as is.
*/
-export function strikeFactRowInPage<T extends { compiled_truth: string; timeline: string }>(page: T, rowNum: number, by: number, validUntil?: string): T {
+export function strikeFactRowInPage<T extends { compiled_truth: string; timeline: string; slug?: string }>(page: T, rowNum: number, by: number, validUntil?: string): T {
for (const key of ['compiled_truth', 'timeline'] as const) {
- const rows = parseFactsFence(page[key]).facts;
+ const rows = parseFactsFenceFor(page[key], { slug: page.slug }).facts;
if (!rows.some(f => f.rowNum === rowNum)) continue;
return { ...page, [key]: replaceOrInsertFactsFence(page[key], renderFactsTable(rows.map(f => f.rowNum === rowNum
? { ...f, active: false, supersededBy: by, context: `superseded by #${by}`, ...(validUntil ? { validUntil } : {}) } : f))) };
@@ -945,7 +985,7 @@ export function stripFactsFence(body: string, opts: StripFactsFenceOpts = {}): s
// which is the safe direction at a privacy boundary — when in doubt,
// strip rather than leak.
if (keep) {
- const { facts } = parseFactsFence(body.slice(region.start, region.end));
+ const { facts } = parseFactsFenceFor(body.slice(region.start, region.end), { reader: true });
out += renderFactsTable(facts.filter(f => keep.has(f.visibility)));
}
}
diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.ts
index f82e96cdab..c09cf4d8f3 100644
--- a/src/core/facts/extract-from-fence.ts
+++ b/src/core/facts/extract-from-fence.ts
@@ -45,10 +45,12 @@ import { computeEffectiveDate } from '../effective-date.ts';
/** #7247: the page dates that say when its content happened. A page's creation or import time is not one. */
/**
- * The page a fact saved without an entity is a row of (GBRA-190 G4, D3). Its fence rows belong to no entity: they
- * project with `entity_slug` NULL, so their withdrawal is source-wide ('*'), as a subjectless fact's always was.
+ * The page a fact saved without an entity is a row of (GBRA-190 G4, D3). A row with no `entity` cell belongs to no
+ * entity: it projects with `entity_slug` NULL, so its withdrawal is source-wide ('*'), as a subjectless fact's always
+ * was. A held row (GBRA-449: its entity has no page yet, on a strict source) projects the entity its cell names.
*/
-export const UNATTRIBUTED_MEMORY_SLUG = 'memory/unattributed';
+export { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';
+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';
export const FACT_DATE_SOURCES: ReadonlySet<string> = new Set(['event_date', 'date', 'published', 'filename']);
@@ -271,7 +273,7 @@ export function extractFactsFromFenceText(
const row: FenceExtractedFact = {
fact: f.claim,
kind: f.kind as FactKind,
- entity_slug: slug === UNATTRIBUTED_MEMORY_SLUG ? null : slug,
+ entity_slug: slug === UNATTRIBUTED_MEMORY_SLUG ? f.entity ?? null : slug,
visibility: f.visibility as FactVisibility,
notability: f.notability,
context: f.context ?? null,
diff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.ts
index 7f529fc81c..f950735fba 100644
--- a/src/core/facts/fence-fact-append.ts
+++ b/src/core/facts/fence-fact-append.ts
@@ -32,7 +32,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import type { Page } from '../types.ts';
import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { factsFenceSection, fenceCellReadBackProblem, formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, strikeFactRowInPage, upsertFactRow } from '../facts-fence.ts';
+import { factsFenceSection, fenceCellReadBackProblem, formatFenceDate, parseFactsFenceFor, renderFactsTable, replaceOrInsertFactsFence, strikeFactRowInPage, upsertFactRow } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { materializedPage, segmentedOverCeiling } from '../persistence/segmented-apply.ts';
@@ -49,6 +49,7 @@ import type { TrustTier } from '../trust/tier.ts';
import { extractFactsFromFenceText, UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';
import { rememberAcceptsPageCreatedSince } from '../persistence/page-identity.ts';
import { fenceRowOf, withHeldFactsFence, type FenceRowInput } from './unfenced-facts.ts';
+import { withdrawnFact } from './withdrawal-overlay.ts';
export type FenceFactAppendInput = {
/** The facts row to publish; `row_num` and `source_markdown_slug` are the helper's. kind and visibility default as insertFacts does. */
@@ -90,12 +91,13 @@ async function insertFenceFactRow(tx: BrainEngine, row: WriteRequest, rowNum: nu
{ fix: requestReceiptFix(row) });
}
-/** One fact as its fence cell at `rowNum` (`fenceRowOf`, the one renderer). */
-function fenceCellFor(fact: FenceFactAppendInput['fact'], rowNum: number): ReturnType<typeof fenceRowOf> {
- return fenceRowOf({ kind: (fact.kind ?? 'fact') as FenceRowInput['kind'], visibility: fact.visibility ?? 'private', context: fact.context ?? null, valid_from: fact.valid_from,
+/** One fact as its fence cell at `rowNum` (`fenceRowOf`, the one renderer); on memory/unattributed a held fact names its entity (GBRA-449). */
+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 } : {};
+ 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,
- notability: fact.notability ?? null, confidence: fact.confidence ?? null }, rowNum, fact.fact);
+ notability: fact.notability ?? null, confidence: fact.confidence ?? null }, rowNum, fact.fact) };
}
/**
@@ -109,7 +111,7 @@ export async function prepareFenceFactCreate(engine: BrainEngine, row: WriteRequ
const [indexedMax] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);
const rowNum = (indexedMax?.n ?? 0) + 1;
const { expected_revision: _ignored, ...intent } = row.intent ?? {};
- const content = `${input.frontmatter}\n${upsertFactRow(`${input.heading}\n`, fenceCellFor(input.fact, rowNum)).body}`;
+ const content = `${input.frontmatter}\n${upsertFactRow(`${input.heading}\n`, fenceCellFor(input.fact, rowNum, row.slug)).body}`;
const prepared = await withPendingFenceRows({ ...page, rowNums: [rowNum], tier: input.pendingTier },
() => preparePageMutation(engine, { ...row, intent: { ...intent, content, force: false } }, config, undefined, signal, { unprojected: true }));
if (prepared.observedRevision !== null) {
@@ -140,7 +142,7 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ
if (input.mode === 'index-existing') {
const { rowNum } = input;
- const cell = [base.compiled_truth, base.timeline ?? ''].flatMap(text => parseFactsFence(text).facts).find(f => f.rowNum === rowNum);
+ const cell = [base.compiled_truth, base.timeline ?? ''].flatMap(text => parseFactsFenceFor(text, page).facts).find(f => f.rowNum === rowNum);
const problem = fenceCellReadBackProblem(cell, { fact: fact.fact, visibility: fact.visibility ?? 'private' });
if (problem || !cell) {
const reason = problem ?? 'row_missing';
@@ -165,13 +167,13 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ
// #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.
const section = factsFenceSection(target.page);
const fenced = { compiled_truth: target.page.compiled_truth, timeline: target.page.timeline ?? '' };
- const rowNum = Math.max(indexedMax?.n ?? 0, ...[fenced.compiled_truth, fenced.timeline].flatMap(text => parseFactsFence(text).facts.map(f => f.rowNum))) + 1;
- const cell = fenceCellFor(fact, rowNum);
+ const rowNum = Math.max(indexedMax?.n ?? 0, ...[fenced.compiled_truth, fenced.timeline].flatMap(text => parseFactsFenceFor(text, page).facts.map(f => f.rowNum))) + 1;
+ const cell = fenceCellFor(fact, rowNum, row.slug);
const unfenced = snapshot ? (await withHeldFactsFence(engine, row.source_id, row.slug, fenced))[section] : fenced[section];
// #6385 R12: an entity fence that does not parse cleanly refuses typed instead of losing the rows it skipped.
- const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(unfenced, cell));
+ const appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(unfenced, cell, page));
let next = { ...fenced, [section]: appended.body };
- if (input.supersede) next = strikeFactRowInPage(next, input.supersede.rowNum, rowNum, input.supersede.validUntil ? formatFenceDate(input.supersede.validUntil) : undefined);
+ if (input.supersede) next = strikeFactRowInPage({ ...next, slug: row.slug }, input.supersede.rowNum, rowNum, input.supersede.validUntil ? formatFenceDate(input.supersede.validUntil) : undefined);
const content = serializePageToMarkdown({ ...base, ...next }, snapshot?.tags ?? []);
// The canonical parser/chunker and durable filesystem publication; the CAS binds this render to the snapshot.
// #5575 ENG-1: the new row has no facts row yet; its chunks are cut at the append's tier.
@@ -197,7 +199,8 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ
* row is gone (nothing in a file to strike). The page write is prepared unprojected, as remember's own is.
*/
export async function prepareFenceRowRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, slug: string,
- retire: { rowNum: number; note: string; validUntil: Date | null }, signal?: AbortSignal): Promise<CompanionPage | null> {
+ retire: { rowNum: number | readonly number[]; note: string; validUntil: Date | null; forgotten?: boolean; dropEntity?: boolean }, signal?: AbortSignal): Promise<CompanionPage | null> {
+ const retired = new Set([retire.rowNum].flat());
const snapshot = await engine.readPageSnapshot(slug, { sourceId: row.source_id, includeDeleted: true });
if (!snapshot || snapshot.page.deleted_at) return null;
if (segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, `${row.operation} facts fence write`);
@@ -205,13 +208,14 @@ export async function prepareFenceRowRetirement(engine: BrainEngine, row: WriteR
// #6188 / #6385 R12, as the append: the stored fence is normalized first and a residual refuses typed instead of losing the rows it skipped.
const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug, kind: 'facts', page: base });
const fenced = { compiled_truth: target.page.compiled_truth, timeline: target.page.timeline ?? '' };
- const section = (['compiled_truth', 'timeline'] as const).find(key => parseFactsFence(fenced[key]).facts.some(f => f.rowNum === retire.rowNum && f.active));
+ const section = (['compiled_truth', 'timeline'] as const).find(key => parseFactsFenceFor(fenced[key], { slug }).facts.some(f => retired.has(f.rowNum) && f.active));
if (!section) return null;
const until = retire.validUntil ? formatFenceDate(retire.validUntil) : undefined;
- const parsed = parseFactsFence(fenced[section]);
+ const parsed = parseFactsFenceFor(fenced[section], { slug });
refuseUnparsedRewrite(target.page, slug, row.source_id, () => assertFenceRewritable('facts', parsed));
- const rows = parsed.facts.map(f => f.rowNum === retire.rowNum
- ? { ...f, active: false, context: [retire.note, f.context?.trim()].filter(Boolean).join(' | '), ...(until ? { validUntil: until } : {}) } : f);
+ // GBRA-449: a forgotten held row is struck as a withdrawal strikes a row (`forgotten: <note>`), so it reads back forgotten.
+ const rows = parsed.facts.map(f => !retired.has(f.rowNum) || !f.active ? f : retire.forgotten ? withdrawnFact(f, (retire.validUntil ?? new Date()).toISOString().slice(0, 10), retire.note)
+ : { ...f, active: false, context: [retire.note, f.context?.trim()].filter(Boolean).join(' | '), ...(until ? { validUntil: until } : {}), ...(retire.dropEntity ? { entity: undefined } : {}) });
const content = serializePageToMarkdown({ ...base, ...fenced, [section]: replaceOrInsertFactsFence(fenced[section], renderFactsTable(rows)) }, snapshot.tags);
const prepared = await preparePageMutation(engine, { ...row, slug, page_id: snapshot.page.id,
intent: { ...row.intent, content, expected_revision: snapshot.revision, force: false } }, config, undefined, signal, { unprojected: true });
diff --git a/src/core/facts/held-fact-move.ts b/src/core/facts/held-fact-move.ts
new file mode 100644
index 0000000000..22350305dc
--- /dev/null
+++ b/src/core/facts/held-fact-move.ts
@@ -0,0 +1,62 @@
+/**
+ * GBRA-449: 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`.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';
+import { maintenancePreflight, submitPlannedFactFenceAdoption } from '../persistence/prepared-maintenance.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { 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). */
+ unmovable: Array<{ code: 'held_fact_unmovable'; slug: string; fact_ids: number[]; reason: string }>;
+}
+
+export async function moveHeldFacts(engine: BrainEngine, sourceId: string): Promise<HeldFactMoveOutcome> {
+ const outcome: HeldFactMoveOutcome = { moved: 0, moved_slugs: [], unmovable: [] };
+ const rows = await engine.executeRaw<UnfencedFactRow>(
+ `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
+ 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
+ AND 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]);
+ if (rows.length === 0) return outcome;
+ const authority = await maintenancePreflight(engine, sourceId);
+ if (!authority) return outcome;
+ const groups = new Map<string, UnfencedFactRow[]>();
+ for (const row of rows) groups.set(row.entity_slug!, [...groups.get(row.entity_slug!) ?? [], row]);
+ 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 });
+ };
+ for (const [slug, group] of groups) {
+ try {
+ 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 page not every reader of the source can read is not named on the world-readable holding page: its struck row loses its entity cell.
+ const plan = await planManagedPage(engine, authority, sourceId, slug, group, { note: page.visible === true ? `moved to ${slug}` : 'moved' });
+ 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);
+ } catch (error) {
+ unmovable(slug, group.map(r => r.id), (error instanceof Error ? error.message : String(error)).slice(0, 300));
+ }
+ }
+ return outcome;
+}
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index d37feab25a..00843c2e69 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -224,7 +224,8 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, i
'Pass the same entity as the fact being replaced, or forget the old fact and remember the new one separately.');
}
// GBRA-190 G4: a fact saved without an entity is a row of memory/unattributed; linking it strikes that row in the same write.
- const linking = target.entity_slug == null && input.entity_slug != null && candidate.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG;
+ // GBRA-449: 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;
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.ts
index 791620f330..057375f10a 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -485,14 +485,15 @@ function recordUnadoptable(outcome: UnfencedFactsOutcome, slug: string, records:
}
/** One managed page, planned read-only: what the adoption would do with it right now. */
-type ManagedPagePlan =
+export type ManagedPagePlan =
| { kind: 'no_page' }
| { kind: 'warnings'; warnings: string[] }
| { kind: 'unadoptable'; records: UnadoptableFactRecord[] }
| { kind: 'submit'; snapshot: NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>; fence: { body: string; assignments: Array<{ id: string; row_num: number }>; rejected: UnadoptableFactRecord[] };
request: Extract<Awaited<ReturnType<typeof planFactFenceAdoption>>, { kind: 'submit' }> };
-async function planManagedPage(engine: BrainEngine, authority: MaintenanceAuthority, sourceId: string, entitySlug: string, group: UnfencedFactRow[]): Promise<ManagedPagePlan> {
+export async function planManagedPage(engine: BrainEngine, authority: MaintenanceAuthority, sourceId: string, entitySlug: string, group: UnfencedFactRow[],
+ move?: { note: string }): Promise<ManagedPagePlan> {
const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });
if (!snapshot) return { kind: 'no_page' };
const fence = await planFence(engine, sourceId, entitySlug, serializePageToMarkdown(snapshot.page, snapshot.tags), group);
@@ -500,7 +501,7 @@ async function planManagedPage(engine: BrainEngine, authority: MaintenanceAuthor
if (fence.assignments.length === 0) return { kind: 'unadoptable', records: fence.rejected };
const request = await planFactFenceAdoption(engine, authority, entitySlug, {
content: fence.body, expectedRevision: snapshot.revision,
- assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })),
+ assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })), ...(move ? { move } : {}),
});
if (request.kind === 'suppressed') {
return { kind: 'unadoptable', records: [...fence.rejected, ...fence.assignments.map(a => ({ source_id: sourceId, slug: entitySlug,
@@ -509,6 +510,13 @@ async function planManagedPage(engine: BrainEngine, authority: MaintenanceAuthor
return { kind: 'submit', snapshot, fence, request };
}
+/** Whether a managed page publishes to a canonical file (it records one, or one exists at its slug path). */
+export async function pageHasFile(engine: BrainEngine, sourceId: string, slug: string, page: { source_path?: string | null; source_uri?: string | null }): Promise<boolean> {
+ if (page.source_path || page.source_uri?.startsWith('file:')) return true;
+ const target = await resolvePageWriteTarget(engine, slug, sourceId);
+ return target.ok && existsSync(target.filePath);
+}
+
/**
* Managed brains (#5728 class): the managed writer guard refuses direct fence
* writes into the canonical worktree and any raw `UPDATE facts`. Each page
@@ -555,9 +563,7 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi
continue;
}
recordUnadoptable(outcome, entitySlug, fence.rejected);
- const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
- await submitPlannedFactFenceAdoption(engine, authority, entitySlug, request,
- Boolean(snapshot.page.source_path) || snapshot.page.source_uri?.startsWith('file:') === true || (target.ok && existsSync(target.filePath)));
+ await submitPlannedFactFenceAdoption(engine, authority, entitySlug, request, await pageHasFile(engine, sourceId, entitySlug, snapshot.page));
outcome.fenced += fence.assignments.length;
outcome.pages_touched += 1;
outcome.fenced_slugs.push(entitySlug);
diff --git a/src/core/facts/withdrawal-overlay.ts b/src/core/facts/withdrawal-overlay.ts
index 43c30af979..409e954e25 100644
--- a/src/core/facts/withdrawal-overlay.ts
+++ b/src/core/facts/withdrawal-overlay.ts
@@ -1,10 +1,12 @@
import { createHash } from 'node:crypto';
-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, parseFactsFenceFor, renderFactsTable, type ParsedFact } from '../facts-fence.ts';
import type { PageWithdrawal } from '../page-state/types.ts';
import { OperationError } from '../ops/contract.ts';
import { normalizeLoweredClaim } from './withdrawal-schema.ts';
export const WITHDRAWAL_MARKER_LIMIT = 16_384;
+/** A withdrawal reads a held row's `entity` cell wherever writes let it be (memory/unattributed, GBRA-449). */
+const READER = { reader: true } as const;
/** Preserve historical expiry and context while emitting the parser's explicit withdrawal marker. */
export function withdrawnFact(fact: ParsedFact, date: string, reason = 'memory withdrawn'): ParsedFact {
@@ -27,7 +29,7 @@ export function withdrawalFenceBlocks(body: string): Array<{ start: number; end:
continue;
}
if (!open) continue;
- blocks.push({ start: open.start, end: marker.end, parsed: parseFactsFence(body.slice(open.start, marker.end)) });
+ blocks.push({ start: open.start, end: marker.end, parsed: parseFactsFenceFor(body.slice(open.start, marker.end), READER) });
open = undefined;
}
const inline: typeof blocks = [];
@@ -67,7 +69,7 @@ function inlineCodeFenceBlocks(body: string, markers: FenceMarker[]): Array<{ st
for (let i = 0; i < markers.length; i++) {
const begin = markers[i], end = markers[i + 1];
if (begin.kind !== 'begin' || end?.kind !== 'end' || !(begin.inlineCode || end.inlineCode)) continue;
- const parsed = parseFactsFence(body.slice(begin.start, end.end));
+ const parsed = parseFactsFenceFor(body.slice(begin.start, end.end), READER);
if (parsed.facts.length || parsed.warnings.length) blocks.push({ start: begin.start, end: end.end, parsed });
}
return blocks;
@@ -94,7 +96,7 @@ export function ambiguousWithdrawalFenceSegments(body: string): string[] {
continue;
}
const segment = body.slice(open.start, marker.end);
- if (parseFactsFence(segment).warnings.length) segments.push(segment);
+ if (parseFactsFenceFor(segment, READER).warnings.length) segments.push(segment);
boundary = marker.end;
open = undefined;
}
diff --git a/src/core/fence-repair/import-step.ts b/src/core/fence-repair/import-step.ts
index 89c4f547cb..7c9dfe0167 100644
--- a/src/core/fence-repair/import-step.ts
+++ b/src/core/fence-repair/import-step.ts
@@ -11,7 +11,7 @@
* number is never reused and a stored row keeps its number.
*/
import type { BrainEngine } from '../engine.ts';
-import { parseFactsFence } from '../facts-fence.ts';
+import { parseFactsFenceFor } from '../facts-fence.ts';
import { parseTakesFence } from '../takes-fence.ts';
import { screenFenceCtx, type ContentRefusal, type FenceScreen, type ImportScreenResult } from '../import-screen.ts';
import type { ParsedMarkdown, ParseOpts } from '../markdown.ts';
@@ -27,7 +27,7 @@ import type { FenceCtx, FenceFix, FenceKind, FencePage, StoredRowMap } from './t
export function hiddenFenceRows(existing: FencePage): Set<number> {
const rows = new Set<number>();
for (const text of [existing.compiled_truth ?? '', existing.timeline ?? '']) {
- for (const fact of parseFactsFence(text).facts) if (fact.visibility !== 'world') rows.add(fact.rowNum);
+ for (const fact of parseFactsFenceFor(text, existing).facts) if (fact.visibility !== 'world') rows.add(fact.rowNum);
for (const take of parseTakesFence(text).takes) rows.add(take.rowNum);
}
return rows;
@@ -149,7 +149,7 @@ interface StoredPageInput { sourceId: string; slug: string; page: FencePage & {
/** Tier 1 over a page body the caller is about to write (switch read only when there is a fix; stored rows only for `renumber`). */
async function storedPageStep(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, input: StoredPageInput): Promise<{ page: FencePage; step: FenceStep<FencePage> }> {
- const page = { compiled_truth: input.page.compiled_truth ?? '', timeline: input.page.timeline ?? '' };
+ const page = { compiled_truth: input.page.compiled_truth ?? '', timeline: input.page.timeline ?? '', slug: input.slug };
const ctx: FenceCtx = { pageVisibility: effectiveVisibility({ kind: 'page', page: { type: input.page.type ?? null, frontmatter: input.page.frontmatter,
folder_restricted: await folderRestricted(engine, input.sourceId, input.slug) } }) };
let step = fenceStep(page, ctx, { normalize: true });
diff --git a/src/core/fence-repair/page-checks.ts b/src/core/fence-repair/page-checks.ts
index f6b4e3b0c8..b0bc9faf17 100644
--- a/src/core/fence-repair/page-checks.ts
+++ b/src/core/fence-repair/page-checks.ts
@@ -9,7 +9,7 @@
* chunker and the strip functions share) hid before a repair and shows after
* it.
*/
-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFenceFor } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
import { indexOfOutsideCode, protectedRegions, scanMarkdownCode } from '../fence-scan.ts';
import type { FenceKind, FencePage, FenceSection } from './types.ts';
@@ -41,7 +41,7 @@ export function strictFailures(page: FencePage): StrictFailure[] {
const numbers: Record<FenceKind, number[]> = { facts: [], takes: [] };
for (const [section, text] of sectionsOf(page)) {
for (const kind of repeatedMarkerKinds(text)) failures.push({ section, fence: kind, check: 'repeated_marker', rows: [] });
- const facts = parseFactsFence(text);
+ const facts = parseFactsFenceFor(text, page);
const takes = parseTakesFence(text);
if (facts.warnings.length) failures.push({ section, fence: 'facts', check: 'warnings', rows: [] });
if (takes.warnings.length) failures.push({ section, fence: 'takes', check: 'warnings', rows: [] });
diff --git a/src/core/fence-repair/refusal.ts b/src/core/fence-repair/refusal.ts
index 01c8845569..59bd313857 100644
--- a/src/core/fence-repair/refusal.ts
+++ b/src/core/fence-repair/refusal.ts
@@ -13,7 +13,7 @@
* versioned `error_detail.fence` that survives receipt compaction, is read back
* into the same location by `fenceReceiptLocation`.
*/
-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, type ParsedFact } from '../facts-fence.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFenceFor, type ParsedFact } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence, type ParsedTake } from '../takes-fence.ts';
import { codeEndAt, indexOfOutsideCode, scanMarkdownCode, type MarkdownCodeMap } from '../fence-scan.ts';
import { FenceRewriteRefusal } from '../fence-shared.ts';
@@ -147,7 +147,7 @@ export interface CanonicalFenceScan {
}
/** Parse both canonical sections once and list every reason the projection would refuse them. */
-export function scanCanonicalFences(page: { compiled_truth: string; timeline?: string | null }): CanonicalFenceScan {
+export function scanCanonicalFences(page: { compiled_truth: string; timeline?: string | null; slug?: string }): CanonicalFenceScan {
const fields: Array<[FenceSection, string]> = [['body', page.compiled_truth ?? ''], ['timeline', page.timeline ?? '']];
const empty: CanonicalFenceScan = { defects: [], facts: [], takes: [], quoting: false, sections: { facts: new Map(), takes: new Map() } };
// No marker text at all: nothing to parse or refuse (the parsers return nothing either).
@@ -167,7 +167,7 @@ export function scanCanonicalFences(page: { compiled_truth: string; timeline?: s
}
quoting ||= quotesMarker(field, code);
}
- const parsed = fields.map(([section, field]) => ({ section, field, facts: parseFactsFence(field), takes: parseTakesFence(field) }));
+ const parsed = fields.map(([section, field]) => ({ section, field, facts: parseFactsFenceFor(field, page), takes: parseTakesFence(field) }));
for (const { section, field, facts, takes } of parsed) {
for (const [fence, warnings] of [['facts', facts.warnings], ['takes', takes.warnings]] as const) {
if (warnings.length) defects.push(warningLocation(rawOf(section, field), fence, section, warnings));
diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.ts
index 036bf6a1c1..acaf1e968e 100644
--- a/src/core/fence-repair/types.ts
+++ b/src/core/fence-repair/types.ts
@@ -121,4 +121,6 @@ export interface FenceCtx {
export interface FencePage {
compiled_truth: string;
timeline: string;
+ /** The page's slug when known: only `memory/unattributed` reads the facts `entity` column (GBRA-449). */
+ slug?: string;
}
diff --git a/src/core/generations/fence-evidence.ts b/src/core/generations/fence-evidence.ts
index 1c0f4fd8c2..8612ba9af1 100644
--- a/src/core/generations/fence-evidence.ts
+++ b/src/core/generations/fence-evidence.ts
@@ -24,7 +24,7 @@ const rowKey = (row: { row_num: number | null; fact: string; visibility?: string
/** The (row number, claim, visibility) of every row a body's facts fence holds; nothing for a body that was not read whole. */
export function fenceRowKeys(body: FenceBody, slug: string, sourceId: string): Set<string> {
if (isSegmentedPage(body as { body_storage?: 'segmented' | null }) || body.compiled_truth == null) return new Set();
- const scan = scanCanonicalFences({ compiled_truth: body.compiled_truth, timeline: body.timeline ?? '' });
+ const scan = scanCanonicalFences({ compiled_truth: body.compiled_truth, timeline: body.timeline ?? '', slug });
return new Set(extractFactsFromFenceText(scan.facts, slug, sourceId).map(rowKey));
}
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 6f714ced7a..26508e73a7 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -67,7 +67,7 @@ import { abortSegmentedStaging, bodyStorageOf, demoteSegmentedPage, materialized
stringWriteStorage, type SegmentedImport } from './persistence/segmented-apply.ts';
import type { SegmentedStagingOwner } from './page-body/ingest.ts';
import type { PageBodyPolicy } from './page-body/limits.ts';
-import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';
+import { parseFactsFenceFor, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';
import { assertOriginUnclaimed, isOriginClaimRefusal } from './persistence/origin-guard.ts';
import { fileBodyMatchesStored, readStoredBody } from './facts/file-body-guard.ts';
import { currentEngineScope, needsEngineScope, runInEngineScope, withEngineScope } from './engine-scope.ts';
@@ -93,8 +93,8 @@ function mergeHiddenFactRowsIntoBody(
existingBody: string | null | undefined,
): string {
if (!existingBody) return incomingBody;
- const incomingFacts = parseFactsFence(incomingBody);
- const existingFacts = parseFactsFence(existingBody);
+ const incomingFacts = parseFactsFenceFor(incomingBody, { slug });
+ const existingFacts = parseFactsFenceFor(existingBody, { slug });
const merge = restoreHiddenFactRows(incomingFacts, existingFacts);
if (merge) {
if (merge.renumbered.length > 0) {
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index a0d51c279a..e306ee25f4 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -448,7 +448,7 @@ export function screenImportContent(input: ImportScreenInput): ImportScreenResul
let fences: FenceScreen | undefined;
if (input.fences) {
const before = { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '' };
- const step = fenceStep(before, screenFenceCtx(parsed, input.activePack), { normalize: input.normalize !== false });
+ const step = fenceStep({ ...before, slug: parsed.slug }, screenFenceCtx(parsed, input.activePack), { normalize: input.normalize !== false });
if (step.status === 'residual') {
const issues = fenceIssuesWire([...step.issues, ...step.fixable]);
if (input.fences === 'coordinated') return { status: 'refused', refusal: { ...fenceRefusal(step.location), fence_issues: issues } };
diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.ts
index 3ccb995904..781c50293f 100644
--- a/src/core/interop-notices.ts
+++ b/src/core/interop-notices.ts
@@ -330,12 +330,15 @@ export function privateFactNotice(factId?: string | number): Notice {
* GST-2446: remember saved a fact for an entity that has no page, on a source whose pages are in Git. The fact is in
* the database alone until the page exists; the fix is the call that creates it. Once per entity per session.
*/
-export function entityPageMissingNotice(sourceId: string, entitySlug: string): Notice {
+export function entityPageMissingNotice(sourceId: string, entitySlug: string, held = false): Notice {
return {
code: 'entity_page_missing',
kind: 'info',
dedupe_key: `${sourceId}\0${entitySlug}`,
- 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. To give it a file, create the page; the next maintenance cycle (gbrain dream) can then move the facts saved for ${entitySlug} into the page's Facts table, in its file.`,
+ // GBRA-449: on a strict source the fact is held in Git, as a row of memory/unattributed that names the entity.
+ why: held
+ ? `Saved and committed to Git; held on memory/unattributed until ${entitySlug} has a page. Say that when you report the save. Once the page exists, the next maintenance cycle (gbrain dream) moves the fact into the page's Facts table, in its file.`
+ : `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. To give it a file, create the page; the next maintenance cycle (gbrain dream) can then move the facts saved for ${entitySlug} into the page's Facts table, in its file.`,
fix: {
argv: ['gbrain', 'put', entitySlug],
mcp: { tool: 'put_page', arguments: { slug: entitySlug, content: '<content>' } },
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index c58601aae5..84b2a0d523 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -16,7 +16,8 @@ import { OperationError, opError } from './contract.ts';
import type { AuthInfo, Operation, OperationContext } from './contract.ts';
import type { Action } from '../agent-output.ts';
import { hostFix, invalidParam, paramUse, readFix } from './op-fix.ts';
-import { CJK_SLUG_CHARS, SLUG_WORD_CHARS } from '../cjk.ts';
+import { CJK_SLUG_CHARS } from '../cjk.ts';
+import { isOpPageSlug, OP_PAGE_SLUG_RE } from '../page-slug-grammar.ts';
import { validateSlug } from '../utils.ts';
import { ALL_SOURCES, NO_SOURCES, isValidSourceId } from '../source-id.ts';
import { encodeDeepResearchId } from '../deep-research-id.ts';
@@ -187,29 +188,6 @@ export function validateUploadPath(filePath: string, root: string, strict = true
return real;
}
-/**
- * Op-boundary page-slug segment (#4665/#5032): cjk.ts's PAGE_SLUG_SEG shape
- * widened LOCALLY so `.` and `_` are allowed as part-CONTINUATION characters.
- * Colon separates individually valid parts inside a path segment, preserving
- * existing integration slugs such as `calendar:event-id` without admitting
- * empty or dot-led parts (`calendar:../x` remains invalid). The
- * sync slugifier deliberately preserves both (`notes/v1.0.0`,
- * `people/my_file_name` — see slugifySegment in src/core/sync.ts), so the
- * put_page boundary must round-trip every slug sync can produce. The lead
- * char stays a word char, so dot-LED segments remain impossible — `..`
- * traversal and every H5 rejection (backslash, %2e/%2f encodings, control
- * chars, RTL overrides, spaces) still fail. Deliberately NOT widened in
- * cjk.ts: cite-render, SlugRegistry's SLUG_RE, and the dream-cycle
- * SUMMARY_SLUG_RE consume the shared grammar with different semantics.
- * Compose with the `u` flag — see SLUG_WORD_CHARS.
- */
-// Underscore may also LEAD a segment: the sync slugifier preserves leading
-// underscores (`_index.md` → `_index`, the Hugo convention), so rejecting
-// them recreates the un-updatable-synced-page class this widen closes.
-// Dot stays continuation-only — `..` traversal remains impossible.
-const OP_PAGE_SLUG_PART = `[${SLUG_WORD_CHARS}_][${SLUG_WORD_CHARS}._\\-]*`;
-const OP_PAGE_SLUG_SEG = `${OP_PAGE_SLUG_PART}(?::${OP_PAGE_SLUG_PART})*`;
-const OP_PAGE_SLUG_RE = new RegExp(`^${OP_PAGE_SLUG_SEG}(\\/${OP_PAGE_SLUG_SEG})*$`, 'iu');
/**
* Allowlist validator for page slugs. Rejects URL-encoded traversal, backslashes,
@@ -233,10 +211,7 @@ export function validatePageSlug(slug: string): void {
}
}
-/** True when `slug` passes validatePageSlug's op-boundary grammar. */
-export function isOpPageSlug(slug: string): boolean {
- return typeof slug === 'string' && slug.length > 0 && slug.length <= 255 && OP_PAGE_SLUG_RE.test(slug);
-}
+export { isOpPageSlug };
/**
* #6212: a slug an older gbrain stored that today's grammar refuses (a space,
diff --git a/src/core/page-slug-grammar.ts b/src/core/page-slug-grammar.ts
new file mode 100644
index 0000000000..e1650bee3a
--- /dev/null
+++ b/src/core/page-slug-grammar.ts
@@ -0,0 +1,30 @@
+import { SLUG_WORD_CHARS } from './cjk.ts';
+
+/**
+ * Op-boundary page-slug segment (#4665/#5032): cjk.ts's PAGE_SLUG_SEG shape
+ * widened LOCALLY so `.` and `_` are allowed as part-CONTINUATION characters.
+ * Colon separates individually valid parts inside a path segment, preserving
+ * existing integration slugs such as `calendar:event-id` without admitting
+ * empty or dot-led parts (`calendar:../x` remains invalid). The
+ * sync slugifier deliberately preserves both (`notes/v1.0.0`,
+ * `people/my_file_name` — see slugifySegment in src/core/sync.ts), so the
+ * put_page boundary must round-trip every slug sync can produce. The lead
+ * char stays a word char, so dot-LED segments remain impossible — `..`
+ * traversal and every H5 rejection (backslash, %2e/%2f encodings, control
+ * chars, RTL overrides, spaces) still fail. Deliberately NOT widened in
+ * cjk.ts: cite-render, SlugRegistry's SLUG_RE, and the dream-cycle
+ * SUMMARY_SLUG_RE consume the shared grammar with different semantics.
+ * Compose with the `u` flag — see SLUG_WORD_CHARS.
+ */
+// Underscore may also LEAD a segment: the sync slugifier preserves leading
+// underscores (`_index.md` → `_index`, the Hugo convention), so rejecting
+// them recreates the un-updatable-synced-page class this widen closes.
+// Dot stays continuation-only — `..` traversal remains impossible.
+const OP_PAGE_SLUG_PART = `[${SLUG_WORD_CHARS}_][${SLUG_WORD_CHARS}._\\-]*`;
+const OP_PAGE_SLUG_SEG = `${OP_PAGE_SLUG_PART}(?::${OP_PAGE_SLUG_PART})*`;
+export const OP_PAGE_SLUG_RE = new RegExp(`^${OP_PAGE_SLUG_SEG}(\\/${OP_PAGE_SLUG_SEG})*$`, 'iu');
+
+/** True when `slug` passes validatePageSlug's op-boundary grammar. */
+export function isOpPageSlug(slug: string): boolean {
+ return typeof slug === 'string' && slug.length > 0 && slug.length <= 255 && OP_PAGE_SLUG_RE.test(slug);
+}
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index bb6fc79b85..a0a17e2ca4 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -8,7 +8,7 @@ import { hasScope } from '../scope.ts';
import { normalizeTokenScopes } from '../legacy-token-scope.ts';
import { authSourcesFromGrant, grantFromTokenRow, tokenGrantRowSelect, type TokenGrantRow } from '../grants/model.ts';
import { readLocalWriter, currentVerifiedLocalWriter, takeRegisteredWriterRow, verifyLocalWriter, type LocalGrant } from './identity.ts';
-import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model.ts';
+import { authorizedSlug, type Principal, type SqlEngine, type WriteAuthority, type WriteRequest } from './model.ts';
import { authorizePageVisibility, excludesPrivateWritesAtAdmission } from './page-visibility.ts';
import { currentCallerAccess } from '../search/private-visibility.ts';
import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';
@@ -148,7 +148,8 @@ export async function slugDisclosable(engine: SqlEngine, a: WriteAuthority, slug
return authorizePageVisibility(engine, a, slug).then(() => true, () => false);
}
/** Caller holds source guards first. FOR SHARE serializes publication against revocation. */
-export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operation: string, slug: string, lock = false): Promise<void> {
+export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operation: string, page: string, lock = false): Promise<void> {
+ const slug = authorizedSlug(a, page);
if (a.version !== 1 || !a.principal || !a.sourceId || !a.sourceIncarnation) deny('Missing durable write authority.');
assertSkillWriteScopes(a.scopes, operation, a.remote);
// GST-359: an attested write is granted by the public operation the person's system called (memory_write runs remember).
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index e496787204..065f8ab8f3 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -619,7 +619,7 @@ export async function reprojectTimelineRow(tx: BrainEngine, pageId: number, body
}
export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string, factDate: Date | null = null) {
- const scan=scanCanonicalFences(page);
+ const scan=scanCanonicalFences({ ...page, slug });
if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);
const fields:Array<[FenceSection,string]>=[['body',page.compiled_truth],['timeline',page.timeline ?? '']];
return { factRows: extractFactsFromFenceText(scan.facts,slug,sourceId,{ pageEffectiveDate: factDate }), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 5cba61dbb4..cbb5db5221 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -428,7 +428,8 @@ export function decoratePublicationOutcome(row: WriteRequest, prepared: Prepared
final: { revision: string } | null, fileCount: number, skill: boolean): void {
if (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 } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };
+ 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' };
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/forget-prepare.ts b/src/core/persistence/forget-prepare.ts
index 6b7b0de570..d942fc0bf1 100644
--- a/src/core/persistence/forget-prepare.ts
+++ b/src/core/persistence/forget-prepare.ts
@@ -29,6 +29,8 @@ import { pageIdentityError } from './page-identity.ts';
import { MEMBER_PAGE_PREFIX } from '../access/member-facts.ts';
import type { CompanionPage, PageMutationFile, PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';
+import { prepareFenceRowRetirement } from '../facts/fence-fact-append.ts';
interface ForgetTarget { id: number; entity_slug: string | null; trust_tier?: string | null }
@@ -75,7 +77,7 @@ export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId:
* the page names the member among its readers; the coordinator checks the page's visibility to the stored writer.
*/
export async function readForgetTarget(engine: BrainEngine, id: number, sourceId: string, remote: boolean, excludePrivate: boolean, lock = false, ownPage: string | null = null) {
- const [fact] = await engine.executeRaw<ForgetTarget & { source_markdown_slug: string | null; expired_at: Date | null }>(`SELECT id,entity_slug,source_markdown_slug,expired_at,trust_tier FROM facts
+ const [fact] = await engine.executeRaw<ForgetTarget & { source_markdown_slug: string | null; row_num: number | null; expired_at: Date | null }>(`SELECT id,entity_slug,source_markdown_slug,row_num,expired_at,trust_tier FROM facts
WHERE id=$1 AND source_id=$2 AND ${ownPage ? `visibility='private' AND source_markdown_slug=$3 AND EXISTS (SELECT 1 FROM pages member_page
WHERE member_page.source_id=facts.source_id AND member_page.slug=$3 AND member_page.deleted_at IS NULL AND member_page.page_readers && ARRAY[$4::text])`
: `($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`}${lock ? ' FOR UPDATE' : ''}`,
@@ -127,7 +129,13 @@ 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.');
- const file = await strike(row.slug, own);
+ // GBRA-449: a fact held on memory/unattributed 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
+ && plan.subject !== '*' && own && !own.page.deleted_at && !isSegmentedPage(own.page) && 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;
+ const file = held ? held.file : await strike(row.slug, own);
const companions: CompanionPage[] = [];
for (const slug of plan.slugs) {
if (slug === row.slug) continue;
@@ -138,7 +146,7 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque
...(companionFile ? { file: companionFile } : {}), apply: async () => undefined });
}
let pages: string[] = [];
- return { observedRevision: own?.revision ?? null, ...(file ? { file } : {}), ...(companions.length ? { companions } : {}),
+ return { observedRevision: held ? held.observedRevision : own?.revision ?? null, ...(file ? { file } : {}), ...(companions.length ? { companions } : {}),
// #8636: forget_fact on an already-expired fact still publishes its withdrawal, then answers fact_already_expired.
...(row.operation === 'forget_fact' && fact.expired_at !== null ? { failure: { code: 'fact_already_expired', message: `Fact id ${id} already expired.` } } : {}),
validate: async tx => {
@@ -147,8 +155,10 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque
if (!current) throw missing();
if (remote && supersessionGuarded('agent_written', current.trust_tier)) throw remoteForgetRaced(id);
if (!ownPage) await refuseForgetReachingOtherCopies(tx, sourceId, current, remote, excludePrivate);
+ await held?.validate?.(tx);
},
- apply: async tx => {
+ apply: async (tx, preimage) => {
+ if (held) await held.apply(tx, preimage ?? null);
// Even an expired legacy fact acquires a ledger row (forget_fact then finishes failed), so a stale import cannot reactivate it.
const publication = { withdrawnAt, expectedSlugs: plan.slugs };
pages = (await recordFactWithdrawal(tx, id, sourceId, remote, ownPage
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index c478830f21..b0f5f339c3 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -117,15 +117,25 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
const writeThrough = configuredWriteThrough && !sandbox;
if (sandbox) authority.databaseOnlyReason = 'subagent_sandbox';
else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';
+ // GBRA-449: 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.
+ const holding = !inferred && memberPage === null && entitySlug !== null && !snapshot && writeThrough
+ && (await getWorktreeBinding(ctx.engine, sourceId))?.canonical_git === true
+ ? await ctx.engine.readPageSnapshot(UNATTRIBUTED_MEMORY_SLUG, { sourceId, includeDeleted: true }) ?? 'absent' : null;
+ const held = holding !== null && (holding === 'absent' || !holding.page.deleted_at);
+ const page = held && holding !== 'absent' ? holding : snapshot;
+ if (held) fence = true;
// An inferred link never designates an owner or reports a missing one.
const target = fence ? await resolveFactWriteTarget(ctx.engine, sourceId, source,
- { sandbox, fileBacked: snapshot ? Boolean(snapshot.page.source_path) : unattributed, remote: ctx.remote !== false }).catch((error: unknown) => {
+ { sandbox, fileBacked: page ? Boolean(page.page.source_path) : unattributed || held, remote: ctx.remote !== false }).catch((error: unknown) => {
if (inferred && error instanceof OperationError) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
- // A source that refuses a new canonical file keeps the subjectless fact database-only, as before memory/unattributed had a page.
- if (unattributed && !snapshot && error instanceof OperationError) return null;
+ // A source that refuses a new canonical file keeps the subjectless (or held) fact database-only, as before memory/unattributed had a page.
+ if ((unattributed || held) && !page && error instanceof OperationError) return null;
throw error;
}) : null;
- if (unattributed && !snapshot && !target) fence = false;
+ if ((unattributed || held) && !page && !target) fence = false;
+ if (held && fence) authority.heldFor = entitySlug!;
// GST-2446: a named entity with no page keeps its fact out of every file. Where the source has a checkout the reason
// is the missing page, never a missing repository.
if (!fence && entitySlug !== null && writeThrough) {
@@ -151,7 +161,8 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
throw new InferredTargetRejected('ENTITY_LINK_FAILED');
}
}
- return { slug, authority, snapshot, fence, binding, writeThrough };
+ return held && fence ? { slug: UNATTRIBUTED_MEMORY_SLUG, authority, snapshot: page, fence, binding, writeThrough, heldFor: entitySlug }
+ : { slug, authority, snapshot, fence, binding, writeThrough, heldFor: null };
}
/** The caller's remember parameters and whether it named a visibility (the verb fills the v1 default otherwise). */
@@ -260,9 +271,12 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
* GST-2243: every remember reply names the page the fact went to and who can recall it. GST-2446: a fact saved for an
* entity with no page is on no page, so the reply names none; where the source's pages are in Git, one notice gives
* the call that creates the page (a brain with no repository keeps the database as its record and is told nothing).
+ * GBRA-449: on a strict git-canonical source the fact is held on memory/unattributed instead (`authority.heldFor`), so
+ * the reply names that page and the notice says it is committed and when it moves.
*/
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 ((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
@@ -378,7 +392,9 @@ 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, remote, ownPage ? undefined : excludePrivate, ownPage);
- const struck = plan ? plan.slugs.filter(page => plan.subject === '*' || plan.subject === page) : [];
+ // GBRA-449: 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;
+ 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;
const target = await resolveFactWriteTarget(ctx.engine, sourceId, source, { sandbox, fileBacked, remote })
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.ts
index 96ff51b9b9..f97eb584d7 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -1,5 +1,6 @@
import type { BrainEngine } from '../engine.ts';
import { assertRecoveryVersion } from './recovery-version.ts';
+import { UNATTRIBUTED_MEMORY_SLUG } 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. */
@@ -31,6 +32,12 @@ export interface WriteAuthority {
attestedOp?: string;
/** GST-1113: the scope source an attested memory_write named instead of the principal's own; publication re-checks attest_sources. */
attestedSource?: string;
+ /**
+ * GBRA-449: the entity a remember held on memory/unattributed is for (a strict source, the entity has no page). The
+ * write is authorized as a write to that entity (its slug fences, grant prefixes and visibility), never to the
+ * holding page, which is gbrain's own companion to it.
+ */
+ heldFor?: string;
databaseOnlyReason?: 'subagent_sandbox' | 'disabled_by_config' | 'no_repo_configured' | 'connector_database' | 'unbound_source' | 'overwrite_restore' | 'detached' | 'entity_page_missing';
autoLinkTrusted?: boolean;
restrictedNamespace?: boolean;
@@ -47,6 +54,11 @@ export interface WriteAuthority {
/** Actual holders touched by a published take mutation; retained after intent compaction. */
takeHoldersUsed?: string[];
}
+/** GBRA-449: 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;
+}
+
/**
* One file's publication recovery. The prior bytes are embedded (`before`, base64), except for a prior file over the
* single-string ceiling (large-file.ts): `before` is null and the bytes are the staged copy `staging.before` (path,
diff --git a/src/core/persistence/page-identity.ts b/src/core/persistence/page-identity.ts
index 26a412ee16..bf05aa1ead 100644
--- a/src/core/persistence/page-identity.ts
+++ b/src/core/persistence/page-identity.ts
@@ -41,12 +41,12 @@ export function yamlLocator(text: string | null | undefined): string {
/**
* GST-359 C2: a member page (GST-1113: or scope page) another write created after this remember was accepted is the same page, not a recreation;
- * so is memory/unattributed, which the first subjectless remember creates (concurrent first saves all land on it).
- * Preparation and the coordinator's publication check share it.
+ * so is memory/unattributed, which the first subjectless (or, GBRA-449, held) remember creates (concurrent first saves
+ * all land on it). Preparation and the coordinator's publication check share it.
*/
-export function rememberAcceptsPageCreatedSince(row: Pick<WriteRequest, 'operation' | 'slug' | 'page_id' | 'intent'>,
+export function rememberAcceptsPageCreatedSince(row: Pick<WriteRequest, 'operation' | 'slug' | 'page_id' | 'intent' | 'authority'>,
snapshot: { 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));
+ && (p.member_page === true || p.scope_page === true || (row.slug === UNATTRIBUTED_MEMORY_SLUG && (p.entity_slug == null || row.authority.heldFor === p.entity_slug)));
}
diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.ts
index 066caa1942..e04873559a 100644
--- a/src/core/persistence/page-visibility.ts
+++ b/src/core/persistence/page-visibility.ts
@@ -6,7 +6,7 @@ import type { AudiencePrincipal } from '../access/audience.ts';
import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';
import { ACCESS_ID_RE, hasReaders, normalizePrincipal, normalizeReaders, readersAllow, NOBODY } from '../access/principals.ts';
import { catalogueError } from '../error-catalogue.ts';
-import type { SqlEngine, WriteAuthority } from './model.ts';
+import { authorizedSlug, type SqlEngine, type WriteAuthority } from './model.ts';
import type { BrainEngine } from '../engine.ts';
import { noGrantFloorReads } from '../source-resolver.ts';
@@ -31,8 +31,9 @@ export async function excludesPrivateWritesAtAdmission(engine: SqlEngine, remote
* member disabled or unbound after submission (a queued job, a replay) loses the page before commit, and the
* member-access part applies even when an operator relaxed privacy.
*/
-export async function authorizePageVisibility(engine: SqlEngine, authority: WriteAuthority, slug: string): Promise<void> {
+export async function authorizePageVisibility(engine: SqlEngine, authority: WriteAuthority, page: string): Promise<void> {
if (!authority.remote) return;
+ const slug = authorizedSlug(authority, page);
if (authority.excludePrivate ?? true) {
// Privacy is hidden whatever the policy says, and an empty identity is the strictest reading (an identity only
// opens a page that names readers or sits under a folder rule), so a page visible with none needs no policy read
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index f55fd99edc..1dfaf8893b 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -10,7 +10,9 @@ 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, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';
+import { fenceCellReadBackProblem, formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, 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';
import { submissionAuthority, authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { currentVerifiedLocalWriter, hostIdFor, registerLocalWriter } from './identity.ts';
@@ -424,6 +426,11 @@ const MALFORMED_ADOPTION = 'A fact adoption assigns one fact or fence position t
* read-back check changes, and every held-back page gets a fresh attempt.
*/
export const FACT_FENCE_PLANNER = 2;
+/**
+ * GBRA-449: the same publication moves facts held on memory/unattributed (a strict source's facts for an entity that had
+ * no page) into their entity page's fence: the rows keep their ids and move in place, and their holding rows are struck.
+ */
+export const HELD_FACT_MOVE = 'managed_maintenance_move_held_fact';
/** How long a refused adoption is held back; the owner that refused it may since have restarted onto code that adopts it. */
const ADOPTION_REFUSAL_HOLD_MS = 24 * 60 * 60 * 1000;
@@ -446,11 +453,11 @@ 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 }> }): Promise<FactFenceAdoptionPlan> {
+ options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }>; move?: { note: 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: 'managed_maintenance_adopt_fact_fence', expected_revision: options.expectedRevision,
- source_incarnation: authority.writer.sourceIncarnation, content: options.content, facts, planner: FACT_FENCE_PLANNER };
+ 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 } : {}) };
for (let attempt = 0; ; attempt++) {
const requestId = maintenanceRequestId({ authority: authority.writer, slug, intent, ...(attempt ? { attempt } : {}) });
const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
@@ -491,6 +498,7 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
const engine = boundedReads(unbounded, clock);
const p = row.intent!;
const facts = p.facts as FactFenceAssignment[];
+ const held = p.kind === HELD_FACT_MOVE;
if (p.source_incarnation !== row.source_incarnation) throw opError('source_changed', 'The fact adoption source changed.',
`Source ${row.source_id} was replaced after fact-fence adoption request ${row.request_id} for ${row.slug} was accepted, so nothing was published. Read the receipt with gbrain write-request -- ${row.request_id}; the next fact backfill run plans against the current source.`,
{ fix: receiptFix(row) });
@@ -507,8 +515,8 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
const current = await readFacts(db, row.source_id, facts.map(f => f.id), lock);
for (const assignment of facts) {
const fact = current.find(f => f.id === assignment.id);
- if (!fact || digest(fact.value) !== assignment.hash || fact.value.entity_slug !== row.slug
- || fact.value.row_num !== null || fact.value.expired_at !== null) {
+ if (!fact || digest(fact.value) !== assignment.hash || fact.value.entity_slug !== row.slug || fact.value.expired_at !== null
+ || (held ? fact.value.source_markdown_slug !== UNATTRIBUTED_MEMORY_SLUG || 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) });
@@ -531,9 +539,11 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
{ fix: receiptFix(row) });
};
await check(engine, false);
- const prepared = await preparePageMutation(unbounded, { ...row, intent: { kind: 'managed_maintenance_page', content: p.content,
- expected_revision: p.expected_revision } }, config, undefined, undefined, { clock });
- return { ...prepared, validate: async tx => { await prepared.validate?.(tx); await check(tx, true); }, apply: async tx => {
+ 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), dropEntity: 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
// projection's expiry pass and insertFacts see the adopted positions.
// The fence cell's parsed text is written back with the row number: the
@@ -541,11 +551,12 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
// 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
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 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 })))]);
+ 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] : [])]);
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) });
const outcome = await prepared.apply(tx);
return { ...outcome, facts_adopted: facts.length };
} };
@@ -619,7 +630,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, co
return { ...outcome, event_projected: projected };
} };
}
- if (row.intent?.kind === 'managed_maintenance_adopt_fact_fence') return prepareFactFenceAdoption(engine, row, config, clock);
+ if (row.intent?.kind === 'managed_maintenance_adopt_fact_fence' || row.intent?.kind === HELD_FACT_MOVE) return prepareFactFenceAdoption(engine, row, config, clock);
if (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_chronicle_event' || row.intent?.kind === 'managed_maintenance_chronicle_retire') {
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 80c2f908a4..37e605f450 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -6,7 +6,7 @@ import type { GBrainConfig } from '../config.ts';
import { importFromContent, type ParsedPage } from '../import-file.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { alignWithStored } from './align-stored.ts';
-import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, restoreHiddenFactRows, type ParsedFact } from '../facts-fence.ts';
+import { parseFactsFenceFor, renderFactsTable, replaceOrInsertFactsFence, restoreHiddenFactRows, type ParsedFact } from '../facts-fence.ts';
import { opError } from '../ops/contract.ts';
import { privateRequestRefusal } from './visibility-request.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
@@ -77,7 +77,7 @@ export function privateFactViolation(next: readonly ParsedFact[], prior: readonl
}
function preservePrivateFacts(incoming: string, stored: string, section: string, sourceId: string, slug: string): string {
- const next = parseFactsFence(incoming), prior = parseFactsFence(stored);
+ const next = parseFactsFenceFor(incoming, { slug }), prior = parseFactsFenceFor(stored, { slug });
if (next.warnings.length || prior.warnings.length) throw opError('invalid_params', 'Fact fences must parse losslessly before reconciliation.',
'The ## Facts table of the file or of the stored page has rows that do not parse cleanly, so reconciliation cannot prove its private facts are kept; nothing was written. Repair the malformed rows in the file, then generate a fresh preview and apply it.');
const row = privateFactViolation(next.facts, prior.facts);
diff --git a/src/core/remote-body.ts b/src/core/remote-body.ts
index 10d54a57d7..e8f935ee36 100644
--- a/src/core/remote-body.ts
+++ b/src/core/remote-body.ts
@@ -1,4 +1,4 @@
-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable } from './facts-fence.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFenceFor, renderFactsTable } from './facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from './takes-fence.ts';
import { sanitizeText } from './batch-rows.ts';
import { stripMaterializedMarkers } from './timeline-marker.ts';
@@ -37,7 +37,7 @@ export function sanitizeRemoteBody(body: string, opts: { includeWithdrawn?: bool
/** What sanitizeRemoteBody puts in place of one protected facts region: its world rows rendered, or nothing. */
export function renderFactsRegion(region: string, includeWithdrawn = false): string {
try {
- const parsed = parseFactsFence(region);
+ const parsed = parseFactsFenceFor(region, { reader: true });
if (parsed.warnings.length === 0) return renderFactsTable(parsed.facts.filter(row => row.visibility === 'world' && (includeWithdrawn || !row.forgotten)));
} catch {
// A protected block that cannot be parsed is omitted, never echoed.
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index ddc5b580f1..0ec67a8e4c 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -508,6 +508,7 @@ test/remediation-manual-only.test.ts
test/remember-batch-entity-7432.test.ts
test/remember-pageless-entity-gst2446.test.ts
test/remember-share-gst2243.test.ts
+test/remember-strict-held-gbra449.test.ts
test/repair-apply-pending-6543.test.ts
test/repair-atom-fence-rows.test.ts
test/repair-database-stop-gbra133.test.ts
diff --git a/test/remember-strict-held-gbra449.test.ts b/test/remember-strict-held-gbra449.test.ts
new file mode 100644
index 0000000000..e4f7870a16
--- /dev/null
+++ b/test/remember-strict-held-gbra449.test.ts
@@ -0,0 +1,286 @@
+/**
+ * GBRA-449 (GST-2492): `remember` for an entity with no page, on a strict git-canonical source.
+ *
+ * 1. Protects: on a source whose pages are canonical in Git, a fact saved for an entity that has no page is written to
+ * Git before its database row, as a row of memory/unattributed whose `entity` cell names the entity. The reply,
+ * batch item and receipt say where it is (`page: memory/unattributed`, `write_through.held_for`). A rebuild from a
+ * clone of HEAD brings the fact back for its entity. Once the entity has a page, the extract_facts phase moves the
+ * row into that page in one commit and strikes the holding row; forget and supersede strike the held row.
+ * 2. Fails when: a strict source keeps such a fact in the database alone (a rebuild loses it), a rebuild brings back a
+ * forgotten or superseded held fact, a move duplicates or loses the fact, or a private entity page is named on the
+ * world-readable holding page.
+ * 3. Existing coverage: test/remember-pageless-entity-gst2446.test.ts pins the non-strict and repo-less answers.
+ * 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 as a remote and a prefix-bound caller, and a rebuild
+ * of a fresh database from a clone of HEAD through sync and the facts step.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { 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 { OperationContext } from '../src/core/ops/contract.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+import { operationsByName, type AuthInfo } from '../src/core/operations.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import * as fence from '../src/core/facts-fence.ts';
+import { scanCanonicalFences } from '../src/core/fence-repair/refusal.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.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 HOLD_FILE = `${HOLD}.md`;
+const PAGED = 'people/hana-example';
+const PAGELESS = 'notes/kitchen-remodel';
+const page = (title: string, extra = '') => `---\ntype: note\ntitle: ${title}\n${extra}---\n\nNotes about ${title}.\n`;
+const gitRepo = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };
+const STDIO = { remote: true, transport: 'stdio', sourceId: 'default' } as const;
+
+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, extra: Record<string, unknown> = {}) =>
+ call(ctx, 'remember', { fact, entity, provenance: 'chat 2026-11-11', ...extra });
+const putPage = (ctx: OperationContext, slug: string, title: string, extra = '') => call(ctx, 'put_page', { slug, content: page(title, extra) });
+const head = (root: string, file: string) => { try { return git(root, 'show', `HEAD:${file}`); } catch { return ''; } };
+const lineOf = (text: string, claim: string) => text.split('\n').find(line => line.includes(claim)) ?? '';
+const factRows = (engine: BrainEngine, claim: string) => engine.executeRaw<{ id: number; entity_slug: string | null; source_markdown_slug: string | null; row_num: number | null; active: boolean; source: string }>(
+ `SELECT id::int AS id, entity_slug, source_markdown_slug, row_num, (expired_at IS NULL) AS active, source FROM facts WHERE source_id='default' AND fact = $1 ORDER BY id`, [claim]);
+async function overMcp(engine: BrainEngine, params: Record<string, unknown>, auth?: AuthInfo) {
+ const out = await dispatchToolCall(engine, 'remember', { provenance: 'chat 2026-11-11', request_id: randomUUID(), ...params }, { ...STDIO, ...(auth ? { auth } : {}) });
+ return { body: JSON.parse(out.content[0]!.text) as Record<string, any>, blocks: out.content.slice(1).map(block => block.text), isError: out.isError === true };
+}
+
+/** A fresh database indexed from a clone of HEAD, with the facts step run, as a rebuild would: the rows of each claim. */
+async function rebuild(root: string, databaseUrl: string | undefined, claims: string[]) {
+ const home = mkdtempSync(join(tmpdir(), 'gbra449-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; active: boolean }>> = {};
+ for (const claim of claims) out[claim] = (await factRows(fresh.engine, claim)).map(({ entity_slug, source_markdown_slug, active }) => ({ entity_slug, source_markdown_slug, active }));
+ return out;
+ } finally { await fresh.close(); }
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+for (const backend of testBackends()) describe(`[${backend}] a strict source holds a pageless fact in Git (GBRA-449)`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ afterEach(() => installFaultHook(undefined));
+ const strict = (run: (brain: ManagedBrain) => Promise<void>) => managedBrain(async brain => {
+ await brain.engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);
+ await putPage(brain.ctx, PAGED, 'Hana Example');
+ await run(brain);
+ }, { databaseUrl, setup: gitRepo });
+
+ test('the fact is in Git before the reply, and the reply, batch, receipt and MCP say where', () => strict(async ({ engine, ctx, root }) => {
+ const notices: Notice[] = [];
+ const local = { ...ctx, emitNotice: (n: Notice | null | undefined) => { if (n) notices.push(n); } } as OperationContext;
+ const claim = 'The kitchen remodel starts in March.';
+ const single = await remember(local, claim, PAGELESS);
+ expect(single).toMatchObject({ status: 'inserted', entity_slug: PAGELESS, page: HOLD, persistence: { mode: 'filesystem' },
+ write_through: { written: true, held_for: PAGELESS } });
+ // Committed through the door before the row: HEAD has it with no Git effect settled.
+ expect(lineOf(head(root, HOLD_FILE), claim)).toContain(PAGELESS);
+ const [notice] = notices.filter(n => n.code === 'entity_page_missing');
+ expect(notice!.why).toContain(`held on ${HOLD} until ${PAGELESS} has a page`);
+ expect(notice!.why).toContain('committed to Git');
+ const receipt = await call(ctx, 'get_write_request', { request_id: single.request_id });
+ expect(receipt.outcome.write_through).toEqual({ written: true, held_for: PAGELESS });
+ expect(await factRows(engine, claim)).toMatchObject([{ entity_slug: PAGELESS, source_markdown_slug: HOLD, active: true }]);
+
+ const budget = 'The remodel budget is 40,000 USD.';
+ const { items } = await call(ctx, 'remember', { provenance: 'chat 2026-11-11', items: [
+ { fact: 'Hana Example cycles to work.', entity: PAGED }, { fact: budget, entity: PAGELESS }] });
+ expect(items[0]).toMatchObject({ page: PAGED, write_through: { written: true } });
+ expect(items[0].write_through).not.toHaveProperty('held_for');
+ expect(items[1]).toMatchObject({ status: 'inserted', page: HOLD, persistence: { mode: 'filesystem' }, write_through: { written: true, held_for: PAGELESS } });
+ expect(lineOf(head(root, HOLD_FILE), budget)).toContain(PAGELESS);
+
+ // MCP shows a notice once per entity per session, so this entity is new.
+ const garden = `notes/garden-plan-${randomUUID().slice(0, 8)}`;
+ const contractor = 'The garden plan adds two raised beds.';
+ const mcp = await overMcp(engine, { fact: contractor, entity: garden });
+ expect(mcp.isError).toBe(false);
+ expect(mcp.body).toMatchObject({ status: 'inserted', page: HOLD, write_through: { written: true, held_for: garden } });
+ expect(mcp.blocks.join('\n')).toContain(`held on ${HOLD}`);
+ expect(lineOf(head(root, HOLD_FILE), contractor)).toContain(garden);
+
+ const rebuilt = await rebuild(root, databaseUrl, [claim, budget, contractor]);
+ for (const text of [claim, budget]) expect(rebuilt[text]).toEqual([{ entity_slug: PAGELESS, source_markdown_slug: HOLD, active: true }]);
+ expect(rebuilt[contractor]).toEqual([{ entity_slug: garden, source_markdown_slug: HOLD, active: true }]);
+ }), 240_000);
+
+ test('a second save of the same fact for the entity is a duplicate of the held one', () => strict(async ({ engine, ctx, root }) => {
+ const claim = 'The kitchen remodel starts in March.';
+ const first = await remember(ctx, claim, PAGELESS);
+ const second = await remember(ctx, claim, PAGELESS);
+ expect(second).toMatchObject({ status: 'duplicate', id: first.id });
+ expect(await factRows(engine, claim)).toHaveLength(1);
+ expect(head(root, HOLD_FILE).split('\n').filter(line => line.includes(claim))).toHaveLength(1);
+ }), 180_000);
+
+ test('once the page exists, maintenance moves the fact into it in one commit and strikes the holding row', () => strict(async ({ engine, ctx, root }) => {
+ const claim = 'The kitchen remodel starts in March.';
+ const saved = await remember(ctx, claim, PAGELESS);
+ await putPage(ctx, PAGELESS, 'Kitchen remodel');
+ await settleManagedGitEffects(engine);
+ const before = git(root, 'rev-parse', 'HEAD').trim();
+ const result = await runExtractFacts(engine, { sourceId: 'default' });
+ expect(result.heldFactsMoved).toBe(1);
+ expect(result.warnings.filter(w => w.startsWith('HELD_FACT_UNMOVABLE'))).toEqual([]);
+ await settleManagedGitEffects(engine);
+ // One commit carries both files.
+ const changed = git(root, 'diff', '--name-only', before, 'HEAD').trim().split('\n').sort();
+ expect(changed).toEqual([HOLD_FILE, `${PAGELESS}.md`]);
+ expect(git(root, 'rev-list', '--count', `${before}..HEAD`).trim()).toBe('1');
+ expect(lineOf(head(root, `${PAGELESS}.md`), claim)).toContain(`| 1 | ${claim} |`);
+ expect(lineOf(head(root, HOLD_FILE), claim)).toContain(`~~${claim}~~`);
+ expect(lineOf(head(root, HOLD_FILE), claim)).toContain(`moved to ${PAGELESS}`);
+ // The row moved in place: same id and provenance. (The struck holding row projects as an expired row, as a rebuild has it.)
+ expect((await factRows(engine, claim)).filter(row => row.active)).toMatchObject([{ id: Number(saved.id), entity_slug: PAGELESS, source_markdown_slug: PAGELESS, row_num: 1, active: true, source: 'chat 2026-11-11' }]);
+ // Nothing left to move: a second run is a no-op.
+ expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved).toBeUndefined();
+ const rebuilt = await rebuild(root, databaseUrl, [claim]);
+ expect(rebuilt[claim]!.filter(row => row.active)).toEqual([{ entity_slug: PAGELESS, source_markdown_slug: PAGELESS, active: true }]);
+ }), 240_000);
+
+ test('a move interrupted after its door commit replays cleanly: the commit is kept and the fact moves once', () => strict(async ({ engine, ctx, root }) => {
+ const claim = 'The kitchen remodel starts in March.';
+ const saved = await remember(ctx, claim, PAGELESS);
+ await putPage(ctx, PAGELESS, 'Kitchen remodel');
+ await settleManagedGitEffects(engine);
+ let crash = '';
+ installFaultHook(async point => {
+ if (point === 'publication:before_commit' && !crash) {
+ crash = git(root, 'rev-parse', 'HEAD').trim();
+ throw Object.assign(new Error('database interruption CONNECTION_CLOSED'), { code: 'CONNECTION_CLOSED' });
+ }
+ });
+ expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved).toBe(1);
+ installFaultHook(undefined);
+ await settleManagedGitEffects(engine);
+ expect(crash).not.toBe('');
+ expect(git(root, 'log', '-1', '--format=%H', '--', `${PAGELESS}.md`).trim()).toBe(crash);
+ expect(git(root, 'show', '--name-only', '--format=', crash).trim().split('\n').sort()).toEqual([HOLD_FILE, `${PAGELESS}.md`]);
+ expect(head(root, `${PAGELESS}.md`).split('\n').filter(line => line.includes(claim))).toHaveLength(1);
+ expect((await factRows(engine, claim)).filter(row => row.active)).toMatchObject([{ id: Number(saved.id), source_markdown_slug: PAGELESS, row_num: 1 }]);
+ const rebuilt = await rebuild(root, databaseUrl, [claim]);
+ expect(rebuilt[claim]!.filter(row => row.active)).toEqual([{ entity_slug: PAGELESS, source_markdown_slug: PAGELESS, active: true }]);
+ }), 240_000);
+
+ test('a move into a restricted page strikes with a neutral note that does not name it', () => strict(async ({ engine, ctx, root }) => {
+ const secret = 'notes/surprise-party';
+ const claim = 'The surprise party is on Saturday.';
+ await remember(ctx, claim, secret);
+ await putPage(ctx, secret, 'Surprise party', 'readable_by: [alice-example]\n');
+ expect((await runExtractFacts(engine, { sourceId: 'default' })).heldFactsMoved).toBe(1);
+ await settleManagedGitEffects(engine);
+ const held = lineOf(head(root, HOLD_FILE), claim);
+ expect(held).toContain(`~~${claim}~~`);
+ expect(held).toContain('moved');
+ expect(held).not.toContain(secret);
+ expect(lineOf(head(root, `${secret}.md`), claim)).toContain(claim);
+ }), 240_000);
+
+ test('a page kept out of Git does not take the fact: it stays held in Git and the run says why', () => strict(async ({ engine, ctx, root }) => {
+ const secret = 'notes/surprise-party';
+ const claim = 'The surprise party is on Saturday.';
+ await remember(ctx, claim, secret);
+ await putPage(ctx, secret, 'Surprise party', 'visibility: private\n');
+ const result = await runExtractFacts(engine, { sourceId: 'default' });
+ expect(result.heldFactsMoved).toBeUndefined();
+ expect(result.warnings.filter(w => w.startsWith('HELD_FACT_UNMOVABLE'))).toEqual([expect.stringContaining(`${secret} facts `)]);
+ expect(result.warnings.join('\n')).toContain('entity_page_database_only');
+ expect(lineOf(head(root, HOLD_FILE), claim)).not.toContain('~~');
+ expect((await factRows(engine, claim)).filter(row => row.active)).toMatchObject([{ entity_slug: secret, source_markdown_slug: HOLD }]);
+ }), 240_000);
+
+ test('forget strikes the held row, so a rebuild does not bring the fact back', () => strict(async ({ engine, ctx, root }) => {
+ const claim = 'The kitchen remodel starts in March.';
+ const other = 'The garden plan adds two raised beds.';
+ const saved = await remember(ctx, claim, PAGELESS);
+ await remember(ctx, other, 'notes/garden-plan');
+ const forgot = await call(ctx, 'forget', { id: String(saved.id) });
+ expect(forgot.error).toBeUndefined();
+ await settleManagedGitEffects(engine);
+ expect(lineOf(head(root, HOLD_FILE), claim)).toContain(`~~${claim}~~`);
+ expect(await factRows(engine, claim)).toMatchObject([{ active: false }]);
+ const rebuilt = await rebuild(root, databaseUrl, [claim, other]);
+ expect(rebuilt[claim]!.filter(row => row.active)).toEqual([]);
+ expect(rebuilt[other]).toEqual([{ entity_slug: 'notes/garden-plan', source_markdown_slug: HOLD, active: true }]);
+ }), 240_000);
+
+ test('supersede: held by held, and held by an entity page row before the move, each survive a rebuild', () => strict(async ({ engine, ctx, root }) => {
+ const a = 'The kitchen remodel starts in March.';
+ const b = 'The kitchen remodel starts in April.';
+ const first = await remember(ctx, a, PAGELESS);
+ expect(await remember(ctx, b, PAGELESS, { replaces: String(first.id) })).toMatchObject({ status: 'superseded', page: HOLD });
+ const c = 'The pond plan needs a liner.';
+ const d = 'The pond plan needs a pump.';
+ const pond = 'notes/pond-plan';
+ const third = await remember(ctx, c, pond);
+ await putPage(ctx, pond, 'Pond plan');
+ expect(await remember(ctx, d, pond, { replaces: String(third.id) })).toMatchObject({ status: 'superseded', page: pond });
+ await settleManagedGitEffects(engine);
+ const rebuilt = await rebuild(root, databaseUrl, [a, b, c, d]);
+ expect(rebuilt[a]!.filter(row => row.active)).toEqual([]);
+ expect(rebuilt[b]).toEqual([{ entity_slug: PAGELESS, source_markdown_slug: HOLD, active: true }]);
+ expect(rebuilt[c]!.filter(row => row.active)).toEqual([]);
+ expect(rebuilt[d]).toEqual([{ entity_slug: pond, source_markdown_slug: pond, active: true }]);
+ }), 240_000);
+
+ test('a prefix-bound caller saves a held fact for an entity inside its prefix; with no entity it is refused as before', () => strict(async ({ engine, root }) => {
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,scope,source_id,bound_slug_prefixes)
+ VALUES ('bound-example','Synthetic bound client','read write','default',$1::text[])`, [['notes/']]);
+ const auth = { token: 't', clientId: 'bound-example', principal: { kind: 'oauth_client', id: 'bound-example' },
+ scopes: ['read', 'write'], sourceId: 'default', boundSlugPrefixes: ['notes/'] } as unknown as AuthInfo;
+ const claim = 'The kitchen remodel starts in March.';
+ const inside = await overMcp(engine, { fact: claim, entity: PAGELESS }, auth);
+ expect(inside.isError).toBe(false);
+ expect(inside.body).toMatchObject({ status: 'inserted', page: HOLD, write_through: { written: true, held_for: PAGELESS } });
+ expect(lineOf(head(root, HOLD_FILE), claim)).toContain(PAGELESS);
+ const outside = await overMcp(engine, { fact: 'Someone likes hiking.', entity: 'people/someone-example' }, auth);
+ expect(outside.body.error).toBe('scope_denied');
+ const none = await overMcp(engine, { fact: 'A stray thought.' }, auth);
+ expect(none.body.error).toBe('scope_denied');
+ expect(none.body.message).toContain(`slug '${HOLD}' is not under`);
+ }), 180_000);
+});
+
+describe('the entity column of the facts fence (GBRA-449)', () => {
+ const table = (entity: string) => [
+ '## Facts', '', '<!--- gbrain:facts:begin -->',
+ '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | entity |',
+ '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------|',
+ `| 1 | The remodel starts in March. | fact | 1.0 | world | medium | 2026-11-11 | | chat | | ${entity} |`,
+ '<!--- gbrain:facts:end -->', ''].join('\n');
+ test('memory/unattributed reads the entity; an invalid entity cell makes the fence malformed', () => {
+ const ok = fence.parseFactsFenceFor(table(PAGELESS), { slug: HOLD });
+ expect(ok.warnings).toEqual([]);
+ expect(ok.facts[0]).toMatchObject({ rowNum: 1, entity: PAGELESS });
+ for (const bad of ['Not A Slug!', HOLD]) {
+ const parsed = fence.parseFactsFenceFor(table(bad), { slug: HOLD });
+ expect(parsed.warnings.join('\n')).toContain('FACTS_TABLE_MALFORMED');
+ // The canonical scan import and sync run holds such a page as a fence defect.
+ expect(scanCanonicalFences({ compiled_truth: table(bad), timeline: '', slug: HOLD }).defects).toMatchObject([{ fence: 'facts' }]);
+ }
+ });
+ test('an entity header on any other page parses exactly as before', () => {
+ const body = table(PAGELESS);
+ expect(fence.parseFactsFenceFor(body, { slug: PAGED })).toEqual(fence.parseFactsFence(body));
+ expect(fence.parseFactsFenceFor(body, {})).toEqual(fence.parseFactsFence(body));
+ expect(fence.parseFactsFence(body).facts.some(f => 'entity' in f && f.entity !== undefined)).toBe(false);
+ expect(scanCanonicalFences({ compiled_truth: body, timeline: '', slug: PAGED })).toEqual(scanCanonicalFences({ compiled_truth: body, timeline: '' }));
+ });
+});