Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Refuse a loops fact for a page-less entity under a page rule on a strict source instead of storing it outside Git
garrytan44b306d8776b
diff --git a/behavior-changes.d/strict_fallback_refusal_gst2635.md b/behavior-changes.d/strict_fallback_refusal_gst2635.mdnew file mode 100644index 0000000000..b8d526193c--- /dev/null+++ b/behavior-changes.d/strict_fallback_refusal_gst2635.md@@ -0,0 +1 @@+On a source whose pages are canonical in Git (`canonical: git`), a fact the Google loops extraction (or any writer that keeps a fallback entity, writeSingleFact) finds for an entity with no page that an exact page rule names is now refused `git_home_required` (reason `facts_lane`) before anything is stored, with a fix that creates the entity's page; before, it was stored in the database only, with no file in Git, or refused with a message naming memory/unattributed. When the access rules cannot be read the write refuses `access_policy_pending` (retry), and that refusal's message now names the entity, for `remember` too. The loops job still records the loop and logs the refusal code with the entity's page; nothing is stored for that fact. Facts stored the old way are not changed: `gbrain repair facts-home` lists them as `folder_restricted`. Sources that are not strict and brains with no Git repository are unchanged.diff --git a/changelog.d/capy-strict-fallback-refusal-gst2635.md b/changelog.d/capy-strict-fallback-refusal-gst2635.mdnew file mode 100644index 0000000000..276191dff5--- /dev/null+++ b/changelog.d/capy-strict-fallback-refusal-gst2635.md@@ -0,0 +1,14 @@+---+important: data-loss+---++**On a source whose pages are canonical in Git, a fact the Google loops extraction finds for an entity with no page that an exact page rule names is now refused before anything is stored, the way `remember` already refused it.**++### Fixed++- On a `canonical: git` source, a commitment fact for an entity with no page under an exact page rule (`gbrain access rule add --slug people/bob-example --readers alice-example`) used to be stored in the database only, with no file or commit holding it, so a rebuild from Git lost it. Once `memory/unattributed` existed, the same write was refused instead, with a message that named `memory/unattributed` rather than the entity. The write is now refused `git_home_required` (reason `facts_lane`) before any row is written, and the message and fix name the entity's page to create. An access state the database role cannot read refuses `access_policy_pending` (retry), and that message now names the entity too.+- The loops job still records the loop. Its log line reads `[loops_extract] fact projection failed … (git_home_required)` (or `(access_policy_pending)`) and names the entity's page, so an operator can see which page to create.+- Sources that are not strict, brains with no Git repository, and fact writers that do not keep a fallback entity behave as before.+- Facts an earlier version already stored this way are untouched: `gbrain repair facts-home --source <id>` lists them as `folder_restricted` (`page_rule`) and its apply leaves them; creating the entity's page lets the `extract_facts` upkeep step fence them.++<!-- behavior-change: strict_fallback_refusal_gst2635 -->diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.mdindex 5f60b75b07..b8864be8dd 100644--- a/docs/architecture/key-files/core-persistence-facts.md+++ b/docs/architecture/key-files/core-persistence-facts.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELManaged facts extraction: the entity-intent preparer and publisher, conversation facts batches and the unmanaged derived index. The extraction pipeline itself is in [Google and Loops (continued)](google-and-loops-continued.md) (`src/core/facts/backstop.ts`) and [Core Services (2/3)](core-services-2.md) (`src/core/facts/extract.ts`).- `src/core/facts/bulk-days.ts` — #7247 the one rule doctor `fact_bulk_dates` and `gbrain repair fact-claim-dates` share. `findBulkFactDays` (one read-only aggregate over active facts of active sources, optionally scoped) returns each UTC `valid_from` day holding at least `BULK_DAY_RULE` (200 facts, 25% of the source, 20 entities) with counts, top source tags and `dated_claims`. `claimDate` returns a claim's only `YYYY-MM-DD` token when it is a real date from 1900 to the day before; the aggregate's SQL applies the same token and bounds.-- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). GBRA-130 A-36: `collectManagedFacts` awaits every row before it throws. An entity request that ended on a code of its own page (`ENTITY_REFUSAL_CODES`: `revision_conflict`, `invalid_fence`, `page_body_segmented`, …; not a file-check or withdrawal refusal, which the follow-up walks own) is reported as `refused` (slug, code, request id) on `ManagedFactsResult` and the `extract_facts` result when the session sets `reportRefusals` and another entity of the batch committed (the backstop sets it; `managed-fact-write.ts` and `remember` do not and keep the refusal), and the completion receipt refused only as incomplete is not a failure of its own; any other terminal row, then a pending one, then a refusal with nothing committed beside it, throws as its receipt. Test: `test/pathological/a-36-facts-batch-partial-refusal.test.ts` (PGLite and Postgres). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches at any visibility (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`; every follow-up, file-check and moved-entity ones included, carries the flag and narrows its facts to the current default visibility, so a claim forgotten at any visibility is skipped at preparation and refused at locked validation), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres). #7602: an automatic extraction with no caller request id (`entityMoveRetry`, set by the backstop; explicit writers keep the refusal) also runs `followEntityMoves`, after admission in `publishManagedFacts` and on resume: an entity request refused `revision_conflict` because another write moved its entity page (`FACTS_ENTITY_MOVED_MESSAGES` in `verb-errors.ts`: changed after admission, changed during preparation, deduplication state changed, the coordinator's `PAGE_CHANGED_DURING_PREPARATION_MESSAGE`, which `coordinator.ts` and `group-publish.ts` throw, and the page layer's `PAGE_CHANGED_AFTER_READ_MESSAGE`, how a move during preparation was stored before the fix; `isEntityMovedRefusal` is the one predicate the walk and the repair preview share) is re-admitted under `digest([batchKey, 'entity-moved-retry', n])` at the page's current revision with its retained intent (`readmitMovedFacts`; a deleted or replaced page keeps the refusal), no model call, each batch settled first so a follow-up that loses again is followed in the same run, bounded by `MAX_FILE_REFUSAL_RETRIES`; a follow-up refused for another reason (a held file) is not re-admitted, and the walk carries every request it did not follow. A follow-up's source-page check in `facts-prepare.ts` accepts a source page moved only by a committed request of the same extraction (same principal and input digest, at the page's current revision), such as a fact the batch wrote onto its own source page; any other change still refuses `The source page changed during fact extraction.` A refusal `collectManagedFacts` still throws after the walks is marked `retryable: false`, so the worker ends the facts-absorb job dead on its first attempt (`jobRefusal`; `revision_conflict` is not in `DETERMINISTIC_WRITE_REFUSALS`, so this is not the `facts_absorb_write_refused` path). Test: `test/facts-entity-moved-7602.test.ts` (PGLite and Postgres). #8526: a page-triggered or input-keyed session also runs `followEmbeddingRefusals`, re-admitting facts the owner's consumer refused `embedding_configuration` (through `readmitMovedFacts`: retained visibility, unattributed groups kept) under `digest([batchKey, 'embedding-retry', n])` only once no live full or promoted consumer that started before the refusal remains (`ownerRestartedSince`: the worktree owner host's consumers, every consumer for a batch with no worktree; with no live consumer row, as on PGLite, admission's check of the retained signature against the brain's current config is the gate), bounded by `MAX_FILE_REFUSAL_RETRIES`. Test: `test/facts-embedding-refusal-heal-8526.test.ts` (PGLite and Postgres). `gbrain repair failed-writes` (`failed-writes.ts`, [Core Utilities (2/2)](core-utilities-2.md)) lists refused fact extractions. #7602: fact rows (moved-entity refusals included) use `factsRecovery`: `recover:` (retry-dead reset) only while the page write's facts-absorb job is dead and the entity page is the one admitted, `pending:` while that job runs, `not recoverable:` for a deleted page, and `re-extract:` otherwise (replaced page, completed or missing job, exhausted follow-ups, a page write the job's own `readFactsBackstopJobPage` check now skips (written again since, or a narrowed writer grant), an extraction whose open entity requests are not all moved-entity or all held-file refusals, a guard refusal). Only the preview reads fact rows (`failedWrites(..., { facts: true })`); the sync-time remember replay and apply-by-id keep the guard/drift query.+- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). GST-2635: under `attributeFallback` (writeSingleFact, the loops extraction's call) a page-less entity `holdingHome` refuses (an exact page rule, an unreadable access state) throws `refuseUnheldFact` (`facts/held-fact-move.ts`) before any request is admitted, instead of falling through to a database-only `memory/unattributed` row. Each `ManagedFactsSession` carries one `MaintenanceWriteWait` (`maintenance-wait.ts`) built from the caller's `FactsBackstopCtx.deadlineAtMs` (the facts-absorb job passes its deadline; other callers get the 30 s base) and its abort signal: `collectManagedFacts` waits that long for each accepted request through `awaitWrite`, a cancelled job stops waiting at once, and a request still nonterminal after the wait leaves as `write_pending` with its receipt (#6778, `test/facts-absorb-publish-wait-6778.test.ts`). GBRA-130 A-36: `collectManagedFacts` awaits every row before it throws. An entity request that ended on a code of its own page (`ENTITY_REFUSAL_CODES`: `revision_conflict`, `invalid_fence`, `page_body_segmented`, …; not a file-check or withdrawal refusal, which the follow-up walks own) is reported as `refused` (slug, code, request id) on `ManagedFactsResult` and the `extract_facts` result when the session sets `reportRefusals` and another entity of the batch committed (the backstop sets it; `managed-fact-write.ts` and `remember` do not and keep the refusal), and the completion receipt refused only as incomplete is not a failure of its own; any other terminal row, then a pending one, then a refusal with nothing committed beside it, throws as its receipt. Test: `test/pathological/a-36-facts-batch-partial-refusal.test.ts` (PGLite and Postgres). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches at any visibility (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`; every follow-up, file-check and moved-entity ones included, carries the flag and narrows its facts to the current default visibility, so a claim forgotten at any visibility is skipped at preparation and refused at locked validation), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres). #7602: an automatic extraction with no caller request id (`entityMoveRetry`, set by the backstop; explicit writers keep the refusal) also runs `followEntityMoves`, after admission in `publishManagedFacts` and on resume: an entity request refused `revision_conflict` because another write moved its entity page (`FACTS_ENTITY_MOVED_MESSAGES` in `verb-errors.ts`: changed after admission, changed during preparation, deduplication state changed, the coordinator's `PAGE_CHANGED_DURING_PREPARATION_MESSAGE`, which `coordinator.ts` and `group-publish.ts` throw, and the page layer's `PAGE_CHANGED_AFTER_READ_MESSAGE`, how a move during preparation was stored before the fix; `isEntityMovedRefusal` is the one predicate the walk and the repair preview share) is re-admitted under `digest([batchKey, 'entity-moved-retry', n])` at the page's current revision with its retained intent (`readmitMovedFacts`; a deleted or replaced page keeps the refusal), no model call, each batch settled first so a follow-up that loses again is followed in the same run, bounded by `MAX_FILE_REFUSAL_RETRIES`; a follow-up refused for another reason (a held file) is not re-admitted, and the walk carries every request it did not follow. A follow-up's source-page check in `facts-prepare.ts` accepts a source page moved only by a committed request of the same extraction (same principal and input digest, at the page's current revision), such as a fact the batch wrote onto its own source page; any other change still refuses `The source page changed during fact extraction.` A refusal `collectManagedFacts` still throws after the walks is marked `retryable: false`, so the worker ends the facts-absorb job dead on its first attempt (`jobRefusal`; `revision_conflict` is not in `DETERMINISTIC_WRITE_REFUSALS`, so this is not the `facts_absorb_write_refused` path). Test: `test/facts-entity-moved-7602.test.ts` (PGLite and Postgres). #8526: a page-triggered or input-keyed session also runs `followEmbeddingRefusals`, re-admitting facts the owner's consumer refused `embedding_configuration` (through `readmitMovedFacts`: retained visibility, unattributed groups kept) under `digest([batchKey, 'embedding-retry', n])` only once no live full or promoted consumer that started before the refusal remains (`ownerRestartedSince`: the worktree owner host's consumers, every consumer for a batch with no worktree; with no live consumer row, as on PGLite, admission's check of the retained signature against the brain's current config is the gate), bounded by `MAX_FILE_REFUSAL_RETRIES`. Test: `test/facts-embedding-refusal-heal-8526.test.ts` (PGLite and Postgres). `gbrain repair failed-writes` (`failed-writes.ts`, [Core Utilities (2/2)](core-utilities-2.md)) lists refused fact extractions. #7602: fact rows (moved-entity refusals included) use `factsRecovery`: `recover:` (retry-dead reset) only while the page write's facts-absorb job is dead and the entity page is the one admitted, `pending:` while that job runs, `not recoverable:` for a deleted page, and `re-extract:` otherwise (replaced page, completed or missing job, exhausted follow-ups, a page write the job's own `readFactsBackstopJobPage` check now skips (written again since, or a narrowed writer grant), an extraction whose open entity requests are not all moved-entity or all held-file refusals, a guard refusal). Only the preview reads fact rows (`failedWrites(..., { facts: true })`); the sync-time remember replay and apply-by-id keep the guard/drift query.- `src/core/facts/same-page-shadow.ts` — #6333 the shadow counter both fact writers share. `samePageRewording(engine, sourceId, fact, embedding)` re-reads the entity's nearest live same-visibility candidate (`listSupersessionCandidates`, the pool and filters of `decideSingleFact`'s cosine pass) and answers whether `wouldDedupSamePage` (capture-dedup.ts: same lane, same `source_session`, same visibility, cosine ≥ 0.85, no diverging guard token) would have called the fact a rewording; `warnSamePageShadow` is the one stderr spelling (`[facts-backstop] #6333 shadow: …; both kept`). `facts-prepare.ts` calls it for every candidate `decideSingleFact` did not match and counts `would_dedup_same_page` on the entity outcome, the completion outcome, `ManagedFactsResult` and the `extract_facts` result; the count is frozen in the receipt, so a replay reports it and does not recount. Nothing is dropped; this is the managed mirror of the unmanaged backstop's counter (`backstop.ts`), which never fired on a managed brain. Tests: `test/backstop-same-page-shadow-managed-6333.test.ts` (PGLite and Postgres), `test/backstop-same-page-shadow-6333.test.ts` (unmanaged).- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure of a batch that held it alone or three failed batches block it (GBRA-130 A-51: `publishBatch` re-publishes a multi-page batch that failed deterministically in halves, so only the page that fails alone takes the code; `test/pathological/a-51-conversation-batch-booking.test.ts`); all without model calls. The batch request id digests its members' (generation, attempt) pairs; `submitConversationPages` raises every member's attempt past an id another write holds, or whose receipt lost its intent without committing (#7516: a redacted `purged_content` refusal or a compacted failure takes the attempt history `loadGenerationIndex` reads, so the same id came back on every run as `idempotency_conflict` after a paid extraction; test `test/conversation-facts-redacted-batch-7516.test.ts`, + Postgres arm). The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `publishConversationFacts` (the managed apply and the unmanaged writer) passes fact rows through the write gate at the page's derived tier and retires the prior batch only for a complete replacement (#7013: `full` scope, at least one fact, nothing held or rejected) or on a page with no active extractor facts, through `replaceConversationFacts`, which deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the rows numbered above every remaining row, failing on a lost insert. Otherwise the prior facts stay: the outcome row replaces the page's prior outcome rows (so the page is not paid for again), a `window` run (`--since` dropped messages) adds its facts beside them, and a `partial` run (a `--segment-limit` cut, a page changed mid-run) publishes no facts over them. Each entry carries its `scope`; an entry frozen without one is `partial` without its outcome, `window` with a `--since` selector, else `full`. Tests: `test/pathological/h4-conversation-facts-zero-yield.test.ts` (managed and unmanaged, + Postgres arm). Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.@@ -23,5 +23,5 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation- `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`; journaled as mode `index-previewed`, which a preparer built before the field preview refuses, and an `index-existing` request with no fields digest refuses `preview_changed` asking for a rerun). 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). GST-2492: `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` — GST-2492 `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/facts/held-fact-move.ts` — GST-2492 `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. `refuseUnheldFact` is the one refusal for a fact `holdingHome` will not hold (`remember`'s `planRememberTarget` and, GST-2635, `publishManagedFacts`' attribute fallback call it before anything is admitted): an exact page rule on a strict source throws `git_home_required` (`facts_lane`, through `assertStrictGitHome`) naming the entity's page, an unreadable access state `access_policy_pending` naming the entity. Test: `test/strict-fallback-refusal-gst2635.test.ts` (PGLite and Postgres).- `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/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.mdindex 19c73d1099..f2cbca9ed8 100644--- a/docs/architecture/key-files/open-loops-engine.md+++ b/docs/architecture/key-files/open-loops-engine.md@@ -11,7 +11,7 @@ close semantics). The Gmail sweep that feeds both lanes is in- `src/core/google/counterparty.ts` — where a loop's counterparty page is (#5504, wave 14 P4.1). `resolveCounterparty(engine, sourceId, { name, email })` tries the loop's OWN source first through `resolveEntitySlugWithSource` (name, then email; never the slugify fallback), and only then crosses a source boundary by identity: an `entity_identities` canonical member in another source (`identity_canonical`, which also redirects an own-source stub to its canonical twin) or the exact email as a `page_aliases` row on exactly one live page in exactly one other source (`email_alias`). A display name never crosses, a tie (two other sources) stays unresolved and the loop keeps a NULL counterparty rather than a guess. Both writers (`loop-detect.ts` `upsertThreadLoop`, `loops-extract.ts`) stamp the result into `open_loops.counterparty_source_id` and point the `owes_to` / `awaiting_reply_from` edge at the page's source; the commitment fact stays in the connector source. Readers confine with `COALESCE(counterparty_source_id, source_id)` (`COUNTERPARTY_SOURCE_SQL`): a row written before v236 reads as its own source. `src/core/loops/loops-schema.ts` is the leaf the migration and the store share (column DDL + the partial index `open_loops_counterparty_source_idx`).- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops; positively automated mail (`isPositivelyAutomated`) and, with the opt-in `LoopDetectPolicy.ownerWroteTo`, `CATEGORY_UPDATES` mail from someone the owner never wrote to return `withheld: {reason, counterpartyEmail}` instead of an open (#5012; closes are unaffected) — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions. `applyThreadLoopVerdict` builds the policy through `ownerWroteToFor` and settles a mute re-check thread (`settleMuteRecheck`) whose verdict neither opened nor closed its queued loops; `invalidateSuppressionCache` drops the per-engine suppression cache after a mute or unmute.- `src/core/google/loops-reciprocity.ts` — the opt-in Updates reciprocity rule (#5012): key `loops.updates_require_reciprocity` (default false; `validateLoopsReciprocityConfigValue` at `config set`). `ownerWroteToFor(engine, source, myAddresses)` returns null when off; on, the addresses in `participants` of the source's email pages whose `senders` include an owner address, cached per engine and source for 10 minutes. Tests: `test/loops-noise-5012.test.ts`, `test/loops-noise-5012-store.test.ts` (+ Postgres twin).-- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>` of thread, direction and the normalized verbatim quote, the text only when no quote verified; same-quote items in one response collapse, and a row already recorded for the quote keeps its key, #7289), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code; a failed facts write is logged with slug, source and a bounded error, never the commitment text, and the loop row still lands), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, `Auto-Submitted`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.+- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>` of thread, direction and the normalized verbatim quote, the text only when no quote verified; same-quote items in one response collapse, and a row already recorded for the quote keeps its key, #7289), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code; a failed facts write is logged with slug, source, the refusal code and a bounded error, never the commitment text, and the loop row still lands; on a strict source a counterparty with no page under an exact page rule, or whose access rules cannot be read, is such a refusal, `git_home_required` or `access_policy_pending`, whose message names the entity's page, GST-2635), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, `Auto-Submitted`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. `openedAt` sets `opened_at` (default now()); an open row keeps the earlier of its stored and incoming value, a reopened row takes the incoming one. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `listOpenLoops` takes an optional `id` that composes with the status/type/counterparty filters and never replaces the source scope; `counterpartySourceId` narrows a `counterparty` slug match to the source the page lives in (`COALESCE(counterparty_source_id, source_id)`), leaving an email match untouched (#5504). `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing and returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success). #5012: `closeMutedLoops` closes (or, without apply, lists) the open reply-owed loops a mute covers as `dropped` / `closed_by: muted`, and the upsert never updates a `muted` row for the same counterparty; `requeueMutedLoops` hands an unmuted loop no other suppression covers to `closed_by: mute_recheck` (no thread: `unmuted`, reported `unverifiable`), which the upsert reopens and `closeThreadLoops` closes on the re-check's verdict, and `settleMuteRecheck` marks `unmuted` when neither happens; `muteRecheckThreads` feeds `loadSuppressions().recheckThreads` and the sweep seed; `listSenderInboundLoops` backs `loops drop sender`.- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write; also closes the covered reply-owed loops and returns `closed`, dry run `would_close`, plus `undo_command`), `loops_unmute` (returns `requeued`, `unverifiable`, `stale_source` + `recheck_command`, `undo_command`; dry run `would_requeue`). The grouped `open_loops` view adds `withheld_noise` (null when none): open reply-owed loops from senders in each source's `loop_withheld_senders` record, every sender ordered by open loop count, each with a `preview_command` (#7285; `gbrain waiting` prints the first 10 and counts the rest). `loops_close` retires a commitment loop's fact through `persistence/loop-fact-retirement.ts` and returns `{ closed, id, status, fact_expired, retryable, reason? }` from the real publication outcome; a loop already closed whose fact is still active re-attempts the retirement. `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. Ranking and rendered ages use one reference time, `as_of` (ISO, default now, echoed in the grouped result; `gbrain waiting --as-of`), so a published order is reproducible (N7-5). An optional `id` (positive safe integer, else `invalid_params` through `invalidParam` without echoing the value) finds one loop at any status unless `status` is given; explicit filters still intersect, scope and redaction are unchanged, so an out-of-scope id returns exactly what a missing id returns, and an id lookup carries no `text` digest. The result carries per-source last-successful-sync ages + a `stale` flag (>24h): all stale sources remain a refusal condition for `gbrain waiting`, while a mixed fresh/stale set continues with a warning naming stale sources (`stale_sources` in JSON). Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly. #5871: grouped output ranks people only; loops with neither a counterparty slug nor an email return in `no_counterparty` (`loop_count`, `by_type`, shown loops, `loops_omitted`; null when none), never ranked or counted by `limit`, and the digest lists them last and never says "You are clean" while they exist; each group shows at most `LOOPS_PER_GROUP` (5) loops, due-soonest then most recently active, with `loops_omitted` (`test/ops-loops.test.ts`, `test/loops-cli.test.ts`).- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported); when only some sources are stale, it continues with the warning and source ids from `open_loops`. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. `loops show <id>` passes the id to `open_loops` (any status and rank); a missing positive id is a usage error (exit 2) and an unknown id renders `not_found` with the `gbrain loops list` fix (exit 1). An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and queues the loops the mute closed for re-check; both take `--dry-run` and print the count and the undo command. A repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally. `loops drop sender <email> [--source] [--note] [--dry-run]` closes one sender's open reply-owed loops through `loops_close` (the dry run is the consent step; a drop cannot be undone), and `waiting` prints the `withheld_noise` lines.diff --git a/docs/guides/entity-scoped-facts.md b/docs/guides/entity-scoped-facts.mdindex 96fa2d5f18..e0602bf32f 100644--- a/docs/guides/entity-scoped-facts.md+++ b/docs/guides/entity-scoped-facts.md@@ -130,7 +130,10 @@ folder kept out of Git keeps the page database-only. A rule added later movesthe held rows it covers there in its own apply; the shared page's row is thenremoved, so the shared page never names the ruled entity. An entity under anexact page rule is refused with `git_home_required` (reason `facts_lane`):-create its page with `put_page`, then remember the fact again. Forgetting or+create its page with `put_page`, then remember the fact again. A fact the+Google loops extraction finds for such an entity is refused the same way and+nothing is stored for it; the loop is still recorded, and the job's log names+the refusal and the page. Forgetting orreplacing a held fact strikes its row too. A brain with no Gitrepository gets no notice: there the database is the record, and the fact isas safe as everything else in it.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex ad25222367..c44666a8f2 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -1041,7 +1041,7 @@ Earlier commits keep whatever was pushed before the change; gbrain never rewrite| Code | What happened | What to do ||---|---|---|-| <a id="git_home_required"></a>`git_home_required` | The write would store content in the database with no file in Git and is in no declared class (`no_file_form`), a publication would commit a file for a declared page (`declared_target`), or a writer with no file form yet wrote to the source (`facts_lane`). Nothing was written. A fact for an entity with no page, or with no entity, is not refused this way: every fact writer commits it as a row of `memory/unattributed` instead, or of its folder's `<folder>/memory/unattributed` when a folder access rule covers the entity. The one exception is an entity with no page under an exact page rule (a rule on the entity's own slug): no holding page carries that rule's readers, so `remember` refuses with `facts_lane` and a fix that creates the page (`put_page`), after which the fact can be remembered again. Through `remember` the frozen `error` is `invalid_params` and `code` is `git_home_required`. Nor is a fact or take the write gate holds for the owner's review, whatever page it names: it is refused `write_held` and nothing reaches a page or Git; releasing a held fact commits it to its page's file before its row. | Ask the user which git home to configure: write the page to a path Git tracks, declare its directory under `storage.db_only` in `gbrain.yml`, or mark it `visibility: private`. `gbrain sources git-gap <source> --json` shows every page's class. Submit again with a new request ID. |+| <a id="git_home_required"></a>`git_home_required` | The write would store content in the database with no file in Git and is in no declared class (`no_file_form`), a publication would commit a file for a declared page (`declared_target`), or a writer with no file form yet wrote to the source (`facts_lane`). Nothing was written. A fact for an entity with no page, or with no entity, is not refused this way: every fact writer commits it as a row of `memory/unattributed` instead, or of its folder's `<folder>/memory/unattributed` when a folder access rule covers the entity. The one exception is an entity with no page under an exact page rule (a rule on the entity's own slug): no holding page carries that rule's readers, so `remember` refuses with `facts_lane` and a fix that creates the page (`put_page`), after which the fact can be remembered again. A background fact writer refuses the same way before writing anything: the Google loops extraction still records the loop and logs `[loops_extract] fact projection failed … (git_home_required)` with the entity's page. Nothing is stored for that fact; once the page exists, the entity's later facts are saved on it. Through `remember` the frozen `error` is `invalid_params` and `code` is `git_home_required`. Nor is a fact or take the write gate holds for the owner's review, whatever page it names: it is refused `write_held` and nothing reaches a page or Git; releasing a held fact commits it to its page's file before its row. | Ask the user which git home to configure: write the page to a path Git tracks, declare its directory under `storage.db_only` in `gbrain.yml`, or mark it `visibility: private`. `gbrain sources git-gap <source> --json` shows every page's class. Submit again with a new request ID. || <a id="git_private_commit_refused"></a>`git_private_commit_refused` | A publication would have committed the file bytes of a private, alias-private or lineage-private page. Nothing was written and `HEAD` is unchanged. A grouped publication refuses as a whole. | The page stays database-only. Write it with `put_page`, which publishes a private page without a file, or remove `visibility: private` if it belongs in Git. || <a id="git_protocol_required"></a>`git_protocol_required` | A database trigger refused a row on a strict source because the writing process does not declare the git-canonical protocol: an older gbrain, or `gbrain.write_sources` set by hand. Nothing was written. | Upgrade (`gbrain upgrade`) or stop every gbrain process that shares the database, then retry with a new request ID. || <a id="git_lfs_not_enabled"></a>`git_lfs_not_enabled` | The file falls under a Git LFS rule in `.gitattributes`, and either `storage.git_lfs` is off (`opt_in_off`, the default) or the checkout does not configure the LFS filter or git-lfs does not run (`checkout_unconfigured`). Nothing was written. | Ask the user. To store it with LFS: `git lfs install --local` in the checkout, then `gbrain config set storage.git_lfs true`. Otherwise narrow the `.gitattributes` rule. With the key on and LFS configured, the door commits the LFS pointer and the object goes to the checkout's LFS store; a publication that rolls back can leave an unreferenced object there, which is harmless. |@@ -1059,7 +1059,7 @@ same on a repo-less brain and on a git-backed one.| <a id="access_identity_unavailable"></a>`access_identity_unavailable` | The member a credential (access token, OAuth client or stdio binding) is bound to could not be looked up: the database failed the statement, or timed out or dropped the connection while the request was submitted. The request was refused and nothing was read or written. Reading the credential as unbound instead would open every unlabelled page to a labelled-only member. | Retry the same request in a few seconds; a write keeps the same `request_id`. `whoami` shows the member the connection reads as once the lookup works again. If it keeps failing, the brain operator runs `gbrain doctor --json` on the brain host. || <a id="access_rule_invalid"></a>`access_rule_invalid` | `gbrain access rule add` was given a rule whose prefix is not a literal lower-case slug folder ending in `/` (or holds `..` or `*`), whose readers are not member ids or `group:<id>`, or whose prefix another rule already covers; nothing was written. Prefixes match slugs literally, so a pattern or typo would restrict the wrong pages. | Write the prefix as a folder such as `partners/alice-example/` and the readers as `alice-example,group:team-a`; to change who reads a folder that already has a rule, pass that rule's `--id`. || <a id="access_policy_invalid"></a>`access_policy_invalid` | A source's committed `.gbrain/access.yml` (or a file given to `gbrain access rule import`) does not validate. The last applied rules stay in force and every prefix the file names reads as nobody for remote callers (the whole source when the file does not parse), so a typo never opens a folder. In a partial clone (`git clone --filter`), a policy file or an earlier version of it that the clone never fetched makes the whole source read as nobody the same way, because sync fetches nothing. | `gbrain access rule list --source <id>` shows each problem with its line. Fix the file, commit it with `gbrain git commit-push`, and run `gbrain sync --source <id> --no-pull`. In a partial clone, run the `git cat-file -p` or `git log -p` the problem names in the checkout, which fetches what is missing, then sync the same way. |-| <a id="access_policy_pending"></a>`access_policy_pending` | A narrowing change to a source's folder rules is still being stamped onto its pages, so pages under the folders it touches read as nobody for remote callers until it finishes (other folders keep the last applied rules). Remote reads carry this as a notice: an empty answer there is not proof of no notes. On a git-canonical source, a `remember` for an entity with no page whose access rules this database role cannot read refuses with it (frozen `error` `unavailable`, `next: wait`), because gbrain cannot tell which holding page has the entity's readers; nothing was written. | Wait and retry. If it stays pending the apply was interrupted: on the brain host run `gbrain access resume --source <id>` (database store) or `gbrain sync --source <id> --no-pull` (git store); `gbrain access rule status --source <id>` shows the pending folders. |+| <a id="access_policy_pending"></a>`access_policy_pending` | A narrowing change to a source's folder rules is still being stamped onto its pages, so pages under the folders it touches read as nobody for remote callers until it finishes (other folders keep the last applied rules). Remote reads carry this as a notice: an empty answer there is not proof of no notes. On a git-canonical source, a `remember` for an entity with no page whose access rules this database role cannot read refuses with it (frozen `error` `unavailable`, `next: wait`), because gbrain cannot tell which holding page has the entity's readers; nothing was written. A background fact writer (the Google loops extraction) refuses the same way; the loops job records the loop and logs the code with the entity's page. | Wait and retry. If it stays pending the apply was interrupted: on the brain host run `gbrain access resume --source <id>` (database store) or `gbrain sync --source <id> --no-pull` (git store); `gbrain access rule status --source <id>` shows the pending folders. |## Shared-agent refusalsdiff --git a/src/core/facts/held-fact-move.ts b/src/core/facts/held-fact-move.tsindex 2f10370a7a..c7946fa1b3 100644--- a/src/core/facts/held-fact-move.ts+++ b/src/core/facts/held-fact-move.ts@@ -16,6 +16,7 @@ import { folderHoldingSlug, holdingSlugSql, isHoldingSlug, UNATTRIBUTED_MEMORY_Simport { maintenancePreflight, planHeldRowDrop, submitMaintenanceIntent, submitPlannedFactFenceAdoption, type HeldDrop } from '../persistence/prepared-maintenance.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { getWorktreeBinding } from '../persistence/ownership.ts';+import { assertStrictGitHome } from '../persistence/git-declared.ts';import { isStatementTimeout, PreparationDeadlineError } from '../persistence/bounded-reads.ts';import { registerEngineView } from '../persistence/switches.ts';import { syncPreparationBudgetMs } from '../persistence/sync-waivers.ts';@@ -86,9 +87,19 @@ export async function heldFactTarget(engine: BrainEngine, sourceId: string, key:return strict.miss === 'ambiguous' ? { ambiguous: await entityReferenceCandidates(engine, sourceId, key) } : null;}+/**+ * The refusal of every fact writer for an entity holdingHome refused to hold (remember, and GST-2635 the managed facts+ * writer's attribute fallback), before anything is written: an exact page rule on a strict source refuses+ * `git_home_required` naming the entity's page to create; otherwise the access state cannot be read, so retry.+ */+export async function refuseUnheldFact(engine: BrainEngine, sourceId: string, entity: string, refused: 'page_rule' | 'access_unreadable', remote: boolean): Promise<never> {+ if (refused === 'page_rule') await assertStrictGitHome(engine, { source_id: sourceId, slug: entity }, remote);+ throw accessStateUnreadable(sourceId, entity);+}+/** holdingHome's `access_unreadable`: the folder rules covering the entity cannot be read now, so nothing was written; retry. */-export function accessStateUnreadable(sourceId: string): OperationError {- return opError('access_policy_pending', `The folder access rules of source ${sourceId} cannot be read right now, so gbrain cannot tell which holding page keeps this fact to its entity's readers; nothing was written.`,+function accessStateUnreadable(sourceId: string, entity: string): OperationError {+ return opError('access_policy_pending', `The folder access rules of source ${sourceId} that cover ${entity} cannot be read right now, so gbrain cannot tell which holding page keeps this fact to its entity's readers; nothing was written.`,'Retry the same request shortly; if it keeps failing, the brain host checks the folder access tables (gbrain doctor names the check).',{ docs: 'docs/guides/write-refusals.md#access_policy_pending', fix: { argv: ['gbrain', 'access', 'rule', 'status', '--source', sourceId, '--json'], consent: [], actor: 'provider',requires_exclusive: false, why: 'Shows the folder rules and anything pending; changes nothing. The write succeeds once the rules read again.' } });diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex 439b7aafff..e900c83c31 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -620,7 +620,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFif (embedded) await assertManagedFactsEmbedding(engine, session.config, session.embedding);const sourceId = session.authority.sourceId;const groups = new Map<string, FrozenExtractedFact[]>();- const { holdingHome } = await import('../facts/held-fact-move.ts');+ const { holdingHome, refuseUnheldFact } = await import('../facts/held-fact-move.ts');for (const fact of facts) {if (ctx.abortSignal?.aborted) throw new DOMException('Fact extraction was aborted before admission.', 'AbortError');if (ctx.notabilityFilter === 'high-only' && fact.notability !== 'high' || ctx.notabilityFilter === 'medium-and-up' && fact.notability === 'low') continue;@@ -629,6 +629,8 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFconst attributed = entitySlug ?? (options.attributeFallback && resolved ? resolved.slug : null);// GST-2492: on a strict source a kept fallback entity is held on its holding page (its folder's under a folder rule).const home = !entitySlug && attributed ? await holdingHome(engine, sourceId, attributed) : null;+ // GST-2635: one no holding page can carry (an exact page rule, an unreadable access state) refuses as remember does, before admission.+ if (home && 'refused' in home) await refuseUnheldFact(engine, sourceId, attributed!, home.refused, ctx.remote !== false);const slug = entitySlug ?? (home && 'slug' in home ? home.slug : 'memory/unattributed');await authorizeWrite(engine, session.authority, 'extract_facts', slug);await authorizePageVisibility(engine, session.authority, slug);diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 740926567f..db43aa2904 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -26,7 +26,6 @@ import { grantedWriteSource, writeGrantRefusal } from './write-grant.ts';import type { WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { ownerReachesFact, readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';-import { assertStrictGitHome } from './git-declared.ts';import { callerIsOwner, currentCallerAccess, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { projectionEligibleSql } from '../eligibility/sql.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';@@ -127,11 +126,10 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc// authority above ran on the entity (decision D1); the holding row is gbrain's own companion write, authorized as a write// to that entity. A folder's holding page takes the folder's storage class (database-only under storage.db_only or a path// Git ignores, as the entity's own page would be); a shared one kept out of Git keeps the fact database-only, as before.- const { accessStateUnreadable, holdingHome } = await import('../facts/held-fact-move.ts');+ const { holdingHome, refuseUnheldFact } = await import('../facts/held-fact-move.ts');const home = !inferred && memberPage === null && entitySlug !== null && !snapshot && writeThrough ? await holdingHome(ctx.engine, sourceId, entitySlug) : null;// An exact page rule on the entity, or an access state this role cannot read: no holding page carries those readers.- if (home && 'refused' in home && home.refused === 'page_rule') await assertStrictGitHome(ctx.engine, { source_id: sourceId, slug: entitySlug! }, ctx.remote !== false);- if (home && 'refused' in home) throw accessStateUnreadable(sourceId);+ if (home && 'refused' in home) await refuseUnheldFact(ctx.engine, sourceId, entitySlug!, home.refused, ctx.remote !== false);const holdingSlug = home && 'slug' in home ? home.slug : null;const holding = holdingSlug ? await ctx.engine.readPageSnapshot(holdingSlug, { sourceId, includeDeleted: true }) ?? 'absent' : null;const held = holding !== null && (holding === 'absent' || !holding.page.deleted_at && (Boolean(holding.page.source_path) || holdingSlug !== UNATTRIBUTED_MEMORY_SLUG));diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 8e46047371..3c32bb6c8b 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -626,6 +626,7 @@ test/stale-plan-heal.test.tstest/stats-health-source-scope.test.tstest/status-snapshot-source-scope.test.tstest/strict-background-writers-gst2492.test.ts+test/strict-fallback-refusal-gst2635.test.tstest/sync-absent-from-worktree-s27.test.tstest/sync-admission-6712.test.tstest/sync-apply-held-deletions-gbra133.test.tsdiff --git a/test/strict-fallback-refusal-gst2635.test.ts b/test/strict-fallback-refusal-gst2635.test.tsnew file mode 100644index 0000000000..88b52f2a99--- /dev/null+++ b/test/strict-fallback-refusal-gst2635.test.ts@@ -0,0 +1,271 @@+/**+ * GST-2635: on a strict git-canonical source, the attribute-fallback fact writer refuses a fact no holding page can carry.+ *+ * 1. Protects: on a source whose pages are canonical in Git (`canonical: git`), a fact for an entity with no page that an+ * exact page rule names (`gbrain access rule add --slug people/bob-example`), written through the attribute fallback+ * (writeSingleFact, the Google loops extraction's one call, then publishManagedEntityFacts and publishManagedFacts), is+ * refused before anything reaches the database: `git_home_required` (`facts_lane`) naming the entity's page and the+ * fix that creates it, as `remember` refuses. An access state this database role cannot read refuses+ * `access_policy_pending` (retry). The loops job keeps its loop row and logs the refusal code with the entity's page.+ * 2. Fails when: the writer stores the fact in the database with no row in Git (master 1e2fdc28: `inserted`,+ * source_markdown_slug and row_num null, no file, no commit), or refuses with a message that names memory/unattributed+ * instead of the entity's page (master, once memory/unattributed exists), or when a source that is not strict, a brain+ * with no Git repository, or a writer that does not pass the fallback stops behaving as before.+ * 3. Existing coverage: test/folder-holding-page-gst2492.test.ts pins the same refusals for `remember`;+ * test/strict-background-writers-gst2492.test.ts pins the background writers for entities no page rule names.+ * 4. Real seams: the coordinated write and the write door on PGLite and Postgres (DATABASE_URL), a managed Git checkout,+ * the page rule added the way an owner adds it (`gbrain access rule add --slug ... --yes`), member-bound MCP callers,+ * and the loops job as the minion handler runs it, with the model behind the gateway's test transport.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, relative } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { runAccessRules } from '../src/commands/access-rules.ts';+import { holdingPageFor } from '../src/core/facts/held-fact-move.ts';+import { writeSingleFact } from '../src/core/facts/write-single.ts';+import { publishManagedEntityFacts } from '../src/core/facts/managed-fact-write.ts';+import { runLoopsExtract } from '../src/core/google/loops-extract.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 { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const HOLD = 'memory/unattributed';+const ENTITY = 'people/bob-example';+const EMAIL = 'emails/invoice-thread';+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };+let chatReply = '{"commitments":[],"decisions_pending":[]}';+const gitRepo = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };++beforeAll(() => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: chatReply, blocks: [], stopReason: 'end', usage,+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }));+});+afterAll(() => { __setChatTransportForTests(null); resetGateway(); });++const filesHolding = (root: string, claim: string): string[] => {+ const out: string[] = [];+ const walk = (dir: string) => {+ for (const name of readdirSync(dir)) {+ if (name === '.git') continue;+ const path = join(dir, name);+ if (statSync(path).isDirectory()) walk(path);+ else if (readFileSync(path, 'utf8').includes(claim)) out.push(relative(root, path));+ }+ };+ walk(root);+ return out;+};+const factRows = (engine: BrainEngine, claim: string) => engine.executeRaw<{ entity_slug: string | null; source_markdown_slug: string | null; row_num: number | null }>(+ 'SELECT entity_slug, source_markdown_slug, row_num FROM facts WHERE source_id=$1 AND fact=$2 ORDER BY id', ['default', claim]);+const factRequests = (engine: BrainEngine) => engine.executeRaw<{ slug: string; state: string }>(+ `SELECT slug, state FROM persistence_requests WHERE operation='extract_facts' AND source_id='default' ORDER BY sequence`);+const commitsHolding = (root: string, claim: string) => git(root, 'log', '--all', '--format=%h %s', '-S', claim).trim().split('\n').filter(Boolean);++async function addPageRule(engine: BrainEngine) {+ const spy = spyOn(console, 'log').mockImplementation(() => {});+ try { await runAccessRules(engine, 'rule', ['add', '--source', 'default', '--slug', ENTITY, '--readers', 'alice-example', '--yes', '--json'], true); }+ finally { spy.mockRestore(); }+}+const unreadableAccess = (engine: BrainEngine) =>+ engine.executeRaw('CREATE OR REPLACE FUNCTION gbrain_access_state_unreadable() RETURNS boolean LANGUAGE sql STABLE AS $fn$ SELECT true $fn$');+const seedHoldingPage = async (ctx: OperationContext) => {+ await operationsByName.remember!.handler(ctx, { fact: 'An ordinary unattributed note.', provenance: 'chat 2026-11-13', request_id: randomUUID() });+ await settleManagedGitEffects(ctx.engine);+ expect(await ctx.engine.getPage(HOLD, { sourceId: 'default' })).not.toBeNull();+};++type Refusal = { code?: string; canonical?: string; reason?: string; message: string; fix?: Record<string, unknown> };+async function loopsWrite(engine: BrainEngine, claim: string): Promise<{ reply: Awaited<ReturnType<typeof writeSingleFact>> | null; refusal: Refusal | null }> {+ try { return { reply: await writeSingleFact(engine, 'default', { fact: claim, entity: ENTITY, provenance: 'mail 2026-11-13', kind: 'commitment', visibility: 'private', remote: false }), refusal: null }; }+ catch (error) { return { reply: null, refusal: error as Refusal }; }+ finally { await settleManagedGitEffects(engine); }+}++/** Remote MCP callers bound to members, as test/folder-holding-page-gst2492.test.ts builds them. */+async function members(engine: BrainEngine) {+ const tokens: Record<string, string> = {};+ for (const id of ['alice-example', 'carol-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1) ON CONFLICT DO NOTHING', [id]);+ for (const member of ['alice-example', 'carol-example']) {+ const minted = await mintLegacyToken(engine, { name: `${member}-${randomUUID().slice(0, 6)}`, scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: ['default'] });+ tokens[member] = minted.token;+ await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);+ }+ __resetPrivateVisibilityCacheForTests();+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ return async (who: string, op: string, params: Record<string, unknown>) => {+ const auth = await provider.verifyAccessToken(tokens[who]!) as unknown as AuthInfo;+ const localFederated = await noGrantFederatedScope(engine, auth.hasSourceGrant, 'default');+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: 'default', takesHoldersAllowList: ['world'],+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}) });+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n') };+ };+}++/** The loops job as its minion handler runs it, on one email page whose commitment names ENTITY. */+async function runLoopsJob({ engine, ctx }: ManagedBrain, claim: string) {+ await engine.setConfig('loops.extraction_enabled', 'true');+ await operationsByName.put_page!.handler(ctx, { slug: EMAIL, request_id: randomUUID(),+ content: `---\ntitle: Invoice thread\ntype: email\nthread_id: invoice-thread\nfrom: [email protected]\n---\nI will send Bob the invoice summary by Friday.\n` });+ await settleManagedGitEffects(engine);+ chatReply = JSON.stringify({ commitments: [{ text: claim, direction: 'owed_by_me', counterparty_name: ENTITY, counterparty_email: '',+ due_iso: '2026-11-20', quote: 'I will send Bob the invoice summary by Friday.' }], decisions_pending: [] });+ const warned: string[] = [];+ const spy = spyOn(console, 'warn').mockImplementation((...args: unknown[]) => { warned.push(args.map(String).join(' ')); });+ try {+ const result = await runLoopsExtract(engine, { slug: EMAIL, sourceId: 'default' });+ await settleManagedGitEffects(engine);+ const loops = await engine.executeRaw<{ fact_id: number | null; summary: string }>('SELECT fact_id, summary FROM open_loops WHERE source_id=$1', ['default']);+ return { result, loops, log: warned.filter(line => line.startsWith('[loops_extract] fact projection failed')) };+ } finally { spy.mockRestore(); }+}++for (const backend of testBackends()) describe(`[${backend}] GST-2635: the attribute-fallback fact writer on a strict source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const brain = (strict: boolean, run: (brain: ManagedBrain) => Promise<void>) => managedBrain(async b => {+ if (strict) await b.engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id='default'`);+ await run(b);+ }, { databaseUrl, setup: gitRepo });++ test('missing arm: no memory/unattributed yet, the write refuses git_home_required naming the entity\'s page and writes nothing', () => brain(true, async b => {+ await addPageRule(b.engine);+ expect(await holdingPageFor(b.engine, 'default', ENTITY)).toEqual({ refused: 'page_rule' });+ expect(await b.engine.getPage(HOLD, { sourceId: 'default' })).toBeNull();+ const claim = 'Bob example prefers the quarterly invoice summary.';+ const { reply, refusal } = await loopsWrite(b.engine, claim);+ expect(reply).toBeNull();+ expect({ code: refusal?.code, reason: refusal?.reason }).toEqual({ code: 'git_home_required', reason: 'facts_lane' });+ expect(refusal!.message).toContain(ENTITY);+ expect(refusal!.message).not.toContain(HOLD);+ expect(refusal!.fix).toMatchObject({ ask_user: true, mcp: { tool: 'put_page', arguments: { slug: ENTITY } } });+ expect(await factRows(b.engine, claim)).toEqual([]);+ expect(await factRequests(b.engine)).toEqual([]);+ expect(filesHolding(b.root, claim)).toEqual([]);+ expect(commitsHolding(b.root, claim)).toEqual([]);+ expect(await b.engine.getPage(HOLD, { sourceId: 'default' })).toBeNull();+ }), 300_000);++ test('present arm: memory/unattributed exists, the write refuses naming the entity\'s page, not memory/unattributed', () => brain(true, async b => {+ await seedHoldingPage(b.ctx);+ await addPageRule(b.engine);+ expect(await holdingPageFor(b.engine, 'default', ENTITY)).toEqual({ refused: 'page_rule' });+ const before = readFileSync(join(b.root, `${HOLD}.md`), 'utf8');+ const claim = 'Bob example asked for the invoices in euros.';+ const { reply, refusal } = await loopsWrite(b.engine, claim);+ expect(reply).toBeNull();+ expect({ code: refusal?.code, reason: refusal?.reason }).toEqual({ code: 'git_home_required', reason: 'facts_lane' });+ expect(refusal!.message).toContain(ENTITY);+ expect(refusal!.message).not.toContain(HOLD);+ expect(refusal!.fix).toMatchObject({ mcp: { tool: 'put_page', arguments: { slug: ENTITY } } });+ expect(await factRows(b.engine, claim)).toEqual([]);+ expect(await factRequests(b.engine)).toEqual([]);+ expect(filesHolding(b.root, claim)).toEqual([]);+ expect(readFileSync(join(b.root, `${HOLD}.md`), 'utf8')).toBe(before);+ }), 300_000);++ test('an access state this role cannot read refuses access_policy_pending (retry) and writes nothing', () => brain(true, async b => {+ await unreadableAccess(b.engine);+ expect(await holdingPageFor(b.engine, 'default', ENTITY)).toEqual({ refused: 'access_unreadable' });+ const claim = 'Bob example moved the invoice due date.';+ const { reply, refusal } = await loopsWrite(b.engine, claim);+ expect(reply).toBeNull();+ expect(refusal?.code).toBe('access_policy_pending');+ expect(refusal!.message).toContain(ENTITY);+ expect(refusal!.fix).toMatchObject({ actor: 'provider', argv: ['gbrain', 'access', 'rule', 'status', '--source', 'default', '--json'] });+ expect(await factRows(b.engine, claim)).toEqual([]);+ expect(await factRequests(b.engine)).toEqual([]);+ expect(filesHolding(b.root, claim)).toEqual([]);+ }), 300_000);++ test('readers: carol-example, whom the page rule does not name, cannot read the fact; the owner\'s own reads are unchanged', () => brain(true, async b => {+ await addPageRule(b.engine);+ const kept = 'Bob example keeps the renewal terms confidential.';+ await loopsWrite(b.engine, kept);+ const as = await members(b.engine);+ const probe: Record<string, Record<string, boolean | string>> = {};+ for (const who of ['alice-example', 'carol-example']) {+ const out: Record<string, boolean | string> = {};+ for (const [op, params] of [['search', { query: kept, match: 'keyword', fields: 'full', limit: 20 }], ['recall', { entity: ENTITY }], ['recall', { query: 'renewal terms' }], ['memory_recall', { query: 'renewal terms confidential' }]] as const) {+ const got = await as(who, op, params as Record<string, unknown>);+ out[`${op} ${JSON.stringify(params)}`] = got.isError ? `error: ${got.text.slice(0, 160)}` : got.text.includes(kept);+ }+ probe[who] = out;+ }+ expect(Object.values(probe['carol-example']!).some(v => v === true)).toBe(false);+ // Once the owner creates the entity's page, the same write lands on it in Git and the owner reads it.+ await operationsByName.put_page!.handler(b.ctx, { slug: ENTITY, request_id: randomUUID(), content: '---\ntype: person\ntitle: Bob Example\n---\n\nNotes about Bob Example.\n' });+ await settleManagedGitEffects(b.engine);+ expect((await loopsWrite(b.engine, kept)).reply).toMatchObject({ status: 'inserted', entity_slug: ENTITY });+ expect(await factRows(b.engine, kept)).toMatchObject([{ entity_slug: ENTITY, source_markdown_slug: ENTITY, row_num: 1 }]);+ expect(git(b.root, 'show', `HEAD:${ENTITY}.md`)).toContain(kept);+ expect(JSON.stringify(await operationsByName.recall!.handler(b.ctx, { entity: ENTITY }))).toContain(kept);+ }), 300_000);++ test('a source that is not strict keeps the fact database-only, as before', () => brain(false, async b => {+ await addPageRule(b.engine);+ const claim = 'Bob example asked for paper invoices.';+ const { reply, refusal } = await loopsWrite(b.engine, claim);+ expect(refusal).toBeNull();+ expect(reply).toMatchObject({ status: 'inserted', entity_slug: ENTITY });+ expect(await factRows(b.engine, claim)).toEqual([{ entity_slug: ENTITY, source_markdown_slug: null, row_num: null }]);+ expect(filesHolding(b.root, claim)).toEqual([]);+ }), 300_000);++ test('a brain with no Git repository (the keyless default) stores the fact, never refused for lacking a repository', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gst2635-repoless-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ await addPageRule(engine);+ const claim = 'Bob example pays invoices on the first of the month.';+ const reply = await writeSingleFact(engine, 'default', { fact: claim, entity: ENTITY, provenance: 'mail 2026-11-13', kind: 'commitment', visibility: 'private', remote: false });+ expect(reply).toMatchObject({ status: 'inserted' });+ expect(await factRows(engine, claim)).toEqual([{ entity_slug: null, source_markdown_slug: null, row_num: null }]);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ }, 300_000);++ test('a writer that does not pass the fallback still holds the fact on memory/unattributed with no entity, as before', () => brain(true, async b => {+ await addPageRule(b.engine);+ const claim = 'The invoice template gained a tax line.';+ const written = await publishManagedEntityFacts(b.engine, 'default', ENTITY, [{ fact: claim, kind: 'fact', notability: 'medium', source: 'extraction 2026-11-13',+ visibility: 'world', embedding: null, sessionId: null }]);+ await settleManagedGitEffects(b.engine);+ expect(written.inserted).toBe(1);+ expect(await factRows(b.engine, claim)).toMatchObject([{ entity_slug: null, source_markdown_slug: HOLD, row_num: 1 }]);+ expect(git(b.root, 'show', `HEAD:${HOLD}.md`)).toContain(claim);+ }), 300_000);++ for (const arm of ['missing', 'present', 'access_unreadable'] as const) {+ test(`the loops job keeps the loop row and logs the refusal with the entity's page (${arm} arm)`, () => brain(true, async b => {+ if (arm === 'present') await seedHoldingPage(b.ctx);+ if (arm === 'access_unreadable') await unreadableAccess(b.engine); else await addPageRule(b.engine);+ const claim = `Send Bob the invoice summary by Friday (${arm}).`;+ const { result, loops, log } = await runLoopsJob(b, claim);+ expect(result).toMatchObject({ status: 'extracted', commitments: 1 });+ expect(loops).toEqual([{ fact_id: null, summary: claim }]);+ expect(await factRows(b.engine, claim)).toEqual([]);+ expect(filesHolding(b.root, claim).filter(path => !path.startsWith('emails/'))).toEqual([]);+ expect(log).toHaveLength(1);+ expect(log[0]).toContain(arm === 'access_unreadable' ? '(access_policy_pending)' : '(git_home_required)');+ expect(log[0]).toContain(ENTITY);+ expect(log[0]).not.toContain(claim);+ }), 300_000);+ }+});