Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: forget records withdrawals only through forget; no writer derives the ledger from fence markers

garrytan9c3ffac9fc21
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 050fec55d6..0704b43a8e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,7 +25,6 @@ Git stays the parent: a withdrawal is now a page write, published to Git before
| `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 |
| Remembering that claim again with an entity | two copies | the entity row is written and the unattributed row struck in the same publication |
-| A brain rebuilt from Git | lost its withdrawals | a trusted local sync, import or page write of a struck row records the withdrawal again; remote page writes cannot create one |
| 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. Migration v287 adds the multi-page recovery record (one record restores every file of an interrupted publication); it rewrites no data.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 066f1e374e..891f19fbe9 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -423,12 +423,12 @@ The struck rows are written first: every page file that carries the claim is
published in one write (one Git commit on a source that commits through
gbrain), and the withdrawal commits with it. A forget waits for the source's
writer like any other write, so while that writer is unavailable the forget is
-accepted and pending, and the fact is still recalled. A brain rebuilt from Git
-keeps the withdrawal: a sync or import from the owner's checkout, or a local
-write, of a struck row dated in `valid_until` with a `forgotten:` context
-records it again. A row like that arriving in a remote page write is only an
-expired row; it withdraws nothing. A fact saved without an entity is a row of
-the `memory/unattributed` page, so its withdrawal has a file too.
+accepted and pending, and the fact is still recalled. The withdrawal itself is
+a database row, and only `forget` records one: a page write or sync of a struck
+row imports an expired fact and withdraws nothing, so a brain rebuilt from Git
+can save that claim again until it is forgotten there. A fact saved without an
+entity is a row of the `memory/unattributed` page, so its withdrawal has a file
+too.
Automatic extraction (sync import, `put_page`, `extract_facts`, the sweep)
skips a candidate whose exact claim was forgotten in that source and visibility
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1264859acb..e3cbac4d75 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1428,7 +1428,6 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.571.0', text: 'Doctor `fence_integrity` now points a legacy fact row that copies a claim its page\'s `## Facts` table already carries (`duplicate_claim`) at the read-only `gbrain repair duplicate-facts --source <id>` preview, which keeps the fence row and supersedes the copy onto it after the user agrees. Before, every unadoptable row got only a report with no command (GBRA-190).' },
{ since: '0.60.571.0', text: '`forget` and `forget_fact` now write the page files first: every page whose `## Facts` table carries the claim has its row struck (`~~claim~~`, a `valid_until` date and `forgotten: <reason>`) and all of them publish in one write, one Git commit on a source that commits through gbrain, before the withdrawal commits in the same transaction. Before, the database withdrew the fact at once and a later effect rewrote the files. A forget now waits for the source\'s writer like `remember`: while that writer is unavailable it returns the pending-write receipt and the fact is still recalled until it publishes. The page history gets one change for the withdrawal instead of a second materialization change. Withdrawals queued by an older release still drain (GBRA-190).' },
{ since: '0.60.571.0', text: 'A fact remembered without an entity is now a row of the `memory/unattributed` page\'s `## Facts` table (created on first use) instead of a database-only row, so it is in Git, `recall` and search can return that page, and a forget of it strikes the row there. Remembering the same claim with an entity links it and strikes the `memory/unattributed` row in the same write. No placeholder entity page is created (GBRA-190).' },
- { since: '0.60.571.0', text: 'A brain rebuilt from Git keeps its withdrawals: a sync or import from the owner\'s checkout, or a local page write, of a struck `## Facts` row with a `valid_until` date and a `forgotten:` context records that withdrawal again (for the page\'s entity, or every entity on `memory/unattributed`), so the claim cannot be remembered again. The same row arriving in a remote page write only imports as an expired row and withdraws nothing; remote callers still withdraw through `forget` (GBRA-190).' },
// GBRA-216 PR B (keyless claim-conflict lane). `since` is stamped at the merge slot.
{ since: '0.60.571.0', id: 'recall_decide_contested_gbra216', text: '`recall` now marks a fact `contested` (proposal_ref `dp<id>`, role, fact_id; the CLI prints `(contested by #<id>)`) when it is in a pending `gbrain decide` supersede proposal and both facts are still active, as it already did for trust proposals. The label appears only when the caller can read the other fact (remote callers see world facts only; private provenance and the trust floor apply). If the lookup fails, recall still answers and reports `facts_degraded: {reason: "contested_unavailable"}`.' },
{ since: '0.60.571.0', id: 'trust_review_contradictions_gbra216', text: '`gbrain trust review` now lists pending `gbrain decide` proposals whose two facts are both active as kind `contradiction` (`dp<id>`), with supersede, forget, confirm and drop commands and who runs each. `--kind contradiction` filters them, `counts.contradiction` counts them, and `gbrain trust review --accept-all` never decides them: each one appears under `skipped` with reason `contradiction`.' },
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index dfe58485ae..dd7e369856 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -11,7 +11,6 @@ import { coverageActive, noteBelief, readLedgerSource, withBeliefBatch } from '.
import { createPageVersion } from '../page-state/versions.ts';
import { validateSlug } from '../utils.ts';
import { factWithdrawalSubjectSql, onMemberPageSql } from '../access/member-facts.ts';
-import { UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -177,33 +176,6 @@ export async function recordFactWithdrawal(
});
}
-/**
- * GBRA-190 G4 (D1): the ledger is derived from Git. A trusted local import (the owner's sync or import, a local page
- * write; never a remote one, prepareCanonicalProjections' `ledger`) of a fence row carrying the explicit withdrawal
- * marker (struck, a `valid_until` date and context `forgotten: ...`, as forget writes it) records its withdrawal at that
- * date, so a brain rebuilt from Git keeps it and the import overlay leaves the row as the file holds it. A struck row
- * without its date is an expired row with no ledger entry: deriving one would make the next import rewrite the row's
- * `valid_until`, so the stored body would no longer match the file. The subject is
- * the page's slug, and '*' only for a row of memory/unattributed (a fact saved without an entity). A '*' row is not
- * derived while the same claim is active on a fact with an entity: it would withdraw that fact too, which forget
- * refuses (`claim_linked`). Existing ledger rows are kept as they are. Returns the rows added.
- */
-export async function deriveFenceWithdrawals(tx: BrainEngine, sourceId: string, slug: string,
- rows: readonly ParsedFact[]): Promise<number> {
- const marked = rows.filter(row => !row.active && row.forgotten === true && /^\d{4}-\d{2}-\d{2}$/.test(row.validUntil ?? ''))
- .map(row => ({ fact: row.claim, visibility: row.visibility, at: `${row.validUntil}T00:00:00Z` }));
- if (!marked.length) return 0;
- const inserted = await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,subject,fact_hash,withdrawn_at)
- SELECT $1,m.visibility,$2,gbrain_fact_fingerprint(m.fact),min(m.at::timestamptz)
- FROM jsonb_to_recordset($3::text::jsonb) AS m(fact text,visibility text,at text)
- WHERE m.visibility IN ('private','world')
- AND ($2<>'*' OR NOT EXISTS (SELECT 1 FROM facts l WHERE l.source_id=$1 AND l.visibility=m.visibility AND l.entity_slug IS NOT NULL
- AND l.expired_at IS NULL AND (l.valid_until IS NULL OR l.valid_until > now()) AND gbrain_fact_fingerprint(l.fact)=gbrain_fact_fingerprint(m.fact)))
- GROUP BY m.visibility,gbrain_fact_fingerprint(m.fact)
- ON CONFLICT DO NOTHING RETURNING fact_hash`, [sourceId, slug === UNATTRIBUTED_MEMORY_SLUG ? '*' : slug, JSON.stringify(marked)]);
- return inserted.length;
-}
-
// Fingerprint each incoming claim once. Inside the join condition the planner
// re-evaluates both fingerprint functions for every (claim, withdrawal) pair,
// so a 28-row fence against 400 withdrawals spent 4 s in this query.
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 69e9eb788e..6e7f50dff2 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -6,7 +6,6 @@ import { pipelined } from '../page-state/transactions.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-fence.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';
import { extractFactsFromFenceText, pageFactDate } from '../facts/extract-from-fence.ts';
-import { deriveFenceWithdrawals } from '../facts/withdrawal.ts';
import { takesPreparation } from '../takes-write.ts';
import { LINK_EXTRACTOR_VERSION_TS, parseTimelineEntries } from '../link-extraction.ts';
import { eachStoredTimelineRow, extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, TimelineKeySet,
@@ -622,7 +621,7 @@ export function compileCanonicalProjections(page: ParsedPage, slug: string, sour
const scan=scanCanonicalFences(page);
if(scan.defects.length) throw fenceOperationError(scan.defects[0]!, slug, sourceId);
const fields:Array<[FenceSection,string]>=[['body',page.compiled_truth],['timeline',page.timeline ?? '']];
- return { fenceFacts: scan.facts, factRows: extractFactsFromFenceText(scan.facts,slug,sourceId,{ pageEffectiveDate: factDate }), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };
+ return { factRows: extractFactsFromFenceText(scan.facts,slug,sourceId,{ pageEffectiveDate: factDate }), takes: scan.takes, sections: scan.sections, quoted: scan.quoting ? quotedFenceRows(fields) : null };
}
/**
@@ -663,12 +662,10 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug
* over the single-string ceiling) is read block by block (segmentedPriorView).
*/
export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,
- prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy,
- /** GBRA-190 G4 (D1): a trusted local writer's body (the owner's sync or import, a local page write) records the ledger rows of its explicit withdrawal markers. */
- ledger?: { deriveWithdrawals: boolean }): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {
+ prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {
// #7247: a fence row without a valid_from takes the page's stated date, as extract_facts does, never the import time.
const factDate = pageFactDate({ slug, frontmatter: page.frontmatter, timeZone: await engine.getConfig('brain.timezone') });
- const { fenceFacts, factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId, factDate);
+ const { factRows, takes, quoted, sections } = compileCanonicalProjections(page, slug, sourceId, factDate);
// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it
// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.
const projectFences = !isQuarantined(page.frontmatter);
@@ -818,7 +815,6 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
() => pipelined(tx, factGeneration.retiring ? [expireFacts, ...timelineRows] : timelineRows)));
if (factsHeld) await step('timeline', () => pipelined(tx, timelineRows));
if (guard.rows.length) await step('facts', () => tx.insertFacts(guard.rows, { source_id: sourceId })); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
- if (!factsHeld && ledger?.deriveWithdrawals) await step('withdrawals', () => deriveFenceWithdrawals(tx, sourceId, slug, fenceFacts));
const contested = await step('fact_trust', () => guard.finish(tx));
// W1 #6783 §12 (b): a fence row's field rewrite can lower a more trusted fact (the tier trigger); what was derived from it follows.
const above = factRows.length ? await factsAboveWriter(tx, sourceId, slug) : [];
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 0cbe1ed2fb..3b082a765e 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -272,8 +272,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
const rendered = imageBytes ?? (code ? content : serializePageToMarkdown({
...(snapshot ? withoutBody(snapshot.page) : { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,
} as Page, tags));
- const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file', undefined,
- { deriveWithdrawals: true });
+ const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');
const mutation: PreparedMutation = { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),
trust: await ownerImportTrust(engine, row, ready.parsedPage?.frontmatter, p.sourcePath), deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },
...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 70eb4b841d..3fff3945db 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -983,7 +983,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wri
// Projections, advisories, link resolution (links-preparation.ts), the file target and the core guard go out together.
enterClaimStep(clock, 'link_resolution', undefined, 'db');
const [project, advisories, links, target, core] = await pipelined(together, [
- async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy,{ deriveWithdrawals: row.authority.remote === false }) : undefined,
+ async () => projected ? prepareCanonicalProjections(engine,ready.parsedPage,row.slug,row.source_id,snapshot,writer,timelinePolicy) : undefined,
async () => noop || targetDeleted ? pageNoopAdvisories(row) : !ordinaryPage ? remoteLinkHint(row) : preparePageAdvisories(engine,row,ready.parsedPage,snapshot),
async () => !noop && !targetDeleted && autoLinkedPage && (row.authority.autoLinkTrusted ?? !row.authority.remote) && await isAutoLinkEnabled(engine)
? prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id,options.coordinated === true) : undefined,
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 1de0478b3d..9fc7ace76d 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -117,7 +117,7 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconci
{ fix: pageFix(state.pins.source_id, state.pins.slug) });
if (ready.observedRevision !== state.snapshot.revision) staleReconcile('revision changed during policy assessment');
const resolved = reconcileCanonical(ready.parsedPage, [...new Set([...state.snapshot.tags, ...ready.parsedPage.tags])]);
- const project = await prepareCanonicalProjections(engine, resolved, state.pins.slug, state.pins.source_id, state.snapshot, writer, undefined, { deriveWithdrawals: true });
+ const project = await prepareCanonicalProjections(engine, resolved, state.pins.slug, state.pins.source_id, state.snapshot, writer);
return { ...merged, result: resolved, ready, project };
}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index c5768673cf..e25cfd7c31 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -913,7 +913,7 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _c
const writeback = canonicalWritebackNeeded(row, p, p.content, canonicalFile);
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
enterClaimStep(clock, 'canonical_projections', undefined, 'db');
- const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file', undefined, { deriveWithdrawals: row.authority.remote !== true });
+ const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: sha256(p.content!),
...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}), parser: syncImportParser(pack?.identity ?? null),
...(p.fullEpisode ? { full_episode: p.fullEpisode } : {}) };
diff --git a/test/g4-forget-fence-edit.test.ts b/test/g4-forget-fence-edit.test.ts
index a5eb685f75..7c666b8a2c 100644
--- a/test/g4-forget-fence-edit.test.ts
+++ b/test/g4-forget-fence-edit.test.ts
@@ -1,13 +1,12 @@
/**
- * GBRA-190 G4: forget is a fence edit, and the withdrawal ledger is derived from Git.
+ * GBRA-190 G4: forget is a fence edit.
* - A withdrawal that strikes several pages is one coordinated publication: every struck file lands in one door commit
* on a strict source, before the ledger row and expiries commit, and no withdrawal-mirror effect is queued (D2).
* - Interrupted before its commit, recovery restores every file of its version 3 record and the replay commits once;
* interrupted after it, the committed files are kept and the replay completes against them.
* - Remember linking a fact saved without an entity strikes its memory/unattributed row in the same commit (D3).
- * - A trusted local import of a withdrawal marker records its ledger row, so a brain rebuilt from Git keeps the
- * withdrawal; subject '*' only for memory/unattributed rows, the page's slug otherwise. A remote page write carrying
- * the marker records no ledger row and blocks no remember (D1).
+ * - No writer derives ledger rows from markers: a brain rebuilt from Git records no withdrawal, and a remote page write
+ * carrying a struck forgotten: row records nothing, blocks no remember and stays inert after a rebuild.
* Runs on PGLite and, with DATABASE_URL, on Postgres.
*/
import { describe, expect, test } from 'bun:test';
@@ -160,7 +159,7 @@ for (const backend of testBackends()) describe(`[${backend}] G4: forget is a fen
expect(await ledger(engine, CLAIM)).toEqual([]);
}, { databaseUrl, setup }), 180_000);
- test('a brain rebuilt from Git keeps the withdrawal: the local import derives the ledger from the markers', async () => {
+ test('a brain rebuilt from Git records no withdrawal: the markers stay in the files and no ledger row is derived', async () => {
const copy = mkdtempSync(join(tmpdir(), 'gbrain-g4-rebuild-'));
try {
await managedBrain(async ({ engine, ctx, root }) => {
@@ -169,15 +168,14 @@ for (const backend of testBackends()) describe(`[${backend}] G4: forget is a fen
const { settleManagedGitEffects } = await import('./helpers/managed-brain.ts');
await settleManagedGitEffects(engine);
expect(git(root, 'status', '--porcelain')).toBe('');
+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain(`~~${CLAIM}~~`);
execFileSync('git', ['clone', '-q', root, join(copy, 'repo')]);
}, { databaseUrl, setup });
- await managedBrain(async ({ engine, ctx }) => {
+ await managedBrain(async ({ engine, root }) => {
expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
- // memory/unattributed rows are withdrawn for every subject; a page's own marker for that page's subject.
- expect(await ledger(engine, CLAIM)).toEqual(['*', 'notes/a']);
- expect(await isFactWithdrawn(engine, 'default', 'world', CLAIM, null)).toBe(true);
- const again = await call(ctx, 'remember', { fact: CLAIM, provenance: 'test', visibility: 'world', infer_entity: false }).catch((error: { code?: string; message?: string }) => error);
- expect(String((again as { message?: string }).message)).toContain('fact_withdrawn');
+ expect(readFileSync(join(root, 'notes/a.md'), 'utf8')).toContain(`~~${CLAIM}~~`);
+ expect(await ledger(engine, CLAIM)).toEqual([]);
+ expect(await isFactWithdrawn(engine, 'default', 'world', CLAIM, null)).toBe(false);
}, { databaseUrl, setup: ({ root }) => { rmSync(root, { recursive: true, force: true }); execFileSync('git', ['clone', '-q', join(copy, 'repo'), root]); } });
} finally { rmSync(copy, { recursive: true, force: true }); }
}, 240_000);
@@ -208,26 +206,30 @@ for (const backend of testBackends()) describe(`[${backend}] G4: forget is a fen
expect(await ledger(engine, OTHER)).toEqual(['notes/b']);
}, { databaseUrl, setup }), 180_000);
- test('a local page write of a withdrawal marker records it under the page; a remote one records nothing and blocks no remember', () => managedBrain(async ({ engine, ctx }) => {
- const marked = (claim: string) => [`| 1 | ~~${claim}~~ | fact | 1.0 | world | medium | 2026-01-01 | ${today} | test | forgotten: no longer true |`];
- const clientId = `client-${randomUUID().slice(0, 8)}`;
- await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','example-client','read write','default')`, [clientId]);
- const remote = { ...ctx, remote: true, transport: 'http', auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'write'], sourceId: 'default' } } as OperationContext;
- const REMOTE = 'Remote marker claim g4remote', LOCAL = 'Local marker claim g4local';
- expect(await call(remote, 'put_page', { slug: 'notes/remote', content: note('Remote', marked(REMOTE)) })).toMatchObject({ state: 'committed' });
- expect(await ledger(engine, REMOTE)).toEqual([]);
- expect((await engine.executeRaw<{ active: boolean }>(`SELECT expired_at IS NULL AS active FROM facts WHERE source_id='default' AND fact=$1`, [REMOTE]))[0]!.active).toBe(false);
- expect(await call(ctx, 'remember', { fact: REMOTE, provenance: 'test', visibility: 'world', entity: 'notes/remote' })).toMatchObject({ state: 'committed' });
- expect(await call(ctx, 'put_page', { slug: 'notes/local', content: note('Local', marked(LOCAL)) })).toMatchObject({ state: 'committed' });
- expect(await ledger(engine, LOCAL)).toEqual(['notes/local']);
- const refused = await call(ctx, 'remember', { fact: LOCAL, provenance: 'test', visibility: 'world', entity: 'notes/local' }).catch((error: { message?: string }) => error);
- expect(String((refused as { message?: string }).message)).toContain('fact_withdrawn');
- // A struck, forgotten row without its valid_until date is not the marker forget writes: no ledger row, so the next
- // import's withdrawal overlay never dates the row and the stored body stays the file's.
- const UNDATED = 'Undated marker claim g4undated';
- const undated = note('Undated', [`| 1 | ~~${UNDATED}~~ | fact | 1.0 | world | medium | 2026-01-01 | | test | forgotten: no longer true |`]);
- expect(await call(ctx, 'put_page', { slug: 'notes/undated', content: undated })).toMatchObject({ state: 'committed' });
- expect(await ledger(engine, UNDATED)).toEqual([]);
- expect((await engine.readPageSnapshot('notes/undated', { sourceId: 'default' }))!.page.compiled_truth).toContain(`| ~~${UNDATED}~~ | fact | 1.0 | world | medium | 2026-01-01 | |`);
- }, { databaseUrl, setup }), 180_000);
+ test('a remote page write of a struck forgotten: row records nothing, blocks no remember, and stays inert after a rebuild from Git', async () => {
+ const copy = mkdtempSync(join(tmpdir(), 'gbrain-g4-remote-'));
+ const REMOTE = 'Remote marker claim g4remote';
+ try {
+ await managedBrain(async ({ engine, ctx, root }) => {
+ const clientId = `client-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id) VALUES($1,'fixture-hash','example-client','read write','default')`, [clientId]);
+ const remote = { ...ctx, remote: true, transport: 'http', auth: { token: 'fixture', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'write'], sourceId: 'default' } } as OperationContext;
+ const marked = note('Remote', [`| 1 | ~~${REMOTE}~~ | fact | 1.0 | world | medium | 2026-01-01 | ${today} | test | forgotten: no longer true |`]);
+ expect(await call(remote, 'put_page', { slug: 'notes/remote', content: marked })).toMatchObject({ state: 'committed' });
+ expect(await ledger(engine, REMOTE)).toEqual([]);
+ expect(await isFactWithdrawn(engine, 'default', 'world', REMOTE, 'notes/remote')).toBe(false);
+ const { settleManagedGitEffects } = await import('./helpers/managed-brain.ts');
+ await settleManagedGitEffects(engine);
+ expect(git(root, 'status', '--porcelain')).toBe('');
+ expect(readFileSync(join(root, 'notes/remote.md'), 'utf8')).toContain('forgotten: no longer true');
+ execFileSync('git', ['clone', '-q', root, join(copy, 'repo')]);
+ }, { databaseUrl, setup });
+ await managedBrain(async ({ engine, ctx }) => {
+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ expect(await ledger(engine, REMOTE)).toEqual([]);
+ expect(await isFactWithdrawn(engine, 'default', 'world', REMOTE, 'notes/remote')).toBe(false);
+ expect(await call(ctx, 'remember', { fact: REMOTE, provenance: 'test', visibility: 'world', entity: 'notes/remote' })).toMatchObject({ state: 'committed' });
+ }, { databaseUrl, setup: ({ root }) => { rmSync(root, { recursive: true, force: true }); execFileSync('git', ['clone', '-q', join(copy, 'repo'), root]); } });
+ } finally { rmSync(copy, { recursive: true, force: true }); }
+ }, 240_000);
});