Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W2: purged lifetimes collapse to disclosed intervals; rename preimage behavior row; purge, purge_fact and remote probes; design wording on soft delete
garrytancbaad1f0c30e
diff --git a/docs/designs/BELIEF_LEDGER.md b/docs/designs/BELIEF_LEDGER.mdindex 7f627df083..6bc3bbbfc8 100644--- a/docs/designs/BELIEF_LEDGER.md+++ b/docs/designs/BELIEF_LEDGER.md@@ -118,9 +118,11 @@ Two lifetimes scope every key:side table `belief_page_lifetimes (source_id, source_incarnation, slug,page_lifetime, started_at, ended_at)`. It is not derived from`knowledge_revision`, which changes on every write (`src/schema.sql:1862`)- and whose first value is not recoverable once versions are pruned. A delete- then recreate of a slug starts a new lifetime. A rename keeps the lifetime- and records the new slug. Subjects with no page (database-only facts whose+ and whose first value is not recoverable once versions are pruned. A soft+ delete keeps the lifetime: a later write to the slug restores the same page+ row and appends `page.restored` on it. Only a page removed outright (purge,+ retention cleanup) and then written again at the slug starts a new+ lifetime. A rename keeps the lifetime and records the new slug. Subjects with no page (database-only facts whose`entity_slug` names no page) have a NULL `page_lifetime` and are scoped bysource lifetime and subject slug alone.@@ -1186,7 +1188,7 @@ W2's interval tests map onto these directly:| Before, at and after creation and each of two edits | (1) || Stalled transaction straddling T, including one that commits after ceiling plus grace | (2) || Rolled-back write | No event, because the append is in the rolled-back transaction |-| Delete then recreate | A new page lifetime |+| Soft delete then write; purge then write | `page.restored` on the same lifetime; a new page lifetime || Version-id tie | Per-page `id` order under the page lock || Create, forget, materialize, edit | (1), the added preimages |diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex bd53b0baa3..9982305996 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -530,6 +530,18 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### clock_mismatch++<a id="clock_mismatch"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date. | Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, so it is refused instead of guessed. | Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date. | agent | `repeat the read that failed` | 1 | no |++Reasons: `date_for_instant`.++More: [docs/guides/repair.md#clock-mismatch](../../docs/guides/repair.md#clock-mismatch)+### code_callees_requires_symbol<a id="code_callees_requires_symbol"></a>@@ -820,9 +832,11 @@ More: [docs/guides/core-memory.md#remote-edits](../../docs/guides/core-memory.md| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark. | Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. | Ask about a time at or after the `from` time, or run `gbrain beliefs backfill --source <id>` for best-effort history before it. | agent | `repeat the read that failed` | 1 | no |+| The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark. | Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. A best-effort backfill from retained versions carries source times only, so it never answers a recorded-time read. | Ask about a time at or after the time the message names; `gbrain beliefs status --source <id>` lists the coverage intervals. | agent | `repeat the read that failed` | 1 | no |++Reasons: `not_recorded`, `backfill_only`, `backfill_incomplete`.-More: [docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark](../../docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark)+More: [docs/guides/repair.md#coverage-from](../../docs/guides/repair.md#coverage-from)### coverage_gap@@ -830,9 +844,11 @@ More: [docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark](.| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore. | The request itself was wrong or no longer matches the brain; nothing was changed. | Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps. | agent | `repeat the read that failed` | 1 | no |+| The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore. | Nothing proves what happened to the page inside the gap, so the read refuses instead of answering from either side. | Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps. | agent | `repeat the read that failed` | 1 | no |-More: [docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark](../../docs/designs/BELIEF_LEDGER.md#71-activation-baseline-and-the-watermark)+Reasons: `not_covered`, `restore`.++More: [docs/guides/repair.md#coverage-gap](../../docs/guides/repair.md#coverage-gap)### cursor_incarnation_retired@@ -1968,6 +1984,16 @@ More: [docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgrMore: [docs/guides/sync-unblock-runbook.md#decision-table](../../docs/guides/sync-unblock-runbook.md#decision-table)+### known_as_of_unproven++<a id="known_as_of_unproven"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A change to the page was recorded before the requested instant but was not yet proven committed at it, so the page at that instant cannot be stated. | A write's recorded time is a lower bound on when it became visible; until its commit mark (or a later write to the same page) proves it committed by the instant, the page then may or may not have included it. | Ask about an instant before the write was recorded, or after it was observed committed (the message names both). | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/repair.md#known-as-of-unproven](../../docs/guides/repair.md#known-as-of-unproven)+### legacy_job_selection_invalid<a id="legacy_job_selection_invalid"></a>diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 236ce04424..f19838b898 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -706,6 +706,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.265.0', text: 'On a managed brain, `gbrain pages purge-deleted` (retention cleanup of pages soft-deleted more than 72 hours ago) no longer writes purge tombstones: it removes the page as before but records no page, fact or take tombstone, so the same content can be imported again later, as on a brain without managed persistence. Only `gbrain delete <slug> --purge` and `purge_fact` forget content. A page purge now also holds its source exclusively while it publishes, so other writes to that source wait for it.' },// Lane 31 (mirror-recovery fast fail). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp. A sync behind a withdrawal-mirror or page-write recovery blocked on unexpected_file_bytes stops at once instead of waiting 5 minutes.{ since: '0.60.265.0', text: 'A sync queued behind a recovery that only the user can resolve now stops after one governor tick with `drain_stalled`, `cause: head_blocked`, instead of waiting out the 5-minute no-progress window. Two recoveries count: a fact-withdrawal mirror whose page file was edited while the mirror was publishing (`blocked_by=effect_recovery(unexpected_file_bytes …)`; the fix asks the user to put the file back to a version gbrain recorded, then rerun the sync), and a page write whose file was edited while it was publishing (`blocked_by=request_recovery(unexpected_file_bytes …)`, whether it blocks the queued head or is the head; the fix runs the `gbrain repair stuck-recovery` preview, or the user undoes the edit). Both name the file, and `gbrain sources writer status` shows the same advice. A recovery that can still finish (its file back on a recorded version) keeps the wait. Known gap: a recovery stuck on `unexpected_staging_bytes` still waits out the window.' },+ // W2 belief ledger page-at-time. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.265.0', text: 'A page rename (a sync that sees a file move, a frontmatter slug repair, a held-file or import move) now saves the page as it stood before the move as a version, as an edit does, so `get_versions` and `gbrain history` list one more snapshot per rename. The move advances the page\'s revision, and until now no version held the body from before it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/belief/page-at-time.ts b/src/core/belief/page-at-time.tsindex 16a966fba3..659ca8e6db 100644--- a/src/core/belief/page-at-time.ts+++ b/src/core/belief/page-at-time.ts@@ -105,15 +105,15 @@ function visibilityAt(e: PageEventRow, t: number): 'visible' | 'not_visible' | 'interface Draft { lifetime: string; slug: string; revision: string | null; deleted: boolean; gone: BodyReason | null; content: boolean; event: PageInterval['event'] }-/** Replays one lifetime's events into intervals: one per content state (a revision, or a view change at one revision), rename or removal. A purge-redacted event keeps its own interval, with no revision. */+/** Replays one lifetime's events into intervals: one per content state (a revision, or a view change at one revision), rename or removal. A purge-redacted event (value NULL) carries no revision, so a purged lifetime's content changes collapse: its intervals split only where its slug or deleted state changed, which the event type and row still say. */function replay(events: PageEventRow[]): Draft[] {const out: Draft[] = [];let state: { slug: string; deleted: boolean; revision: string | null } | null = null;for (const e of events) {const v = e.value ?? {};const gone = GONE[e.event_type] ?? (v.hard === true ? 'hard_deleted' : null);- const content = gone == null && (typeof v.revision_after === 'string' || e.purged);- const next: { slug: string; deleted: boolean; revision: string | null } = { slug: e.slug, revision: content ? (v.revision_after as string | undefined) ?? null : state?.revision ?? null,+ const content = gone == null && typeof v.revision_after === 'string';+ const next: { slug: string; deleted: boolean; revision: string | null } = { slug: e.slug, revision: content ? v.revision_after as string : state?.revision ?? null,deleted: gone != null || e.event_type === 'page.deleted' || (v.deleted === true && e.event_type !== 'page.restored') };if (state && !content && gone == null && next.slug === state.slug && next.deleted === state.deleted) continue;state = next;diff --git a/test/belief-ledger-page-at-time.test.ts b/test/belief-ledger-page-at-time.test.tsindex 69d6029386..54e222cce1 100644--- a/test/belief-ledger-page-at-time.test.ts+++ b/test/belief-ledger-page-at-time.test.ts@@ -176,6 +176,11 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect((await refusal(read(b, { slug: 'notes/old-example', known_as_of: after })))?.code).toBe('page_not_found');const lifetimes = new Set((await b.events()).filter(e => e.subject_kind === 'page').map(e => e.page_lifetime));expect(lifetimes.size).toBe(1);+ const created = (await b.events()).find(e => e.event_type === 'page.published' && e.slug === 'notes/old-example')!;+ const kept = await b.engine.executeRaw<{ knowledge_revision: string; compiled_truth: string }>(`SELECT v.knowledge_revision::text AS knowledge_revision, v.compiled_truth FROM page_versions v+ JOIN pages p ON p.id = v.page_id WHERE p.source_id = $1 AND p.slug = $2 ORDER BY v.id`, [b.sourceId, 'notes/new-example']);+ expect(kept.map(v => v.knowledge_revision)).toEqual([created.value!.revision_after as string]);+ expect(kept[0]!.compiled_truth).toContain('Before the move.');// Forced probe: without the rename's preimage (the move advances the revision), the body before the rename is disclosed missing, not borrowed from the live page.await b.engine.executeRaw('DELETE FROM page_versions WHERE page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = $2)', [b.sourceId, 'notes/new-example']);expect(await read(b, { slug: 'notes/old-example', known_as_of: before })).toMatchObject({ body: 'unavailable', body_reason: 'version_missing' });@@ -209,18 +214,84 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {expect(await read(b, { slug, known_as_of: await at(b) })).toMatchObject({ certified: false, uncertified_reason: 'unmanaged' });}, { managed: false }), 120_000);- test('a purged page discloses every body as purged, never a neighbouring version', () => brain(async b => {- await b.put(slug, draft('First draft.'));+ test('a purged page reads as one interval with no body: its content changes collapse, and nothing purged comes back to a local or remote caller', () => brain(async b => {+ await b.put(slug, beliefPage({ prose: 'First draft.', facts: ['Acme sells purple widgets'] }));await pause();- await b.put(slug, draft('Second draft.'));+ await b.put(slug, beliefPage({ prose: 'Second draft.', facts: ['Acme sells purple widgets', 'Acme opened a Lisbon office'] }));const t = await at(b);+ const [create] = await pageEvents(b, slug);const revision = (await b.engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]))[0]!.r;await b.op('delete_page', { slug, purge: true, expected_revision: revision });- const history = await versions(b, { slug, known_as_of: await at(b), include_body: true });- expect(history.versions.map((v: any) => [v.event, v.body, v.body_reason, v.compiled_truth])).toEqual([- ['page.purged', 'unavailable', 'purged', undefined], ['page.published', 'unavailable', 'purged', undefined], ['page.published', 'unavailable', 'purged', undefined]]);- expect(await read(b, { slug, known_as_of: t })).toMatchObject({ event: 'page.published', deleted: false, body: 'unavailable', body_reason: 'purged' });- expect((await read(b, { slug, known_as_of: t })).compiled_truth).toBeUndefined();+ const after = await at(b);+ const purge = (await pageEvents(b, slug)).at(-1)!;+ const remote = { ...b.ctx, remote: true, transport: 'stdio', takesHoldersAllowList: ['world'] } as typeof b.ctx;+ const shapeOf = (h: Record<string, any>) => h.versions.map((v: any) => [v.event_id, v.event, v.deleted, v.body, v.body_reason, v.until]);+ const history = await versions(b, { slug, known_as_of: after, include_body: true, diff: true });+ expect(shapeOf(history)).toEqual([[purge.id, 'page.purged', true, 'unavailable', 'purged', null], [create!.id, 'page.published', false, 'unavailable', 'purged', iso(purge.recorded_at)]]);+ expect(history.versions.every((v: any) => v.diff === null && v.compiled_truth === undefined && v.title === undefined)).toBe(true);+ const atT = await read(b, { slug, known_as_of: t });+ expect(atT).toMatchObject({ event_id: create!.id, deleted: false, body: 'unavailable', body_reason: 'purged' });+ const leaked = (v: unknown) => ['First draft', 'Second draft', 'purple widgets', 'Lisbon'].filter(s => JSON.stringify(v).includes(s));+ expect(leaked([history, atT])).toEqual([]);+ expect((await refusal(operationsByName.get_page!.handler(remote, { slug, known_as_of: t })))?.code).toBe('page_not_found');+ expect((await refusal(operationsByName.get_versions!.handler(remote, { slug, known_as_of: after, include_body: true, diff: true })))?.code).toBe('page_not_found');+ // Forced probe: a purge that left the revisions in its redacted events would split the purged lifetime into one interval per edit again.+ await b.engine.executeRaw(`UPDATE belief_events SET value = jsonb_build_object('revision_before', NULL, 'revision_after', gen_random_uuid()::text)+ WHERE source_id = $1 AND page_lifetime = $2::uuid AND event_type = 'page.published' AND purged`, [b.sourceId, create!.page_lifetime]);+ expect((await versions(b, { slug, known_as_of: after })).versions).toHaveLength(3);+ }), 120_000);++ test('purge_fact: no historical body or diff returns the purged claim; the surviving claim still reads (control)', () => brain(async b => {+ await b.put(slug, beliefPage({ prose: 'Profile.', facts: ['Acme sells purple widgets', 'Acme opened a Lisbon office'] }));+ await pause();+ await b.put(slug, beliefPage({ prose: 'Profile, edited.', facts: ['Acme sells purple widgets', 'Acme opened a Lisbon office'] }));+ const edited = await at(b);+ const [fact] = await b.engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_id = $1 AND fact = 'Acme opened a Lisbon office' AND expired_at IS NULL ORDER BY id LIMIT 1`, [b.sourceId]);+ const purgeOp = operationsByName.purge_fact!;+ const dry = await purgeOp.handler(b.ctx, { id: Number(fact!.id), dry_run: true }) as Record<string, any>;+ await purgeOp.handler(b.ctx, { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });+ const now = await at(b);+ const remote = { ...b.ctx, remote: true, transport: 'stdio', takesHoldersAllowList: ['world'] } as typeof b.ctx;+ const reads = async (ctx: typeof b.ctx) => [+ await operationsByName.get_page!.handler(ctx, { slug, known_as_of: edited }),+ await operationsByName.get_versions!.handler(ctx, { slug, known_as_of: now, include_body: true, diff: true })];+ for (const ctx of [b.ctx, remote]) {+ const out = JSON.stringify(await reads(ctx));+ expect(out).not.toContain('Lisbon');+ expect(out).toContain('purple widgets');+ }+ // Forced probe: a version the purge failed to redact returns the claim through the historical read.+ await b.engine.executeRaw(`UPDATE page_versions SET compiled_truth = compiled_truth || ' Acme opened a Lisbon office.'+ WHERE page_id = (SELECT id FROM pages WHERE source_id = $1 AND slug = $2)`, [b.sourceId, slug]);+ expect(JSON.stringify(await reads(remote))).toContain('Lisbon');+ }), 180_000);++ test('remote callers: a private page never answers; a page made private hides every interval; one made public shows only what was recorded while world', () => brain(async b => {+ const remote = { ...b.ctx, remote: true, transport: 'stdio', takesHoldersAllowList: ['world'] } as typeof b.ctx;+ const rread = (params: Record<string, unknown>) => operationsByName.get_page!.handler(remote, params) as Promise<Record<string, any>>;+ const rversions = (params: Record<string, unknown>) => operationsByName.get_versions!.handler(remote, params) as Promise<Record<string, any>>;+ const priv = (prose: string) => beliefPage({ prose, frontmatter: { visibility: 'private' } });+ await b.put('companies/secret-example', priv('Secret plans.'));+ await b.put('companies/public-example', draft('Public profile.'));+ await b.put('companies/closing-example', draft('Open at first.'));+ await b.put('companies/opening-example', priv('Private at first.'));+ const t1 = await at(b);+ await b.put('companies/closing-example', priv('Now private.'));+ await b.put('companies/opening-example', draft('Now public.'));+ const t2 = await at(b);+ expect((await rread({ slug: 'companies/public-example', known_as_of: t1 })).compiled_truth).toContain('Public profile.');+ expect((await refusal(rread({ slug: 'companies/secret-example', known_as_of: t2 })))?.code).toBe('page_not_found');+ expect((await refusal(rread({ slug: 'companies/closing-example', known_as_of: t1 })))?.code).toBe('page_not_found');+ expect((await refusal(rversions({ slug: 'companies/closing-example', known_as_of: t2, include_body: true })))?.code).toBe('page_not_found');+ expect((await refusal(rread({ slug: 'companies/opening-example', known_as_of: t1 })))?.code).toBe('page_not_found');+ expect((await rread({ slug: 'companies/opening-example', known_as_of: t2 })).compiled_truth).toContain('Now public.');+ const opened = await rversions({ slug: 'companies/opening-example', known_as_of: t2, include_body: true, diff: true });+ expect(opened.versions).toHaveLength(1);+ expect(JSON.stringify(opened)).not.toContain('Private at first.');+ expect((await read(b, { slug: 'companies/closing-example', known_as_of: t1 })).compiled_truth).toContain('Open at first.');+ // Forced probe: an event recorded while private, relabelled world, would surface the private body to the remote caller.+ await b.engine.executeRaw(`UPDATE belief_events SET visibility = 'world' WHERE source_id = $1 AND slug = 'companies/opening-example'`, [b.sourceId]);+ expect(JSON.stringify(await rversions({ slug: 'companies/opening-example', known_as_of: t2, include_body: true }))).toContain('Private at first.');}), 120_000);});}