Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

GBRA-161 PR 2: deleted-page originGone, publishExtractedFacts (non-user facts never owner facts), deprecations, docs, ratchets

garrytand79bd502bad7
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 740f683202..0d339b7de0 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -6,6 +6,7 @@ src/core/persistence/derived-retirement-hold.ts 2 contract retireDerivedPages ve
src/core/generations/adapters/page.ts 1 contract GBRA-161: importPageItem writes a derived page item through importFromContent inside the generation activation's maintenanceTransaction (publish.ts), behind the canonical table trigger; managed brains keep the coordinator path.
src/core/generations/adapters/atoms.ts 1 contract GBRA-161: the unmanaged atom completion flip (source_hash) runs in the generation activation's maintenanceTransaction after every atom and provenance edge was written and before the items are rechecked live; managed brains keep the coordinator path.
src/core/generations/adapters/fact-rows.ts 1 contract GBRA-161 PR 2: restoreFactRow puts a recorded fact before-state back (lifecycle, consolidation marks, fence row number) only inside a generation restore maintenanceTransaction, matched on id, claim and visibility; managed brains refuse generation restores.
+src/core/generations/adapters/extracted-facts.ts 2 contract GBRA-161 PR 2: the extracted-facts adapter inserts a page's new extracted rows and expires the ones a whole-body result dropped, only inside publishGeneration's maintenanceTransaction under the page key; the ownership rule detaches non-user facts before anything is written.
src/core/persistence/links-maintenance.ts 1 coordinator Managed extract --stale and post-sync extraction add only the coordinator's unrecorded canonical timeline tuples inside a revision-bound withCoordinatedWrite transaction that also replaces the page's derived links and stamps its watermark.
src/core/extract-takes-from-pages.ts 0 coordinator Managed bootstrap submits one revision-checked put_page per source page so its complete takes fence and projected rows commit together; unmanaged writes retain the md-first helper.
src/core/persistence/origin-guard.ts 2 engine_guard #6948 bindOrigin records a page origin (and drops an origin_twin marker) only after assertOriginUnclaimed holds the origin advisory lock inside the caller's engine.transaction(); callers are the guarded publication applies and repairs.
diff --git a/docs/architecture/generations.md b/docs/architecture/generations.md
index 40ae6bb0f9..33d44b7630 100644
--- a/docs/architecture/generations.md
+++ b/docs/architecture/generations.md
@@ -54,6 +54,34 @@ Adapters (`contract.ts`) own one kind each: `adapters/atoms.ts` (atoms, one key
release. An atom's identity leaves out the provenance a managed writer stamps (`source_kind`, `ingested_via`,
`ingested_at`, `trust_tier` and the other content-hash ephemeral keys), so a managed write never reads as an edit.
+### Facts and takes (PR 2)
+
+A page's `## Facts` and takes fences are canonical, so their kinds (`fact_fence`, `take_fence`, one key `page:<slug>`
+each, `generations/fence.ts`) have no shrink floor, valve or item cap: a fence read whole and valid is complete whatever
+its row count, and an empty one retires every row (`fenceParsedEmpty`). Every writer that would retire fence rows (the
+page publication's projection, `extract_facts`, `gbrain extract takes`) calls `publishFenceGeneration` in its own
+transaction, under the page key, before it writes. A fence that is absent, unread or on a segmented page holds
+(`fence_absent`): nothing retires, and doctor `generation_held`, `gbrain sync status` (`fence_holds`) and
+`get_page` (`fence_held`) list the page with an `ask_user` fix naming both outcomes (restore the section to keep the
+rows, or write the exact empty fence it prints to retire them; never a default). The rows of a deleted page expire only
+on `originGone`: the page is gone under its key and the rows came from a fence (a live generation, or a fence in the
+deleted page's stored body); otherwise they are held `no_proof`. Each retired or replaced row's before-state is on the
+ledger. A fence restore (`fence-restore.ts`) writes the earlier generation's fence block into the page as it is now
+through a guarded `put_page` bound to its revision, leaving the body, timeline, tags and the other fence alone, and
+refuses a fence edited since (`edited_since`, `section_moved`).
+
+The dream consolidate phase records each cluster (`consolidation`, key `entity:<slug>:cluster:<ids>`,
+`adapters/fact-rows.ts`): a strict chain records each member's `valid_until`, `consolidated_at` and
+`consolidated_into` before it closes them (unmanaged and managed), a same-instant tie (#6023) is held `tie` with nothing
+written, and `--mode restore` reopens a chain, which the phase then leaves open.
+
+Model-extracted facts publish through `publishExtractedFacts` (`adapters/extracted-facts.ts`, kind `extracted_facts`,
+key `page:<slug>:<writer>`), the path the conversation lane and the facts backstop move onto: a `whole_body` result
+retires what it dropped under the model floor and valve, an `appended_range` result is additive, and an
+assistant-attributed or third-party fact is stored on its source page with no entity, never attached to an entity page
+as an owner fact. `deleteFactsForPage`, `expireFact` and `insertFacts({ deleteForPageFirst })` are deprecated; no
+production code calls them (`test/generations-deprecated-fact-writers.test.ts`).
+
### Managed sources
A managed source (`generations/managed.ts`) never composes a generation in one transaction: every page write is its own
@@ -87,7 +115,7 @@ doctor `atom_retirements_restorable` leaves out an atom whose retirement the led
`--mode restore` (the default) republishes the item set the selected live generation replaced, `--mode release-held`
publishes a held result once (a managed source releases an atom page key through its writer), and `--mode cleanup` lists
pending members and orphan candidates, read-only. A managed source restores retired atoms with `gbrain repair
-atoms-restore`; `--mode restore` refuses there. Doctor reports `generation_retirements` (ok, with the restorable
+atoms-restore`; `--mode restore` refuses there for every kind but the fence kinds, whose restore is a guarded page write. Doctor reports `generation_retirements` (ok, with the restorable
count), `generation_held` (warn) and `generation_pending` (warn).
## Purge
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 7f9a221c64..d17b45d659 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -1528,6 +1528,42 @@ held result waits, with the read-only release preview as its fix;
`generation_retirements` reports what is restorable. Show the user the preview
before running the apply. Managed brains keep their coordinator path for now.
+Facts and takes fences, consolidation chains and extracted facts publish the
+same way (`--kind fact_fence`, `take_fence`, `consolidation`,
+`extracted_facts`; key `page:<slug>` for a fence). A fence restore writes the
+earlier fence block into the page as it is now, through a guarded page write
+that leaves the rest of the page alone; it works on managed brains too, and a
+fence edited since is refused. A consolidation restore reopens the chain's
+`valid_until` and consolidation marks.
+
+#### Fence absent
+
+A page written without its `## Facts` (or takes) section keeps its rows: the
+fact or take generation is held `fence_absent` and nothing is retired. Doctor
+`generation_held`, `gbrain sync status` (`fence_holds`) and `get_page`
+(`fence_held`) list the page with an ask-the-user fix. The user may have deleted
+the whole section on purpose, or an edit may have lost it: ask which.
+
+- To keep the rows, restore the section (from the page's history or the
+ previous version of its file).
+- To retire them, write the empty fence the fix prints into the page; the next
+ write retires every row on it. For facts it is:
+
+```markdown
+## Facts
+
+<!--- gbrain:facts:begin -->
+
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+<!--- gbrain:facts:end -->
+```
+
+A page with no file changes through `get_page` (`include_content: true`) and
+`put_page` with that revision as `expected_revision`; `edit_page` refuses to
+write fence markers. Neither outcome is a default, and nothing changes until the
+user chooses.
+
### Extractor facts
A managed write by a gbrain older than v0.60.11.0 to a conversation page
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index f2e1f9bb10..f9a6927b12 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -613,3 +613,9 @@ src/core/generations/adapters/page.ts preimageMarkdown field NONE reads the body
src/core/generations/adapters/page.ts pageVersionEvidence sql INLINE legacy-adoption evidence: hashes retained page_versions copies of derived atom pages and compares identity hashes only; segmented versions (compiled_truth NULL) are skipped
src/core/generations/adapters/atoms.ts atomGenerationAdapter sql META input size only: body_bytes for a segmented page, octet_length of an inline page columns (pages leave body_bytes NULL inline)
src/core/generations/repair.ts releaseManaged field INLINE assertInlineBody refuses a segmented origin page before the managed release reads its body to bind the origin
+src/core/cycle/extract-facts.ts expireDeletedPageFacts sql INLINE reads the deleted page's stored fence through readFenceBlocks, which reads a segmented page as segmented: no fence proof, so its rows expire only when a live generation recorded them (GBRA-161 PR 2)
+src/core/generations/fence-restore.ts planFenceRestore call:serializePageToMarkdown INLINE a segmented page is refused segmented_unsupported before the page is serialized for the guarded restore write
+src/core/generations/fence-restore.ts planFenceRestore field INLINE a segmented page is refused segmented_unsupported before its fence blocks are read
+src/core/generations/fence.ts readFenceBlocks field INLINE a segmented page reads segmented (held fence_absent) before any body field is read
+src/core/generations/fence.ts fenceInput field NONE reads the fence block strings of a FenceRead (already parsed), never a stored page body
+src/core/generations/fence.ts storedBlocks field NONE reads the fence block strings of a FenceRead (already parsed), never a stored page body
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 5edc37ed68..535c9c62b9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1087,6 +1087,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.348.0', text: 'The background `doctor-refresh` job now queues behind sync, the autopilot cycles, global maintenance, embed backfill and loops extract (priority 10), and measures for at most 10 minutes: past that it starts no further check, records what it finished and completes, and the rest stays unknown until the next hourly refresh. Its timeout drops from 2 hours to 15 minutes. `gbrain config set doctor.background_refresh false` stops doctor from queueing it.' },
{ since: 'TBD', text: 'Pages a derived writer retires (an atom a completed re-extraction no longer produces, a chronicle event a re-judged meeting no longer yields, an atom `gbrain repair stale-atoms` retired) now stay restorable for 30 days instead of 72 hours: the purge, automatic and `gbrain pages purge-deleted` alike, skips a page stamped `retired_by` extract-atoms, managed-reextract, stale-atoms or life-chronicle until 30 days after its deletion, and `gbrain restore <slug>` brings it back with its body. The unmanaged extract_atoms and chronicle retirements now save a page version first and stamp the page. A remote page write that adds or changes `retired_by`, `retired_at` or `retired_generation` is refused with `reserved_frontmatter_key`; carrying the stored value unchanged, or dropping the key, still writes.' },
{ since: 'TBD', text: 'Unmanaged atom extraction now publishes each page\'s or transcript\'s atoms as one generation: the atoms, their provenance edges and the completion stamp land together or not at all (a failed write leaves no provisional atom), and the atoms a complete re-extraction no longer produces are retired in the same transaction. A re-extraction that would keep fewer than half of an origin\'s atoms (`generations.shrink_floor`), retire them all without proof the input is empty, change more than 64 atoms (`generations.max_items`) or trip the retirement valve is held instead: nothing changes, doctor `generation_held` warns, and `gbrain repair generations --kind atom --mode release-held --held` previews it. An atom from before this release is retired only when the extraction reproduces it or a retained page version the extractor wrote shows it unedited; a hand-written or hand-edited atom naming the origin stays live. `gbrain repair generations --kind atom --since 30d` previews restoring what a generation replaced. The derived purge hold now follows `generations.restore_days` (default 30).' },
+ { since: 'TBD', text: 'A page write whose body no longer has its `## Facts` or takes section no longer expires or deletes the rows that section held (GBRA-161 PR 2): the page projection, `extract_facts` and `gbrain extract takes` keep them live and record a held generation (`generation_held`, reason `fence_absent`). Doctor `generation_held`, `gbrain sync status` (new `fence_holds`) and `get_page` (new `fence_held`) list the page with an ask-the-user fix: restore the section to keep the rows, or write the exact empty fence it prints to retire them. An empty fence (begin and end markers, no rows) still retires every row, and an edit that removes some rows retires exactly those, with no shrink floor; each retired or replaced row\'s before-state is recorded and `gbrain repair generations --kind fact_fence|take_fence --mode restore` puts the earlier fence block back into the page as it is now.' },
+ { since: 'TBD', text: 'The facts of a soft-deleted page now expire only when the page is still deleted under its page key and its rows came from a fence (a recorded generation, or a fence in the deleted page\'s stored body), one transaction per page (GBRA-161 PR 2); rows no fence derived are kept and held `no_proof`. Dream consolidation now records each cluster\'s `valid_until`, `consolidated_at` and `consolidated_into` before it closes it, records a same-instant tie (#6023) as a held generation (`tie`), and `gbrain repair generations --kind consolidation --mode restore` reopens a chain, which later runs leave open.' },
{ since: 'TBD', text: 'A fact that replaces another (`remember` with `replaces`, a near-duplicate supersession, or a published facts batch that supersedes) now also closes the retired fact\'s `valid_until` at the new fact\'s `valid_from`, in the database row and in its struck facts-fence row, so as-of reads no longer see the retired fact as current for the time between (#7214). A backdated replacement, starting on or before the retired fact, leaves the retired interval as it was.' },
{ since: 'TBD', text: 'A facts-fence row with no `valid_from` cell now takes the page\'s stated date (frontmatter `event_date`, `date` or `published`, or a dated filename) on every write path: `put_page`, sync and import used to store the write time, and `extract_facts` used the page\'s creation or import time when the page stated no date (#7247). A page that states no date leaves such rows at the time they were recorded. Rows already stored keep their dates.' },
// GBRA-60 small-items wave (#7026 part 2, #7234). `since` is stamped at the merge slot.
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 2f96afff23..1762299636 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -84,6 +84,7 @@ import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.t
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { factsFenceView } from '../facts-fence.ts';
import { publishFenceGeneration, readFenceBlocks, FACT_FENCE_KIND, type FenceRead } from '../generations/fence.ts';
+import type { BodyStorage } from '../page-body/types.ts';
import { factFenceItems, factPreimages, factRetireItem } from '../generations/adapters/fact-rows.ts';
import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../page-body/segment-facts.ts';
import {
@@ -649,7 +650,9 @@ async function expireDeletedPageFacts(tx: BrainEngine, sourceId: string, slug: s
AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ($3::integer IS NULL OR p.id = $3::integer) AND p.deleted_at IS NOT NULL)`,
[sourceId, slug, pageId])).map(r => Number(r.id));
if (!ids.length) return [];
- const generation = await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId, slug, read: { state: 'absent' }, items: [], originGone: true,
+ const [stored] = await tx.executeRaw<{ compiled_truth: string | null; timeline: string | null; body_storage: BodyStorage | null }>(
+ 'SELECT compiled_truth, timeline, body_storage FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NOT NULL ORDER BY id DESC LIMIT 1', [sourceId, slug]);
+ const generation = await publishFenceGeneration(tx, { kind: FACT_FENCE_KIND, sourceId, slug, read: stored ? readFenceBlocks(stored, 'facts') : { state: 'absent' }, items: [], originGone: true,
retire: (await factPreimages(tx, sourceId, ids)).map(factRetireItem), writer: 'deleted_page' });
if (generation.state !== 'published') return [];
return (await tx.executeRaw<{ id: number }>('UPDATE facts SET expired_at = now() WHERE source_id = $1 AND id = ANY($2::bigint[]) AND expired_at IS NULL RETURNING id',
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index cc0d7087f3..106e4d7b64 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -270,14 +270,8 @@ export async function runPhaseConsolidate(
for (const cluster of clusters) {
if (cluster.length < 2) continue;
const tie = clusterTie(cluster, claims);
- if (tie) {
- clustersHeldSameInstant += 1;
- if (sameInstantClusters.length < SAME_INSTANT_SAMPLES) sameInstantClusters.push(heldCluster(b, tie));
- if (recordsTies) await engine.transaction(tx => holdConsolidationTie(tx, b.source_id, b.entity_slug, cluster.map(f => f.id),
- { entity_slug: b.entity_slug, tied: tie.ids, valid_from: new Date(tie.at).toISOString(), metric: tie.metric }));
- continue;
- }
- if (await consolidationRestored(engine, b.source_id, b.entity_slug, cluster.map(f => f.id))) continue;
+ if (tie) { clustersHeldSameInstant += 1; if (sameInstantClusters.length < SAME_INSTANT_SAMPLES) sameInstantClusters.push(heldCluster(b, tie)); if (recordsTies) await recordTie(engine, b, cluster, tie); continue; }
+ if (await consolidationRestored(engine, b.source_id, b.entity_slug, cluster.map(f => f.id))) continue; // the operator reopened this chain
// Take selection: pick the highest-confidence fact's text as the
// take claim (v0.31 deterministic). v0.32 will swap to a Sonnet
// synthesis pass.
@@ -390,10 +384,7 @@ export async function runPhaseConsolidate(
if (gate) await recordFlaggedRow(tx, gate, { table: 'takes', id: takeId, sourceId: b.source_id });
}
- const before = await factPreimages(tx, b.source_id, cluster.map(f => f.id));
- for (const f of cluster) await tx.consolidateFact(f.id, takeId);
- await writeValidUntilChain(tx, cluster);
- await recordConsolidationGeneration(tx, b.source_id, b.entity_slug, before);
+ await closeCluster(tx, b, cluster, takeId);
return { result: { created, takeId }, rows: [{ table: 'takes' as const, id: Number(takeId), sourceId: b.source_id }] };
});
if (written?.created) nextRowNum += 1;
@@ -480,6 +471,23 @@ function clusterTie(cluster: FactRow[], claims: Map<number, ClaimShape>): SameIn
unit: claims.get(f.id)?.unit ?? null, period: claims.get(f.id)?.period ?? null })))[0];
}
+/**
+ * Marks the cluster consolidated into `takeId` and closes its chain, recording each member's before-state as the cluster's
+ * consolidation generation first (GBRA-161 PR 2), so `gbrain repair generations --kind consolidation` can reopen it.
+ */
+async function closeCluster(tx: BrainEngine, bucket: { source_id: string; entity_slug: string }, cluster: FactRow[], takeId: number): Promise<void> {
+ const before = await factPreimages(tx, bucket.source_id, cluster.map(f => f.id));
+ for (const f of cluster) await tx.consolidateFact(f.id, takeId);
+ await writeValidUntilChain(tx, cluster);
+ await recordConsolidationGeneration(tx, bucket.source_id, bucket.entity_slug, before);
+}
+
+/** #6023 (GBRA-161 PR 2): records a tied cluster as a held consolidation generation (`tie`); nothing is written to its facts. */
+async function recordTie(engine: BrainEngine, bucket: { source_id: string; entity_slug: string }, cluster: FactRow[], tie: SameInstantTie): Promise<void> {
+ await engine.transaction(tx => holdConsolidationTie(tx, bucket.source_id, bucket.entity_slug, cluster.map(f => f.id),
+ { entity_slug: bucket.entity_slug, tied: tie.ids, valid_from: new Date(tie.at).toISOString(), metric: tie.metric }));
+}
+
function heldCluster(bucket: { source_id: string; entity_slug: string }, tie: SameInstantTie): SameInstantCluster {
const validFrom = new Date(tie.at).toISOString();
const claim = [tie.metric, tie.unit, tie.period].filter(Boolean).join(', ');
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 885dc7cd20..47b624890b 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2201,8 +2201,8 @@ export interface BrainEngine {
* self-commits, so an insert throw would permanently lose the page's
* facts.) `slug` / `excludeSourcePrefixes` / `preserveExpiredLegacy`
* mirror `deleteFactsForPage`; the deleted count is returned as
- * `deleted`. Callers that omit it get the standalone insert
- * (deleted: 0), unchanged.
+ * `deleted`. Callers that omit it get the standalone insert (deleted: 0), unchanged.
+ * `opts.deleteForPageFirst` is deprecated (GBRA-161 PR 2, test/generations-deprecated-fact-writers.test.ts).
*/
insertFacts(
rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number }>,
@@ -2248,8 +2248,8 @@ export interface BrainEngine {
* this does NOT promise: it protects the record, not the forget itself —
* if the fence still carries the same claim, fence canonicality
* independently reinserts it as a fresh active row (legacy DB-only
- * forgets are documented as non-durable; see extract-facts.ts). Omitted
- * ⇒ legacy behavior.
+ * forgets are documented as non-durable; see extract-facts.ts). Omitted ⇒ legacy behavior.
+ * @deprecated GBRA-161 PR 2: retire through publishFenceGeneration / publishExtractedFacts (docs/architecture/generations.md).
*/
deleteFactsForPage(
slug: string,
@@ -2260,6 +2260,7 @@ export interface BrainEngine {
/**
* Mark a fact expired. Never DELETE. Returns true iff a row was updated.
* Idempotent-as-false (already expired returns false without changing state).
+ * @deprecated GBRA-161 PR 2: retire through publishFenceGeneration / publishExtractedFacts (docs/architecture/generations.md).
*/
expireFact(id: number, opts?: { supersededBy?: number; at?: Date }): Promise<boolean>;
diff --git a/src/core/generations/adapters/extracted-facts.ts b/src/core/generations/adapters/extracted-facts.ts
new file mode 100644
index 0000000000..53a7829659
--- /dev/null
+++ b/src/core/generations/adapters/extracted-facts.ts
@@ -0,0 +1,131 @@
+/**
+ * GBRA-161 PR 2: model-extracted facts on the generation primitive (kind `extracted_facts`, one owner key per source page
+ * and writer). This is the publish path the conversation lane and the facts backstop move onto (GBRA-60):
+ * `publishExtractedFacts`.
+ *
+ * - Coverage: a result that read the whole page (`whole_body`) is complete, so the rows it no longer has retire, each
+ * with its before-state on the ledger, under the model-produced shrink floor and valve; an empty `whole_body` result
+ * retires nothing without a proof (`no_proof`). A result over an appended range (`appended_range`) is additive: it
+ * writes its rows and retires nothing.
+ * - Ownership: an assistant-attributed or third-party fact (`attributed_to` `assistant` or `other`) is never attached
+ * to an entity page as an owner fact. Whatever subject the extractor or subject inference gave it, it is stored on the
+ * page it was extracted from with no entity, and the outcome lists it under `detached`.
+ */
+import type { BrainEngine, NewFact } from '../../engine.ts';
+import { digest } from '../../persistence/digest.ts';
+import type { GenerationAdapter, GenerationKey, InputState, ItemRow, ProposedItem } from '../contract.ts';
+import { publishGeneration, type PublishOutcome } from '../publish.ts';
+import { factPreimages, restoreFactRow, type FactPreimage } from './fact-rows.ts';
+
+export const EXTRACTED_FACTS_KIND = 'extracted_facts';
+export type ExtractedFactsWriter = 'conversation' | 'backstop';
+/** What the producer read: the whole page, or only a range appended since its last run. Only `whole_body` may retire. */
+export type ExtractionCoverage = 'whole_body' | 'appended_range';
+
+const SOURCE_PREFIX: Record<ExtractedFactsWriter, string> = { conversation: 'cli:extract-conversation-facts', backstop: 'backstop:extracted-facts' };
+
+export interface ExtractedFactsRequest {
+ sourceId: string;
+ /** The page the facts were extracted from (a conversation, a captured turn). */
+ slug: string;
+ writer: ExtractedFactsWriter;
+ coverage: ExtractionCoverage;
+ /** The page as the producer read it (`pin` changes whenever it does); activation refuses when it moved. */
+ input: InputState;
+ facts: ReadonlyArray<Omit<NewFact, 'source'> & { source?: string }>;
+ runId?: string;
+}
+
+export type ExtractedFactsOutcome = PublishOutcome & { detached: Array<{ fact: string; entity_slug: string; attributed_to: 'assistant' | 'other' }> };
+
+type StoredFact = Omit<NewFact, 'valid_from' | 'valid_until'> & { valid_from?: string | null; valid_until?: string | null };
+
+const ownerKey = (slug: string, writer: ExtractedFactsWriter) => `page:${slug}:${writer}`;
+const parseOwner = (key: GenerationKey) => {
+ const writer = key.ownerKey.slice(key.ownerKey.lastIndexOf(':') + 1) as ExtractedFactsWriter;
+ return { slug: key.ownerKey.slice('page:'.length, key.ownerKey.lastIndexOf(':')), writer, prefix: SOURCE_PREFIX[writer] };
+};
+const identityOf = (row: { fact: string; visibility?: string | null; entity_slug?: string | null; attributed_to?: string | null }) =>
+ digest(['extracted-fact-v1', row.fact, row.visibility ?? 'private', row.entity_slug ?? null, row.attributed_to ?? null]).slice(0, 32);
+const itemKeyOf = (row: Parameters<typeof identityOf>[0]) => `fact:${identityOf(row)}`;
+
+/** The ownership rule, applied before anything is keyed or written. */
+function placeFacts(request: ExtractedFactsRequest): { rows: StoredFact[]; detached: ExtractedFactsOutcome['detached'] } {
+ const detached: ExtractedFactsOutcome['detached'] = [];
+ const rows = request.facts.map(fact => {
+ const { valid_from, valid_until, ...rest } = fact;
+ const row: StoredFact = { ...rest, source: fact.source ?? SOURCE_PREFIX[request.writer], valid_from: valid_from ? valid_from.toISOString() : null,
+ valid_until: valid_until ? valid_until.toISOString() : null };
+ const attribution = fact.attributed_to;
+ if ((attribution === 'assistant' || attribution === 'other') && fact.entity_slug && fact.entity_slug !== request.slug) {
+ detached.push({ fact: fact.fact, entity_slug: fact.entity_slug, attributed_to: attribution });
+ return { ...row, entity_slug: null, context: [fact.context, `entity ${fact.entity_slug} not attached: ${attribution}-attributed`].filter(Boolean).join('; ') };
+ }
+ return row;
+ });
+ return { rows, detached };
+}
+
+async function storedRows(engine: BrainEngine, key: GenerationKey): Promise<FactPreimage[]> {
+ const { slug, prefix } = parseOwner(key);
+ const ids = (await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND COALESCE(source,'') LIKE $3 ORDER BY id`, [key.sourceId, slug, `${prefix}%`])).map(row => Number(row.id));
+ return factPreimages(engine, key.sourceId, ids);
+}
+
+export const extractedFactsAdapter: GenerationAdapter<{ input: InputState }> = {
+ kind: EXTRACTED_FACTS_KIND,
+ retiredBy: 'generation-restore',
+ modelProduced: true,
+ lockKeys: key => [{ sourceId: key.sourceId, slug: parseOwner(key).slug }],
+ async readInput(engine, key, context) {
+ const [page] = await engine.executeRaw<{ live: boolean }>('SELECT deleted_at IS NULL AS live FROM pages WHERE source_id=$1 AND slug=$2 ORDER BY deleted_at NULLS FIRST LIMIT 1',
+ [key.sourceId, parseOwner(key).slug]);
+ return page?.live ? context?.input ?? null : null;
+ },
+ async readItems(engine, key) {
+ const out = new Map<string, ItemRow>();
+ for (const row of await storedRows(engine, key)) {
+ const itemKey = itemKeyOf(row);
+ const live = row.expired_at === null;
+ if (out.get(itemKey)?.live && !live) continue;
+ out.set(itemKey, { key: itemKey, identityHash: identityOf(row), live, owned: true, segmented: false,
+ preimage: () => ({ json: row as unknown as Record<string, unknown>, bytes: JSON.stringify(row).length }) });
+ }
+ return out;
+ },
+ legacyEvidence: async () => new Set(),
+ async publishItems(tx, key, items: readonly ProposedItem[]) {
+ const { slug } = parseOwner(key);
+ const [max] = await tx.executeRaw<{ n: number | null }>('SELECT MAX(row_num)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [key.sourceId, slug]);
+ let rowNum = Number(max?.n ?? 0);
+ const rows = items.map(item => {
+ const { valid_from, valid_until, ...stored } = JSON.parse(item.content) as StoredFact;
+ return { ...stored, source: stored.source, row_num: ++rowNum, source_markdown_slug: slug,
+ ...(valid_from ? { valid_from: new Date(valid_from) } : {}), ...(valid_until ? { valid_until: new Date(valid_until) } : {}) } as NewFact & { row_num: number; source_markdown_slug: string };
+ });
+ if (rows.length) await tx.insertFacts(rows, { source_id: key.sourceId }); // gbrain-allow-direct-insert: extracted-facts generation activation, inside its maintenance transaction
+ },
+ async retireItems(tx, key, itemKeys) {
+ if (!itemKeys.length) return;
+ const wanted = new Set(itemKeys);
+ const ids = (await storedRows(tx, key)).filter(row => row.expired_at === null && wanted.has(itemKeyOf(row))).map(row => Number(row.id));
+ if (ids.length) await tx.executeRaw('UPDATE facts SET expired_at = now() WHERE source_id=$1 AND id = ANY($2::bigint[]) AND expired_at IS NULL', [key.sourceId, ids]);
+ },
+ async restoreItem(tx, key, _itemKey, preimage) {
+ if (!await restoreFactRow(tx, key.sourceId, preimage)) throw new Error(`extracted fact ${String(preimage.id)} changed; nothing restored`);
+ },
+ preimageIdentity: preimage => identityOf(preimage as unknown as Parameters<typeof identityOf>[0]),
+};
+
+/**
+ * GBRA-60 entry point: publishes one page's extracted facts as a generation of `writer` on that page. Call it
+ * with the whole result of one extraction and the page input it read; `coverage` says whether that was the whole page.
+ */
+export async function publishExtractedFacts(engine: BrainEngine, request: ExtractedFactsRequest): Promise<ExtractedFactsOutcome> {
+ const { rows, detached } = placeFacts(request);
+ const items = [...new Map(rows.map(row => [itemKeyOf(row), { key: itemKeyOf(row), content: JSON.stringify(row), identityHash: identityOf(row) }])).values()];
+ const outcome = await publishGeneration(engine, extractedFactsAdapter, { key: { kind: EXTRACTED_FACTS_KIND, sourceId: request.sourceId, ownerKey: ownerKey(request.slug, request.writer) },
+ items, input: request.input, partial: request.coverage === 'appended_range', runId: request.runId, context: { input: request.input } });
+ return { ...outcome, detached };
+}
diff --git a/src/core/generations/adapters/fact-rows.ts b/src/core/generations/adapters/fact-rows.ts
index b6678d8463..0268de835b 100644
--- a/src/core/generations/adapters/fact-rows.ts
+++ b/src/core/generations/adapters/fact-rows.ts
@@ -25,10 +25,10 @@ export const CONSOLIDATION_KIND = 'consolidation';
/** The columns a fact's before-state keeps. */
const FACT_PREIMAGE_SQL = `jsonb_build_object('id', f.id, 'row_num', f.row_num, 'fact', f.fact, 'visibility', f.visibility, 'kind', f.kind,
'entity_slug', f.entity_slug, 'source', f.source, 'expired_at', f.expired_at, 'valid_from', f.valid_from, 'valid_until', f.valid_until,
- 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into)`;
+ 'superseded_by', f.superseded_by, 'consolidated_at', f.consolidated_at, 'consolidated_into', f.consolidated_into, 'attributed_to', f.attributed_to)`;
export type FactPreimage = { id: number; row_num: number | null; fact: string; visibility: string; expired_at: string | null; valid_until: string | null;
- superseded_by: number | null; consolidated_at: string | null; consolidated_into: number | null };
+ superseded_by: number | null; consolidated_at: string | null; consolidated_into: number | null; entity_slug: string | null; attributed_to: string | null };
/** The fence rows of the new generation (one per row number; a duplicate number keeps its first row, as the reconcile does). */
export function factFenceItems(rows: ReadonlyArray<{ row_num: number; fact: string; visibility?: string | null }>): FenceItem[] {
diff --git a/src/core/generations/adapters/index.ts b/src/core/generations/adapters/index.ts
index c84dde3cc6..5ac78fce1a 100644
--- a/src/core/generations/adapters/index.ts
+++ b/src/core/generations/adapters/index.ts
@@ -6,8 +6,9 @@ import type { GenerationAdapter } from '../contract.ts';
import { atomGenerationAdapter } from './atoms.ts';
import { consolidationAdapter, factFenceAdapter } from './fact-rows.ts';
import { takeFenceAdapter } from './take-rows.ts';
+import { extractedFactsAdapter } from './extracted-facts.ts';
-const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, factFenceAdapter, takeFenceAdapter, consolidationAdapter]
+const adapters = new Map<string, GenerationAdapter<unknown>>([atomGenerationAdapter, factFenceAdapter, takeFenceAdapter, consolidationAdapter, extractedFactsAdapter]
.map(adapter => [adapter.kind, adapter as GenerationAdapter<unknown>]));
export function generationAdapter(kind: string): GenerationAdapter<unknown> | undefined { return adapters.get(kind); }
diff --git a/src/core/generations/fence-restore.ts b/src/core/generations/fence-restore.ts
index ea6e72b63d..27597d0333 100644
--- a/src/core/generations/fence-restore.ts
+++ b/src/core/generations/fence-restore.ts
@@ -33,6 +33,7 @@ export async function planFenceRestore(db: BrainEngine, key: GenerationKey, live
const slug = fenceSlugOf(key.ownerKey);
const snapshot = slug ? await db.readPageSnapshot(slug, { sourceId: key.sourceId }) : null;
if (!snapshot || snapshot.page.deleted_at) return refuse('page_gone');
+ if (snapshot.page.body_storage === 'segmented') return refuse('segmented_unsupported');
const read = readFenceBlocks(snapshot.page, fenceName(key.kind as FenceGenerationKind));
if (read.state !== 'parsed' || read.blocks.body !== recorded.body || read.blocks.timeline !== recorded.timeline) return refuse('edited_since');
let content = serializePageToMarkdown(snapshot.page, await db.getTags(slug!, { sourceId: key.sourceId }));
diff --git a/src/core/generations/fence.ts b/src/core/generations/fence.ts
index 97d4e81c9b..6dff6be40a 100644
--- a/src/core/generations/fence.ts
+++ b/src/core/generations/fence.ts
@@ -15,6 +15,7 @@ import type { Action } from '../agent-output.ts';
import type { BrainEngine } from '../engine.ts';
import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../facts-fence.ts';
import { locateOutsideCode } from '../fence-scan.ts';
+import type { BodyStorage } from '../page-body/types.ts';
import { digest } from '../persistence/digest.ts';
import { renderTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';
import { readGenerationsConfig } from './config.ts';
@@ -39,8 +40,9 @@ export const fenceName = (kind: FenceGenerationKind) => kind === FACT_FENCE_KIND
export interface FenceBlocks { body: string | null; timeline: string | null }
export type FenceRead = { state: 'parsed'; blocks: FenceBlocks } | { state: 'absent' | 'unread' | 'segmented' };
-/** The page's `fence` blocks outside markdown code, or `absent` when neither section holds one. */
-export function readFenceBlocks(page: { compiled_truth: string | null; timeline?: string | null }, fence: 'facts' | 'takes'): FenceRead {
+/** The page's `fence` blocks outside markdown code, or `absent` when neither section holds one; a segmented page is never read whole. */
+export function readFenceBlocks(page: { compiled_truth: string | null; timeline?: string | null; body_storage?: BodyStorage | null }, fence: 'facts' | 'takes'): FenceRead {
+ if (page.body_storage === 'segmented') return { state: 'segmented' };
const [begin, end] = fence === 'facts' ? [FACTS_FENCE_BEGIN, FACTS_FENCE_END] : [TAKES_FENCE_BEGIN, TAKES_FENCE_END];
const block = (text: string | null | undefined) => {
const { beginIdx, endIdx } = locateOutsideCode(text ?? '', begin, end);
@@ -71,7 +73,10 @@ export interface FenceGenerationRequest {
retire: readonly FenceItem[];
/** Stored rows the writer overwrites in place with a different identity (a take replaced at its row number). */
overwrite?: readonly FenceItem[];
- /** The page is deleted: its rows retire on `originGone`, rechecked here. */
+ /**
+ * The page is deleted: its rows retire on `originGone`, rechecked here: the page is gone under the caller's key, and the
+ * rows were derived from a fence (a live generation, or `read` of the deleted page's stored body parses one).
+ */
originGone?: boolean;
/** Which writer published (projection, extract_facts, extract_takes, deleted_page, restore). */
writer: string;
@@ -131,7 +136,7 @@ export async function publishFenceGeneration(tx: BrainEngine, request: FenceGene
let proof: string | null = null;
if (request.retire.length) {
if (request.originGone) {
- if (!await originGoneNow(tx, request.sourceId, request.slug)) return hold('no_proof');
+ if (!await originGoneNow(tx, request.sourceId, request.slug) || (!live && request.read.state !== 'parsed')) return hold('no_proof');
proof = 'originGone';
} else if (request.read.state !== 'parsed') {
return hold('fence_absent');
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 6d15c77f2c..efed43fe66 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -27,7 +27,6 @@ import { isAutoLinkEnabled } from '../link-extraction.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import { getContentFlag } from '../quarantine.ts';
import { fileHeldField, readHeldPages } from '../persistence/held-reads.ts';
-import { fenceHoldEntries } from '../generations/fence.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';
import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
@@ -227,9 +226,7 @@ const get_page: Operation = {
// Read-only, over the same visibility-filtered body the reader gets.
const lineGrammar = p.grammar_diagnostics !== true ? undefined : await (await import('../line-grammar-report.ts')).grammarDiagnosticsForPage(ctx.engine, page, visibleBody);
const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259
- const fenceHolds = await fenceHoldEntries(ctx.engine, [page.source_id], { slug: page.slug }).catch(() => []);
- const fileHeld = { ...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}),
- ...(fenceHolds.length ? { fence_held: fenceHolds.map(({ source_id: _source, slug: _slug, ...hold }) => hold) } : {}) };
+ const fenceHeld = (await (await import('../generations/fence.ts')).fenceHoldEntries(ctx.engine, [page.source_id], { slug: page.slug }).catch(() => [])).map(({ source_id: _s, slug: _g, ...hold }) => hold); const fileHeld = { ...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}), ...(fenceHeld.length ? { fence_held: fenceHeld } : {}) };
const segmented = isSegmentedPage(page);
const pin = authorizedReadPin(ctx, page, snapshot!.bodyGeneration, p.min_trust, () => pageNotFoundError(ctx, slug, { includeDeleted, sourceIdParam }));
const whole = bodyRequest.mode === 'full'
diff --git a/test/eval-contradictions/no-valid-until-write.test.ts b/test/eval-contradictions/no-valid-until-write.test.ts
index 25dcda83f8..5e60c0d91a 100644
--- a/test/eval-contradictions/no-valid-until-write.test.ts
+++ b/test/eval-contradictions/no-valid-until-write.test.ts
@@ -70,6 +70,11 @@ import { join } from 'node:path';
// reopens (valid_until back to NULL) only the preview-approved facts the
// pre-#6023 consolidate writeback closed at their own instant; local CLI,
// explicit-only, and the contradiction probe never calls it.
+// - generations/adapters/fact-rows.ts (GBRA-161 PR 2) — `restoreFactRow`
+// writes back a fact's recorded before-state (valid_until included) only in
+// a preview-approved `gbrain repair generations --mode restore` of a
+// consolidation chain or a fence generation; local CLI, and the
+// contradiction probe never calls it.
const VALID_UNTIL_WRITE_ALLOWLIST: ReadonlySet<string> = new Set([
'src/core/cycle/extract-facts.ts',
'src/core/cycle/phases/consolidate.ts',
@@ -79,6 +84,7 @@ const VALID_UNTIL_WRITE_ALLOWLIST: ReadonlySet<string> = new Set([
'src/core/facts/proposal-supersede.ts',
'src/core/facts/withdrawal.ts',
'src/core/facts/withdrawal-schema.ts',
+ 'src/core/generations/adapters/fact-rows.ts',
'src/core/persistence/canonical-projections.ts',
'src/core/persistence/facts-prepare.ts', // #7214: a published supersession closes the retired interval (supersededValidUntil)
'src/core/persistence/loop-fact-retirement.ts',
diff --git a/test/generations-deprecated-fact-writers.test.ts b/test/generations-deprecated-fact-writers.test.ts
new file mode 100644
index 0000000000..9d6eea7c80
--- /dev/null
+++ b/test/generations-deprecated-fact-writers.test.ts
@@ -0,0 +1,29 @@
+/**
+ * GBRA-161 PR 2: `deleteFactsForPage`, `expireFact` and `insertFacts({ deleteForPageFirst })` retire facts with no proof
+ * and no before-state, so they are deprecated: fence rows retire through `publishFenceGeneration`, extracted rows through
+ * `publishExtractedFacts`. Only the engine layers that implement them may name them; a new production caller fails here.
+ */
+import { expect, test } from 'bun:test';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const root = join(import.meta.dir, '..');
+const IMPLEMENTERS = new Set(['src/core/engine.ts', 'src/core/engine-sql/facts.ts', 'src/core/pglite-engine.ts', 'src/core/postgres-engine.ts']);
+const CALL = /\.(?:deleteFactsForPage|expireFact)\s*\(|\bdeleteForPageFirst\s*:/g;
+
+function files(directory: string): string[] {
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? files(join(directory, entry.name))
+ : entry.name.endsWith('.ts') ? [join(directory, entry.name)] : []);
+}
+
+test('no production code calls the deprecated fact writers', () => {
+ const callers = files(join(root, 'src')).map(path => relative(root, path)).filter(path => !IMPLEMENTERS.has(path))
+ .flatMap(path => [...readFileSync(join(root, path), 'utf8').matchAll(CALL)].map(match => `${path}: ${match[0]}`));
+ expect(callers, 'Retire facts through publishFenceGeneration or publishExtractedFacts (docs/architecture/generations.md).').toEqual([]);
+});
+
+test('the guard sees a planted call', () => {
+ expect('await engine.deleteFactsForPage(slug, sourceId)'.match(CALL)).toHaveLength(1);
+ expect('await tx.expireFact (id)'.match(CALL)).toHaveLength(1);
+ expect('insertFacts(rows, ctx, { deleteForPageFirst: { slug } })'.match(CALL)).toHaveLength(1);
+});
diff --git a/test/pathological/g2-extracted-facts.test.ts b/test/pathological/g2-extracted-facts.test.ts
new file mode 100644
index 0000000000..1702855f91
--- /dev/null
+++ b/test/pathological/g2-extracted-facts.test.ts
@@ -0,0 +1,79 @@
+/**
+ * GBRA-161 PR 2, for GBRA-60: `publishExtractedFacts`, the generation publish path of the conversation lane and the facts
+ * backstop. An assistant-attributed or third-party fact is never attached to an entity page as an owner fact, even when
+ * subject inference attached it; only a `whole_body` result retires, an `appended_range` one is additive, and an empty
+ * whole-body result retires nothing without a proof. PGLite; Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { inferConversationSubjects } from '../../src/core/facts/conversation-subject-infer.ts';
+import { publishExtractedFacts } from '../../src/core/generations/adapters/extracted-facts.ts';
+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';
+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { pathologicalArms } from './harness.ts';
+
+const CHAT = 'conversations/chat-example';
+const ALICE = 'people/alice-example';
+
+async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-g2x-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ _resetWriteThroughCacheForTest();
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ await engine.executeRaw(`INSERT INTO pages(slug,type,title) VALUES($1,'person','Alice Example'),($2,'conversation','Chat Example') ON CONFLICT DO NOTHING`, [ALICE, CHAT]);
+ await run(engine);
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+const live = (engine: BrainEngine) => engine.executeRaw<{ fact: string; entity_slug: string | null }>(
+ 'SELECT fact, entity_slug FROM facts WHERE source_markdown_slug=$1 AND expired_at IS NULL ORDER BY fact', [CHAT]);
+const fact = (text: string, attributed_to: 'user' | 'assistant' | 'other' = 'user') => ({ fact: text, visibility: 'world' as const, entity_slug: null as string | null, attributed_to });
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`GBRA-161 PR 2 extracted facts (${backend})`, () => {
+ test('an assistant-attributed or third-party fact inference attached is stored with no entity, never as an owner fact', async () => {
+ await withBrain(databaseUrl, async engine => {
+ const inferred = await inferConversationSubjects(engine, 'default', 'world', [fact('Alice Example prefers green tea.', 'assistant'),
+ fact('Alice Example plays chess every week.', 'other'), fact('Alice Example joined acme-example.')]);
+ expect(inferred.map(row => row.entity_slug)).toEqual([ALICE, ALICE, ALICE]);
+ const outcome = await publishExtractedFacts(engine, { sourceId: 'default', slug: CHAT, writer: 'conversation', coverage: 'whole_body',
+ input: { pin: 'chat-v1', size: 100 }, facts: inferred });
+ expect(outcome.state).toBe('published');
+ expect(outcome.detached.map(row => [row.attributed_to, row.entity_slug])).toEqual([['assistant', ALICE], ['other', ALICE]]);
+ expect(await live(engine)).toEqual([{ fact: 'Alice Example joined acme-example.', entity_slug: ALICE },
+ { fact: 'Alice Example plays chess every week.', entity_slug: null }, { fact: 'Alice Example prefers green tea.', entity_slug: null }]);
+ expect((await engine.executeRaw('SELECT 1 FROM facts WHERE entity_slug=$1 AND attributed_to IN (\'assistant\',\'other\')', [ALICE])).length).toBe(0);
+ });
+ }, 120_000);
+
+ test('only a whole_body result retires (with before-state); appended_range is additive; an empty whole_body result is held no_proof', async () => {
+ await withBrain(databaseUrl, async engine => {
+ const publish = (coverage: 'whole_body' | 'appended_range', pin: string, facts: string[]) => publishExtractedFacts(engine, { sourceId: 'default', slug: CHAT,
+ writer: 'conversation', coverage, input: { pin, size: 100 }, facts: facts.map(text => fact(text)) });
+ expect((await publish('whole_body', 'v1', ['Claim A.', 'Claim B.'])).state).toBe('published');
+ expect((await publish('appended_range', 'v2', ['Claim C.'])).state).toBe('published');
+ expect((await live(engine)).map(row => row.fact)).toEqual(['Claim A.', 'Claim B.', 'Claim C.']);
+ expect((await publish('appended_range', 'v3', [])).state).not.toBe('held');
+ expect((await live(engine)).map(row => row.fact)).toEqual(['Claim A.', 'Claim B.', 'Claim C.']);
+ const shrink = await publish('whole_body', 'v4', ['Claim A.', 'Claim B.']);
+ expect(shrink).toMatchObject({ state: 'published', retired: [expect.stringMatching(/^fact:/)] });
+ expect((await live(engine)).map(row => row.fact)).toEqual(['Claim A.', 'Claim B.']);
+ const [retired] = await engine.executeRaw<{ fact: string }>(`SELECT i.preimage->>'fact' AS fact FROM derived_generation_items i
+ JOIN derived_generations g ON g.id=i.generation_id WHERE g.kind='extracted_facts' AND g.state='live' AND i.action='retired'`);
+ expect(retired?.fact).toBe('Claim C.');
+ expect(await publish('whole_body', 'v5', [])).toMatchObject({ state: 'held', reason: 'no_proof' });
+ expect((await live(engine)).map(row => row.fact)).toEqual(['Claim A.', 'Claim B.']);
+ });
+ }, 120_000);
+ });
+}
diff --git a/test/pathological/g2-fence-generations.test.ts b/test/pathological/g2-fence-generations.test.ts
index 384ae54384..f72eb43a46 100644
--- a/test/pathological/g2-fence-generations.test.ts
+++ b/test/pathological/g2-fence-generations.test.ts
@@ -15,6 +15,7 @@ import { operationsByName } from '../../src/core/operations.ts';
import { resolveRepairScope, type RepairResult } from '../../src/core/repair/core.ts';
import { repairRunner } from '../../src/core/repair/registry.ts';
import type { GenerationsSelection } from '../../src/core/generations/repair.ts';
+import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';
async function repair(engine: BrainEngine, sourceId: string, selection: GenerationsSelection, expectHash?: string): Promise<RepairResult> {
const scope = await resolveRepairScope(engine, sourceId);
@@ -133,5 +134,28 @@ describe('GBRA-161 PR 2 fence generations', () => {
expect(edited.listing?.[0]?.class).not.toBe('refused');
});
}, 180_000);
+
+ test(`[${backend}] a deleted page expires its facts only on originGone, recording each before-state; rows no fence derived are held no_proof`, async () => {
+ const fenceless = 'people/fenceless-example';
+ await managedSource(databaseUrl, async ({ engine, sourceId, put }) => {
+ await put(SLUG, PERSON('Alice Example', FACTS(2)));
+ await put(fenceless, PERSON('Fenceless Example', 'No facts section on this page.\n'));
+ await engine.insertFacts( // gbrain-allow-direct-insert: a fence-positioned row no generation recorded (legacy shape)
+ [{ fact: 'Legacy positioned claim', kind: 'fact', source: 'chat', row_num: 1, source_markdown_slug: fenceless, visibility: 'world' }], { source_id: sourceId });
+ for (const slug of [SLUG, fenceless]) await engine.softDeletePage(slug, { sourceId });
+ }, async ({ engine, sourceId }) => {
+ await runExtractFacts(engine, { sourceId });
+ expect(await liveCounts(engine, sourceId, SLUG)).toEqual({ facts: 0, takes: 0 });
+ const [gone] = await engine.executeRaw<{ proof: string; retired: number; preimages: number }>(`SELECT g.completeness->>'proof' AS proof,
+ (SELECT count(*)::int FROM derived_generation_items i WHERE i.generation_id=g.id AND i.action='retired') AS retired,
+ (SELECT count(*)::int FROM derived_generation_items i WHERE i.generation_id=g.id AND i.action='retired' AND i.preimage IS NOT NULL) AS preimages
+ FROM derived_generations g WHERE g.source_id=$1 AND g.kind='fact_fence' AND g.owner_key=$2 AND g.state='live'`, [sourceId, `page:${SLUG}`]);
+ expect(gone).toEqual({ proof: 'originGone', retired: 2, preimages: 2 });
+ expect(await liveCounts(engine, sourceId, fenceless)).toEqual({ facts: 1, takes: 0 });
+ expect(await ledger(engine, sourceId, fenceless)).toEqual([{ kind: 'fact_fence', state: 'held', retired: 0, preimages: 0 }]);
+ const [held] = await engine.executeRaw<{ held_reason: string }>("SELECT held_reason FROM derived_generations WHERE owner_key=$1 AND state='held'", [`page:${fenceless}`]);
+ expect(held?.held_reason).toBe('no_proof');
+ });
+ }, 180_000);
}
});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 9982eb52fb..cfb1a93732 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -325,6 +325,9 @@ test/pathological/g1-generation-probes.test.ts
test/pathological/g1-generations.test.ts
test/pathological/g1-managed-atom-keys.test.ts
test/pathological/g1-managed-atom-probes.test.ts
+test/pathological/g2-consolidation-generations.test.ts
+test/pathological/g2-extracted-facts.test.ts
+test/pathological/g2-fence-generations.test.ts
test/pathological/h1-zero-yield-atom-reextract.test.ts
test/pathological/h2-git-effect-moved-remote.test.ts
test/pathological/h3-chronicle-partial-generation.test.ts