Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: concurrent first remembers all land on memory/unattributed; a sandboxed subagent forget of a file-backed claim refuses
garrytanc7c556cfe521
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 33da0d18d6..d03b8dc657 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,11 +23,11 @@ Git stays the parent: a withdrawal is now a page write, published to Git before| Situation | Before | Now ||---|---|---|| `forget` / `forget_fact` | the database expired the fact; the page files caught up later through a mirror | every page whose `## Facts` table carries the claim gets its row struck (`~~claim~~`, a `valid_until` date, `forgotten: <reason>`), all in one publication and one commit, then the ledger row and expiries in the same transaction |-| `remember` without an entity | a database-only row | a row of the `memory/unattributed` page's `## Facts` table, created on first use, so Git, `recall` and search see it |+| `remember` without an entity | a database-only row | a row of the `memory/unattributed` page's `## Facts` table, created on first use (concurrent first saves all land on it), so Git, `recall` and search see it || Remembering that claim again with an entity | two copies | the entity row is written and the unattributed row struck in the same publication || A member forgets a fact on their own member page | withdrawn for that page | unchanged: the withdrawal stays on that page, and other members' copies stay active |-A forget now waits for the source's writer the way `remember` does: with the writer unavailable it returns the pending-write receipt, and the fact is still recalled until it publishes. With `sync.write_through` off, or on a source with no canonical owner, a forget of a claim a page file carries is refused (`sync_write_through_off`, `unbound_source`) instead of withdrawing it in the database only; a claim only database-only pages carry is still withdrawn. Migration v287 adds the multi-page recovery record (one record restores every file of an interrupted publication); it rewrites no data.+A forget now waits for the source's writer the way `remember` does: with the writer unavailable it returns the pending-write receipt, and the fact is still recalled until it publishes. With `sync.write_through` off, from a sandboxed subagent, or on a source with no canonical owner, a forget of a claim a page file carries is refused (`sync_write_through_off`, `subagent_sandbox`, `unbound_source`) instead of withdrawing it in the database only; a claim only database-only pages carry is still withdrawn. Migration v287 adds the multi-page recovery record (one record restores every file of an interrupted publication); it rewrites no data.### Review lists and review decisions through the page door (#7791, #7797)@@ -95,6 +95,7 @@ A page can now say when its text takes effect, with `valid_from` and `valid_unti- The answer is the edition with the latest `valid_from` on or before the date, picked across the current page and every version gbrain kept. Its `valid_time` block says whether that edition was `in_force`, `not_in_force`, `not_yet_in_force` or `before_recorded_history`, and whether gbrain held enough history to be sure. Only an `in_force` answer returns the text at the top level, so an agent that skips the status cannot quote expired text as current.- When history is missing (pruned versions, a sync that imported several commits at once, a page that came from a file) or the dates look ambiguous (a corrected date and a renewal leave the same trace), the answer says `uncertain: true`, why, and how to recover: the file's `git log`, or asking the user for a backup. It never guesses.- Works the same on a brain with no Git repository, the default keyless install.+- Over MCP, an `as_of` read follows the plain read's rules: a quarantined page's body is omitted, and an edition's `introduced_because` is shown only when the edition it replaced is one the caller may read.- `gbrain get --as-of` exits 15 when no edition was in force, and 16 (`host_upgrade_required`) when the brain host is too old to answer by date, printing nothing historical.- Writes say when they keep or change an edition's date (`valid_time_correction`, `valid_time_date_only`, `valid_from_unparsed`), and `get_versions` rows carry each version's `valid_from` and `valid_until`.- Behavior change: a plain `get_page` of a page whose own `valid_from` is in the future, or whose `valid_until` has passed, now also carries a `valid_time` status. Pages without those dates read exactly as before.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex b423bc044f..7a0e02b12c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -56,7 +56,7 @@ of making a duplicate.| <a id="refusal_breaker"></a>`refusal_breaker` | the code of the earlier refusals | The same maintenance write (same source, slug, page revision, planner and intent) was refused `persistence.maintenance.refusal_breaker_threshold` times (default 3; `0` turns it off) in the last 24 hours, so maintenance submits nothing for it instead of adding another receipt (#6696). It is tried again once the page, the planner or the write changes, or when the oldest refusal is 24 hours old. | Read the last refusal with `gbrain write-request -- <request_id>` (named in the message) and fix what it names. Doctor `maintenance_write_drift` lists every held-back write with its exit. || <a id="canonical_file_absent"></a>`canonical_file_absent` | `source_changed` (`restore_page` / `gbrain restore`) | On a brain without managed persistence, a restore that writes no file (`sync.write_through` off, a sandbox, a database-only source) of a soft-deleted page whose recorded file is no longer among the files sync imports (#6609). A plain restore would be undone by the next `gbrain sync --full`, so nothing was restored. Not retryable; the fix asks the user. | Ask the user. To keep the page with its file: put the file back at its recorded path, commit it and `gbrain sync --source <source>`. To keep it database-only: `gbrain restore <slug> --source-id <source> --detach` (MCP `restore_page` with `detach: true`), which forgets the recorded file and stamps `database_only_reason='detached'`. See [restoring a page whose file is gone](../storage-tiering.md#restoring-a-page-whose-file-is-gone). || <a id="pending_import"></a>`pending_import` | `source_changed` (detail `file_database_drift`, reason `pending_import`) | The page's canonical file holds a change committed through Git (another agent's commit, a pull) that managed sync has not imported yet: the file on disk is exactly the blob `HEAD` holds for its path and not the one the source's last imported commit holds. The message is "The canonical file holds a committed Git change that sync has not imported yet." Nothing was overwritten. Since #6693 the receipt records origin `pending_import`; a write refused because sync holds the file records origin `sync_held` (see [held files](#held-files-and-content-refusals)). | A `remember` needs nothing from the caller: its `fix.next` is `wait`, the fact is kept in the receipt, and the first managed sync that imports the file (any outcome, a partial run included) makes one replay attempt on the original caller's lane with the fact's original `valid_from` and expiry (the sync result's `replayedRemembers` counts examined, replayed, waiting, skipped, remaining; at most 50 per run and 30 s). Do not save the fact again. A remember refused while sync held its file is replayed the same way once the repaired file is imported. A replay that is refused (authority revoked, page rewritten) stays listed by `gbrain repair failed-writes --source <source>` for a person. Any other write (`put_page`, `add_timeline_entry`) is never replayed automatically, because its body would replace the imported change: wait for the source's running sync owner (`gbrain serve`, autopilot or a sync job) to import the commit, which the refusal's read-only fix `gbrain sync status --source <source> --json` shows, then read the page again and resubmit with a new request ID. Neither refusal tells the caller to start a sync, because a second sync beside a running owner competes with it; when status shows no owner running, ask the user to sync the source on its host. An uncommitted hand edit still refuses `file_database_drift` and needs reconcile. |-| <a id="sync_write_through_off"></a>`sync_write_through_off` | `unavailable` (`forget` / `forget_fact`, detail `sync_write_through_off`) | `sync.write_through` is off and a canonical file carries the claim. The struck row would not reach the file, so a brain rebuilt from Git would bring the claim back; nothing was withdrawn. A claim that only database-only pages carry is still withdrawn. | `gbrain config set sync.write_through true`, then forget the fact again. |+| <a id="sync_write_through_off"></a>`sync_write_through_off` | `unavailable` (`forget` / `forget_fact`, detail `sync_write_through_off`) | `sync.write_through` is off and a canonical file carries the claim. The struck row would not reach the file, so a brain rebuilt from Git would bring the claim back; nothing was withdrawn. A claim that only database-only pages carry is still withdrawn. A sandboxed subagent's forget of such a claim refuses the same way with `scope_denied`, detail `subagent_sandbox`. | `gbrain config set sync.write_through true`, then forget the fact again; from a subagent sandbox, forget it from the main session. || <a id="shared_origin"></a>`shared_origin` | `source_changed` (purge, or a delete whose survivor changed); a soft delete commits with `write_through.skipped: shared_origin` | Two live pages of one source recorded the same canonical file (a duplicate-origin twin: the shared file renders one of them, so a delete of either used to refuse `file_database_drift`, reconcile refused "Several pages claim the recorded canonical file" and every managed sync refused `page_identity_changed`). A soft delete (`gbrain delete <slug> --source-id <id> --expected-revision <rev>`) of a page whose file another live page records now keeps the file and publishes database-only: the selected database page is hidden; the file and the surviving page remain. This does not erase that file's contents. The receipt's `write_through.warning` says so and names the surviving slug to the trusted local owner, or to a remote writer whose grant and visibility cover that slug; other remote writers read a generic "another page of this source records the same file". Sync's census and both origin guards apply one rule: a live page wins over tombstones, several live pages refuse, a single tombstone may be reused, several tombstones stay ambiguous. An owner purge (`--purge`) of a shared-origin page refuses with this reason: a purge tombstones the content source-wide and a same-content survivor would refuse `purged_content` on its next import. The 72 h retention purge (the autopilot purge phase, `gbrain pages purge-deleted --older-than 72h --yes`) of such a page once it is soft-deleted writes no tombstone, so it removes the page row, its chunks, links and facts database-only and leaves the file and the surviving page untouched (#7311); a census that changed under it defers to the next run, which re-reads the claimants and, when the tombstone now owns the file alone, purges it normally, file included. A delete whose surviving claimant changed between preparation and publication (the file moved or removed, a survivor deleted or re-pointed) refuses and never removes the file as a fallback. | Delete the page that should not own the file; the kept file still holds whatever text it had, so edit it first if it holds the deleted page's text, then import its current content into the surviving page with `gbrain repair file-drift --source <id> --slug <surviving-slug> --prefer file` (preview, then the apply command it prints) and `gbrain sync --source <id> --no-pull`. Sync does not overwrite a surviving page that differs from the file: it holds it [`file_drift`](#file_drift), whose fix leads with the same command. For a purge of a live page, soft-delete it instead; a soft-deleted one is removed by the retention purge (a tombstone an older release parked after its refusals is retried once by the first purge run after the upgrade). After a `source_changed` on a changed survivor, submit the delete again with a new `request_id`; it re-reads the file's claimants. || <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The exception is relationship `unreadable_state` (#7636): the database role gbrain connects as cannot see the writer state the guard reads (the `persistence_brain` or `git_canonical_brain` row, or the source or page row the write names) because row-level security hides it, or a `persistence_brain` / `git_canonical_brain` row is missing, so the guard refuses instead of letting the write through as if the brain were unmanaged or the row absent. A derived-state maintainer trigger raises the same refusal (#7637, raiser `gbrain_forget_page_retrievals`, `gbrain_queue_page_projection` and the others [listed in ENGINES.md](../ENGINES.md#derived-state-maintainers)) when row-level security applies to the role on a table it keeps up to date and the role holds no policy for it there, instead of leaving that derived state stale. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. For another trigger it also carries a closed `reason`: `attribution_unclassified_table` or `trust_unclassified_table` (a gbrain stamp trigger met a table it is not built for: a version mismatch), `graduation_in_progress` (the engine-graduation fence, SQLSTATE 55000, refuses writes until the move finishes: retry later), or `unknown` (an operator trigger gbrain does not know; its message text stays on the brain host). The same `reason`, raiser and table appear on the managed sync failure (`gbrain doctor`, the failure ledger) and in `gbrain sync status --json` `last_error.write_error_detail`. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. For relationship `unreadable_state` the build is not the cause: run gbrain as a role that can see that state (the table owner, a role that bypasses RLS, or a scoped role whose policies cover those rows, though a change to which sources are Git-canonical passes only the first two; see [writer-protocol fences](../ENGINES.md#opt-in-rls-source-scope-binding-gbrain_rls_scope_binding), and for a maintainer's table the [policies a scoped writer needs](../ENGINES.md#derived-state-maintainers)), then retry with a **new** request ID; a missing row, which `gbrain init` never leaves, is reported like a defect. Never force-write, edit SQL or disable the guard. || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull`. |diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex b7c321bd25..ef89aea5f6 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -442,7 +442,7 @@ test/v0_37_gap_fill.serial.test.ts Lane D.2 — embed pre-flight catches dim mistest/v0_37_gap_fill.serial.test.ts Lane D.3 — sync surfaces dim-mismatch recipe at incremental AND first-sync catches 2 source-surface-helpertest/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is provider-aware 1 readFileSync,source-surface-helpertest/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 8 source-surface-helper-test/valid-time-gbra217.test.ts valid-time normaliser and verdict (pure) 19 readFileSync+test/valid-time-gbra217.test.ts valid-time normaliser and verdict (pure) 21 readFileSynctest/w13-small-hardening.test.ts P1.14 paid-consent lint wording 1 exec-scantest/worker-supervised-db-probe.test.ts issue #1801 fix #2 — supervised DB self-defense 5 readFileSynctest/write-attribution-legacy.test.ts write attribution inventory 1 readFileSyncdiff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.tsindex cd24d1fb4a..a61d96a36c 100644--- a/src/core/facts/fence-fact-append.ts+++ b/src/core/facts/fence-fact-append.ts@@ -43,6 +43,7 @@ import { withPendingFenceRows } from '../eligibility/fence-overlay.ts';import { withPageTierKept } from '../trust/fence-append.ts';import type { TrustTier } from '../trust/tier.ts';import { extractFactsFromFenceText, UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';+import { rememberAcceptsPageCreatedSince } from '../persistence/page-identity.ts';import { fenceRowOf, type FenceRowInput } from './unfenced-facts.ts';export type FenceFactAppendInput = {@@ -170,7 +171,8 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ// The canonical parser/chunker and durable filesystem publication; the CAS binds this render to the snapshot.// #5575 ENG-1: the new row has no facts row yet; its chunks are cut at the append's tier.const prepared = await withPendingFenceRows({ ...page, rowNums: [rowNum], tier: input.pendingTier },- () => preparePageMutation(engine, { ...row, intent: { ...row.intent, content, ...(snapshot ? { expected_revision: snapshot.revision } : {}), force: false } }, config, undefined, signal, { unprojected: true }));+ () => preparePageMutation(engine, { ...row, ...(snapshot && rememberAcceptsPageCreatedSince(row, snapshot) ? { page_id: snapshot.page.id } : {}),+ intent: { ...row.intent, content, ...(snapshot ? { expected_revision: snapshot.revision } : {}), force: false } }, config, undefined, signal, { unprojected: true }));if (prepared.observedRevision !== (snapshot?.revision ?? null)) {throw opError('revision_conflict', 'The entity page changed during preparation.',`Another write changed ${row.slug} in source ${row.source_id} while request ${row.request_id} was prepared, so it did not save. Check that request's receipt; once it shows conflict, nothing was saved and submitting it again is safe.`,diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 9c4d50e99f..63d6cb87d7 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -5,7 +5,7 @@ import type { PageSnapshot } from '../page-state/types.ts';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';-import { pageIdentityError } from './page-identity.ts';+import { pageIdentityError, rememberAcceptsPageCreatedSince } from './page-identity.ts';import { atomicStagingPath, atomicWriteFileSync, mkdirPrivate, validateAtomicStagingPath } from '../atomic-write.ts';import { flushDirectory } from '../fs-durable.ts';import { isWriteTargetContained } from '../path-confine.ts';@@ -612,7 +612,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr// A rename moves an existing page (its old slug is an additional key): not a new page.createdPage = snapshot === null && !prepared.additionalPageKeys?.length;await authorizePageVisibility(tx, row.authority, row.slug);- if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page was deleted or recreated.');+ if ((snapshot?.page.id ?? null) !== row.page_id && !rememberAcceptsPageCreatedSince(row, snapshot)) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page was deleted or recreated.');await assertUnboundPublication(tx, row, snapshot?.page.source_path);if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, 'Read its current revision and submit the updated intent with a new request_id.');for (const companion of companions) {diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex d2b0f48738..c4694e2e27 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -333,10 +333,20 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo'SELECT 1 FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL AND source_path IS NOT NULL LIMIT 1', [sourceId, struck])).length > 0;const target = await resolveFactWriteTarget(ctx.engine, sourceId, source, { sandbox, fileBacked, remote }).catch((error: unknown) => { if (!fileBacked && error instanceof OperationError) return null; throw error; });- // Likewise with sync.write_through off: the struck file would not be written, so the claim would come back from Git.- if (fileBacked && target?.kind === 'publish' && target.databaseOnlyReason === 'disabled_by_config') {- throw verbError('unavailable', 'This brain has sync.write_through off, so forget cannot strike the claim in the page files that carry it.',- 'Turn write-through back on (gbrain config set sync.write_through true), then forget the fact again; nothing was withdrawn.', 'sync_write_through_off');+ // Likewise with sync.write_through off or from a sandboxed subagent: the struck file would not be written, so the claim+ // would come back from Git.+ if (fileBacked && target?.kind === 'publish' && target.databaseOnlyReason === 'subagent_sandbox') {+ throw verbError('scope_denied', 'A sandboxed subagent cannot strike the claim in the page files that carry it.',+ 'Forget the fact from the main session instead; nothing was withdrawn.', 'subagent_sandbox');+ }+ if (fileBacked && target?.kind === 'publish' && target.databaseOnlyReason) {+ throw verbError('unavailable', target.databaseOnlyReason === 'disabled_by_config'+ ? 'This brain has sync.write_through off, so forget cannot strike the claim in the page files that carry it.'+ : 'This source writes the page database-only, so forget cannot strike the claim in the page files that carry it.',+ target.databaseOnlyReason === 'disabled_by_config'+ ? 'Turn write-through back on (gbrain config set sync.write_through true), then forget the fact again; nothing was withdrawn.'+ : 'Bind the source to its canonical checkout, then forget the fact again; nothing was withdrawn.',+ target.databaseOnlyReason === 'disabled_by_config' ? 'sync_write_through_off' : String(target.databaseOnlyReason));}if (target?.kind === 'publish' && target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;const binding = target?.kind === 'unbound' ? await claimWorktree(ctx.engine, sourceId, target.root, undefined, undefined, { automatic: true })diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 230443a6b4..002dec328e 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -1,7 +1,7 @@import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { opError } from '../ops/contract.ts';-import { pageIdentityError } from './page-identity.ts';+import { pageIdentityError, rememberAcceptsPageCreatedSince } from './page-identity.ts';import { assertPageRevision } from '../page-state/types.ts';import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';import { supersededValidUntil } from '../facts/supersede-interval.ts';@@ -79,9 +79,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque...(p.member_page === true ? { page_slug: row.slug } : {}),...(claim ? { slot: { ...claim, valid_from: String(p.valid_from) } } : {}) };const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- // GST-359 C2: a member page another write created after this one was accepted is the same page, not a recreation.- const createdSince = p.member_page === true && row.page_id === null && snapshot !== null && !snapshot.page.deleted_at;- if ((snapshot?.page.id ?? null) !== row.page_id && !createdSince) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');+ if ((snapshot?.page.id ?? null) !== row.page_id && !rememberAcceptsPageCreatedSince(row, snapshot)) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');if (p.member_page === true && snapshot && !memberPageIsOwn(row.slug, snapshot.page.frontmatter)) throw memberPageNotOwned(row.slug);// A defaulted visibility never lands broader than the target page as it stands at publication.if (p.visibility_defaulted === true && snapshot) input.visibility = tightenToPage(input.visibility, await withFolderRestricted(engine, snapshot.page));diff --git a/src/core/persistence/page-identity.ts b/src/core/persistence/page-identity.tsindex e31d9143d5..fce26ad886 100644--- a/src/core/persistence/page-identity.ts+++ b/src/core/persistence/page-identity.ts@@ -6,6 +6,8 @@* recovers the distinction from the stored message alone (no schema change).*/import { opError, type OperationError } from '../ops/contract.ts';+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';+import type { WriteRequest } from './model.ts';export const PAGE_MISSING_MESSAGE = 'The accepted page no longer exists.';@@ -36,3 +38,15 @@ export function yamlLocator(text: string | null | undefined): string {const m = /\bline (\d+)(?:,? column (\d+))?/i.exec(text ?? '') ?? /\((\d+):(\d+)\)/.exec(text ?? '');return m ? ` at line ${m[1]}${m[2] ? `, column ${m[2]}` : ''}` : '';}++/**+ * GST-359 C2: a member page another write created after this remember was accepted is the same page, not a recreation;+ * so is memory/unattributed, which the first subjectless remember creates (concurrent first saves all land on it).+ * Preparation and the coordinator's publication check share it.+ */+export function rememberAcceptsPageCreatedSince(row: Pick<WriteRequest, 'operation' | 'slug' | 'page_id' | 'intent'>,+ snapshot: { page: { deleted_at?: Date | string | null } } | null): boolean {+ const p = row.intent;+ return row.operation === 'remember' && row.page_id === null && snapshot !== null && !snapshot.page.deleted_at && !!p+ && (p.member_page === true || (row.slug === UNATTRIBUTED_MEMORY_SLUG && p.entity_slug == null));+}diff --git a/test/g4-forget-fence-edit.test.ts b/test/g4-forget-fence-edit.test.tsindex 94806d6f90..bb978e958c 100644--- a/test/g4-forget-fence-edit.test.ts+++ b/test/g4-forget-fence-edit.test.ts@@ -214,6 +214,28 @@ for (const backend of testBackends()) describe(`[${backend}] G4: forget is a fenexpect(await ledger(engine, OTHER)).toEqual(['notes/b']);}, { databaseUrl, setup }), 180_000);+ for (const shape of ['repository', 'repo-less'] as const) test(`three parallel first remembers without an entity all commit to memory/unattributed (${shape})`, () => managedBrain(async ({ engine, ctx }) => {+ const facts = ['Parallel claim one g4par', 'Parallel claim two g4par', 'Parallel claim three g4par'];+ const results = await Promise.all(facts.map(fact => call(ctx, 'remember', { fact, provenance: 'test', visibility: 'world', infer_entity: false })));+ expect(results.map(r => r.state)).toEqual(['committed', 'committed', 'committed']);+ const stored = await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source_id='default' AND entity_slug IS NULL AND expired_at IS NULL AND fact LIKE '%g4par' ORDER BY fact`);+ expect(stored.map(row => row.fact)).toEqual([...facts].sort());+ }, { databaseUrl, ...(shape === 'repository' ? { setup } : {}) }), 180_000);++ test('a sandboxed subagent forget refuses a claim a canonical file carries and withdraws nothing', () => managedBrain(async ({ engine, ctx, root }) => {+ const slug = 'wiki/agents/7/notes-a';+ expect(await call(ctx, 'put_page', { slug, content: note('A', [`| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | test | |`]) })).toMatchObject({ state: 'committed' });+ const { settleManagedGitEffects } = await import('./helpers/managed-brain.ts');+ await settleManagedGitEffects(engine);+ const id = (await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id='default' AND fact=$1 AND expired_at IS NULL`, [CLAIM]))[0]!.id;+ const before = readFileSync(join(root, `${slug}.md`), 'utf8');+ const refused = await call({ ...ctx, viaSubagent: true, subagentId: 7 } as OperationContext, 'forget', { id: String(id) }).catch((error: { code?: string; detail?: string }) => error);+ expect({ code: refused.code, detail: refused.detail }).toEqual({ code: 'scope_denied', detail: 'subagent_sandbox' });+ expect(readFileSync(join(root, `${slug}.md`), 'utf8')).toBe(before);+ expect(await ledger(engine, CLAIM)).toEqual([]);+ expect((await engine.executeRaw<{ active: boolean }>('SELECT expired_at IS NULL AS active FROM facts WHERE id=$1', [id]))[0]!.active).toBe(true);+ }, { databaseUrl, setup }), 180_000);+test('a source whose owner is unavailable still withdraws a claim only a database-only page carries', () => managedBrain(async ({ engine, ctx, root }) => {await engine.setConfig('sync.write_through', 'false');expect(await call(ctx, 'put_page', { slug: 'notes/b', content: note('B', [`| 1 | ${OTHER} | fact | 1.0 | world | medium | 2026-01-01 | | test | |`]) })).toMatchObject({ state: 'committed' });