Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Keep held facts correct on large and restricted pages (GST-2492)
garrytan54ff361e1a30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9c0f497bd8..a5d9bf7f26 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,9 +27,9 @@ identifiers and attribution are available in the pre-removal Git revision**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.+- 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>`); when the page is restricted the held row is removed instead, so the world-readable holding page keeps nothing of it. 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.+- 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. An entity under a folder access rule is never held on the world-readable page: its fact stays in the database, as before.- 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.diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.mdindex d2b6c2966e..ba16a90db7 100644--- a/docs/architecture/key-files/core-persistence-facts.md+++ b/docs/architecture/key-files/core-persistence-facts.md@@ -21,6 +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). 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/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:`; `remove` takes the rows out instead of striking them).+- `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`; a move into a restricted page removes the holding rows instead of striking them.- `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/guides/entity-scoped-facts.md b/docs/guides/entity-scoped-facts.mdindex f2ab196f7e..87d5cbf63f 100644--- a/docs/guides/entity-scoped-facts.md+++ b/docs/guides/entity-scoped-facts.md@@ -117,9 +117,10 @@ 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 entityhas 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+and strikes the held row (`moved to <entity>`; a restricted page's held row is+removed instead); a page kept out of Git does not take it, and the run warns+`HELD_FACT_UNMOVABLE`. An entity under a folder access rule is not held: its+fact stays in the database, as on other sources. Forgetting or replacing a held fact strikes its rowtoo. A brain with no Gitrepository gets no notice: there the database is the record, and the fact isas safe as everything else in it.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 6dfb5680ae..6686fa49e1 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1536,7 +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: '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 (a restricted page\'s held row is removed); forget and replaces strike it too. An entity under a folder access rule is not held. 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/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.tsindex f950735fba..5238e2d858 100644--- a/src/core/facts/fence-fact-append.ts+++ b/src/core/facts/fence-fact-append.ts@@ -199,7 +199,7 @@ 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 | readonly number[]; note: string; validUntil: Date | null; forgotten?: boolean; dropEntity?: boolean }, signal?: AbortSignal): Promise<CompanionPage | null> {+ retire: { rowNum: number | readonly number[]; note: string; validUntil: Date | null; forgotten?: boolean; remove?: 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;@@ -213,9 +213,10 @@ export async function prepareFenceRowRetirement(engine: BrainEngine, row: WriteRconst until = retire.validUntil ? formatFenceDate(retire.validUntil) : undefined;const parsed = parseFactsFenceFor(fenced[section], { slug });refuseUnparsedRewrite(target.page, slug, row.source_id, () => assertFenceRewritable('facts', parsed));- // 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 } : {}) });+ // GBRA-449: a forgotten held row is struck as a withdrawal strikes a row (`forgotten: <note>`), so it reads back forgotten;+ // `remove` takes the rows out (a fact moved into a page not every reader can read leaves nothing on the holding page).+ const rows = parsed.facts.filter(f => !retire.remove || !retired.has(f.rowNum) || !f.active).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 } : {}) });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.tsindex 22350305dc..b228d327c2 100644--- a/src/core/facts/held-fact-move.ts+++ b/src/core/facts/held-fact-move.ts@@ -44,7 +44,7 @@ export async function moveHeldFacts(engine: BrainEngine, sourceId: string): Promif (!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.+ // A fact moved into a page not every reader of the source can read leaves the world-readable holding page altogether.const plan = await planManagedPage(engine, authority, sourceId, slug, group, { note: page.visible === true ? `moved to ${slug}` : 'moved' });if (plan.kind === 'no_page') continue;if (plan.kind === 'warnings') { unmovable(slug, group.map(r => r.id), `entity_fence_malformed: ${plan.warnings.join('; ')}`); continue; }diff --git a/src/core/fence-repair/census.ts b/src/core/fence-repair/census.tsindex da78af86a6..f6dae8f3d2 100644--- a/src/core/fence-repair/census.ts+++ b/src/core/fence-repair/census.ts@@ -126,7 +126,7 @@ const PAGE_COLUMNS = `id, slug, type, frontmatter, source_path, content_hash, upasync function judgePages(engine: Exec, source: CensusSource, rows: readonly PageRow[], at: string): Promise<void> {const clean: string[] = [];for (const row of rows) {- const page = row.live && row.compiled_truth !== null ? { compiled_truth: row.compiled_truth, timeline: row.timeline ?? '' } : null;+ const page = row.live && row.compiled_truth !== null ? { compiled_truth: row.compiled_truth, timeline: row.timeline ?? '', slug: row.slug } : null;const verdict = page && pageHasFenceText(page) ? judgeFences(page, screenFenceCtx({ type: row.type as never, frontmatter: row.frontmatter ?? {} })) : null;if (!verdict) { clean.push(row.slug); continue; }const finding: PageFinding = { ...verdict, sha256: sha256(`${page!.compiled_truth}\u0000${page!.timeline}`), checked_at: at,diff --git a/src/core/fence-repair/repair-io.ts b/src/core/fence-repair/repair-io.tsindex 97c4552b0f..dc4dea2090 100644--- a/src/core/fence-repair/repair-io.ts+++ b/src/core/fence-repair/repair-io.ts@@ -154,7 +154,7 @@ export async function readFenceTarget(engine: BrainEngine, src: FenceSource, canif (!dbOnly) {const parsed = parseMarkdown(content, cand.path, src.activePack ? { activePack: src.activePack } : undefined);return { ok: true, target: { mode: src.mirror ? 'mirror' : src.managed ? 'managed' : 'legacy', sourceId: src.id, key: cand.key, slug, path: cand.path, sourcePath,- page: { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '' }, content, before: sha256(bytes),+ page: { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '', slug }, content, before: sha256(bytes),snapshot: await engine.readPageSnapshot(slug, { sourceId: src.id, includeDeleted: true }), hold,ctx: screenFenceCtx({ ...parsed, folder_restricted: await folderRestricted(engine, src.id, slug) }, src.activePack) } };}@@ -163,7 +163,7 @@ export async function readFenceTarget(engine: BrainEngine, src: FenceSource, canconst slug = holdSlug;const snapshot = slug ? await engine.readPageSnapshot(slug, { sourceId: src.id }) : null;if (!snapshot || snapshot.page.deleted_at) return { ok: false, reason: 'gone' };- const page = { compiled_truth: snapshot.page.compiled_truth ?? '', timeline: snapshot.page.timeline ?? '' };+ const page = { compiled_truth: snapshot.page.compiled_truth ?? '', timeline: snapshot.page.timeline ?? '', slug: snapshot.page.slug };return { ok: true, target: { mode: src.mirror ? 'mirror' : 'db', sourceId: src.id, key: cand.key, slug: snapshot.page.slug, path: null,sourcePath: snapshot.page.source_path ?? null, page, content: null, before: pageSha(page), snapshot, hold,ctx: screenFenceCtx({ type: snapshot.page.type as never, frontmatter: (snapshot.page.frontmatter ?? {}) as Record<string, unknown>,diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.tsindex e793ada998..066bb04916 100644--- a/src/core/page-body/segment-facts.ts+++ b/src/core/page-body/segment-facts.ts@@ -35,7 +35,7 @@ import { open } from 'node:fs/promises';import type { BrainEngine } from '../engine.ts';import { indexOfOutsideCode } from '../fence-scan.ts';import {- FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, timelineHasGenuineFactsFenceMarker, type FactsFenceParseResult, type FactsFenceView,+ FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFenceFor, timelineHasGenuineFactsFenceMarker, type FactsFenceParseResult, type FactsFenceView,} from '../facts-fence.ts';import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';import { commitRuns, derivationScope, keyDigest, planRuns, readRuns, SegmentDerivationRaced, segmentDeriveWork, type DerivationScope, type DeriveRun } from './segment-derive.ts';@@ -108,7 +108,7 @@ export class FactsFenceScan {}result(): RegionFence {- return regionFenceOf(this.parsedText, this.fence !== null, this.endOnly, this.marker);+ return regionFenceOf(this.parsedText, this.fence !== null, this.endOnly, this.marker, this.page.slug);}/** What the blocks pushed so far hold, for a run's fences row. */@@ -120,9 +120,10 @@ export class FactsFenceScan {interface RegionFence { parsed: FactsFenceParseResult; holds: boolean; marker: boolean; text: string | null }-function regionFenceOf(parsedText: string | null, holds: boolean, endOnly: boolean, marker: boolean): RegionFence {+function regionFenceOf(parsedText: string | null, holds: boolean, endOnly: boolean, marker: boolean, slug: string | undefined): RegionFence {const reduced = parsedText ?? (holds ? FACTS_FENCE_BEGIN : endOnly ? `${'\n'.repeat(FACTS_FENCE_BEGIN.length)}${FACTS_FENCE_END}` : '');- return { parsed: parseFactsFence(reduced), holds, marker, text: parsedText };+ // GBRA-449: a segmented memory/unattributed reads its `entity` column as the inline page does.+ return { parsed: parseFactsFenceFor(reduced, { slug }), holds, marker, text: parsedText };}/** One region of the facts fence view, streamed, reading only the runs that can hold a fence marker. */@@ -235,7 +236,7 @@ export async function openFenceRuns(engine: BrainEngine, page: FencePage, scope:}/** A region's facts fence from its runs' summaries, in order; null when a fence does not close in the run it begins in. */-export function factsFromRuns(summaries: readonly FactsRunSummary[]): RegionFence | null {+export function factsFromRuns(summaries: readonly FactsRunSummary[], slug?: string): RegionFence | null {let endOnly = false, marker = false, parsedText: string | null = null;for (const summary of summaries) {marker ||= summary.marker;@@ -245,7 +246,7 @@ export function factsFromRuns(summaries: readonly FactsRunSummary[]): RegionFencparsedText = summary.fence.text;} else endOnly ||= summary.endOnly;}- return regionFenceOf(parsedText, parsedText !== null, endOnly, marker);+ return regionFenceOf(parsedText, parsedText !== null, endOnly, marker, slug);}/**@@ -264,7 +265,7 @@ export async function incrementalFactsFence(engine: BrainEngine, page: { id?: nuif (error instanceof SegmentDerivationRaced) return null;throw error;});- const region = (name: BodyRegion) => runs && factsFromRuns(runs.filter(({ run }) => run.region === name).map(({ output }) => output.facts));+ const region = (name: BodyRegion) => runs && factsFromRuns(runs.filter(({ run }) => run.region === name).map(({ output }) => output.facts), p.slug);const truth = region('truth');const timeline = region('timeline');if (!truth || !timeline) return segmentedFactsFence(engine, page);diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.tsindex d942fc0bf1..6b538f13a1 100644--- a/src/core/persistence/forget-prepare.ts+++ b/src/core/persistence/forget-prepare.ts@@ -132,7 +132,7 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque// 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+ && plan.subject !== '*' && own && !own.page.deleted_at && row.worktree_id? await prepareFenceRowRetirement(engine, row, _config, row.slug, { rowNum: Number(fact.row_num), note: 'memory withdrawn', validUntil: new Date(withdrawnAt), forgotten: true }, signal): null;const file = held ? held.file : await strike(row.slug, own);diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex b0f5f339c3..aaac0a83db 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -26,7 +26,7 @@ import type { WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';-import { callerIsOwner, currentCallerAccess, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';+import { callerIsOwner, currentCallerAccess, folderRestricted, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { projectionEligibleSql } from '../eligibility/sql.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';import { callerMember, factVisibilitySql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug, ownMemberFactIds, scopePageIsShared, scopePageNotShared, SCOPE_PAGE_SLUG } from '../access/member-facts.ts';@@ -120,10 +120,12 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc// 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.+ // An entity under a folder access rule is not named on the world-readable holding page, and a holding page kept out of+ // Git would not commit it: both keep the fact database-only, as before.const holding = !inferred && memberPage === null && entitySlug !== null && !snapshot && writeThrough- && (await getWorktreeBinding(ctx.engine, sourceId))?.canonical_git === true+ && (await getWorktreeBinding(ctx.engine, sourceId))?.canonical_git === true && !await folderRestricted(ctx.engine, sourceId, entitySlug)? await ctx.engine.readPageSnapshot(UNATTRIBUTED_MEMORY_SLUG, { sourceId, includeDeleted: true }) ?? 'absent' : null;- const held = holding !== null && (holding === 'absent' || !holding.page.deleted_at);+ const held = holding !== null && (holding === 'absent' || !holding.page.deleted_at && Boolean(holding.page.source_path));const page = held && holding !== 'absent' ? holding : snapshot;if (held) fence = true;// An inferred link never designates an owner or reports a missing one.diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 1dfaf8893b..2b3f57c925 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -541,7 +541,7 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteRequesawait check(engine, false);const pageRow = { ...row, intent: { kind: 'managed_maintenance_page', content: p.content, expected_revision: p.expected_revision } };const prepared = await preparePageMutation(unbounded, pageRow, config, undefined, undefined, { clock });- const holding = held ? await prepareFenceRowRetirement(unbounded, pageRow, config, UNATTRIBUTED_MEMORY_SLUG, { note: String(p.note), dropEntity: p.note === 'moved',+ const holding = held ? await prepareFenceRowRetirement(unbounded, pageRow, config, UNATTRIBUTED_MEMORY_SLUG, { note: String(p.note), remove: p.note === 'moved',rowNum: (await readFacts(engine, row.source_id, facts.map(f => f.id))).map(f => Number(f.value.row_num)), validUntil: null }) : null;return { ...prepared, ...(holding ? { companions: [holding] } : {}), validate: async tx => { await prepared.validate?.(tx); await check(tx, true); }, apply: async tx => {// Runs ahead of the page import and its canonical projection, so the@@ -630,7 +630,7 @@ async function prepareMaintenanceKind(engine: BrainEngine, row: WriteRequest, coreturn { ...outcome, event_projected: projected };} };}- 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_adopt_fact_fence' || row.intent?.kind === 'managed_maintenance_move_held_fact') 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/test/remember-strict-held-gbra449.test.ts b/test/remember-strict-held-gbra449.test.tsindex e4f7870a16..5b94c46389 100644--- a/test/remember-strict-held-gbra449.test.ts+++ b/test/remember-strict-held-gbra449.test.ts@@ -179,20 +179,56 @@ for (const backend of testBackends()) describe(`[${backend}] a strict source holexpect(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 }) => {+ test('a move into a restricted page leaves nothing of the fact on the holding page', () => 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(head(root, HOLD_FILE)).not.toContain(claim);+ expect(head(root, HOLD_FILE)).not.toContain(secret);expect(lineOf(head(root, `${secret}.md`), claim)).toContain(claim);+ const holding = await call(ctx, 'get_page', { slug: HOLD });+ expect(JSON.stringify(holding)).not.toContain(claim);+ const rebuilt = await rebuild(root, databaseUrl, [claim]);+ expect(rebuilt[claim]).toEqual([{ entity_slug: secret, source_markdown_slug: secret, active: true }]);}), 240_000);+ test('an entity under a folder access rule is not held on the world-readable page', () => strict(async ({ engine, ctx, root }) => {+ await engine.executeRaw(`INSERT INTO access_policy_state(source_id) VALUES('default') ON CONFLICT DO NOTHING`);+ await engine.executeRaw(`INSERT INTO access_rules(source_id,rule_id,prefix,readable_by,revision) VALUES('default','r1','secret/',ARRAY['member:alice-example'],1)`);+ const claim = 'The secret plan has a codename.';+ const saved = await remember(ctx, claim, 'secret/plan-x');+ expect(saved.write_through).not.toHaveProperty('held_for');+ expect(saved.persistence).toEqual({ mode: 'database' });+ expect(head(root, HOLD_FILE)).not.toContain(claim);+ }), 180_000);++ test('a segmented holding page reads its entity column: forget strikes the row and a rebuild keeps the rest', () => strict(async ({ engine, ctx, root }) => {+ const prose = Array.from({ length: 16000 }, (_, i) => `Line ${i} of a long note kept on the holding page so it is stored in segments.`).join('\n');+ await call(ctx, 'put_page', { slug: HOLD, content: `---\ntype: note\ntitle: Unattributed memory\n---\n\n${prose}\n` });+ const [shape] = await engine.executeRaw<{ segmented: boolean }>("SELECT compiled_truth IS NULL AS segmented FROM pages WHERE source_id='default' AND slug=$1", [HOLD]);+ expect(shape!.segmented).toBe(true);+ const loose = 'The spare key is with the neighbour.';+ const kept = 'The garden plan adds two raised beds.';+ const gone = 'The kitchen remodel starts in March.';+ await call(ctx, 'remember', { fact: loose, provenance: 'chat 2026-11-11', infer_entity: false });+ await remember(ctx, kept, 'notes/garden-plan');+ const saved = await remember(ctx, gone, PAGELESS);+ expect(saved.write_through).toEqual({ written: true, held_for: PAGELESS });+ const result = await runExtractFacts(engine, { sourceId: 'default' });+ expect(result.warnings.join('\n')).not.toContain('FACTS_TABLE_MALFORMED');+ const forgot = await call(ctx, 'forget', { id: String(saved.id) });+ expect(forgot.error).toBeUndefined();+ await settleManagedGitEffects(engine);+ expect(lineOf(head(root, HOLD_FILE), gone)).toContain(`~~${gone}~~`);+ const rebuilt = await rebuild(root, databaseUrl, [loose, kept, gone]);+ expect(rebuilt[loose]).toEqual([{ entity_slug: null, source_markdown_slug: HOLD, active: true }]);+ expect(rebuilt[kept]).toEqual([{ entity_slug: 'notes/garden-plan', source_markdown_slug: HOLD, active: true }]);+ expect(rebuilt[gone]!.filter(row => row.active)).toEqual([]);+ }), 300_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.';