Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(extract_facts): receipted fence reconcile and deleted-page fact expiry on managed brains

time-attacke50eb04b8b2a
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 835456f96b..4536f23260 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -45,8 +45,18 @@
import { existsSync, readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
-import { managedDerivedFactsPreflight, withDerivedFactsWrite } from '../persistence/derived-facts.ts';
+import type { GBrainConfig } from '../config.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import { isTerminal, type WriteRequest } from '../persistence/model.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { digest } from '../persistence/digest.ts';
+import { getWriteRequest } from '../persistence/journal.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { resolveManagedFactsEmbedding } from '../persistence/facts-maintenance.ts';
+import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';
+import { opError, OperationError } from '../ops/contract.ts';
import {
resolveSupersededByRow,
supersessionChainOf,
@@ -310,6 +320,254 @@ async function listExistingFactsForPage(
);
}
+interface FenceReconcilePlan {
+ /** Rows the parsed fence carries (duplicates included), for the pages-with-facts count. */
+ fenceRows: number;
+ extracted: FenceExtractedFact[];
+ matched: Map<number, ExistingPageFact>;
+ stale: ExistingPageFact[];
+ updates: FenceExtractedFact[];
+ toInsert: FenceExtractedFact[];
+ chain: SupersessionChain;
+ /** Nothing to write: every row matches and every supersession pointer is in place. */
+ inSync: boolean;
+}
+
+/**
+ * One page's reconcile plan against its stored rows. Null when the fence is
+ * not authoritative (warnings are appended): a warning-bearing parse or a
+ * fence below the timeline sentinel preserves the page's existing index.
+ */
+async function planFenceReconcile(db: BrainEngine, page: { compiled_truth: string | null; timeline: string | null; effective_date?: Date | string | null },
+ slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {
+ const parsed = parseFactsFence(page.compiled_truth ?? '');
+ if (parsed.warnings.length > 0) {
+ // The parser deliberately skips malformed rows and returns any rows it
+ // could still recover. That partial result is not authoritative: using
+ // it for reconciliation would interpret skipped rows as deletions.
+ warnings.push(...parsed.warnings.map(w => `${slug}: ${w}`));
+ return null;
+ }
+ // #3625: a fence below the timeline sentinel lands in page.timeline, where
+ // parseFactsFence cannot see it; reading compiled_truth alone would treat
+ // its rows as deleted. timelineHasGenuineFactsFenceMarker explains the scan.
+ if (timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {
+ warnings.push(
+ `${slug}: FACTS_FENCE_BELOW_SENTINEL: a ## Facts fence was found below ` +
+ `the <!-- timeline --> sentinel, where extract_facts cannot see it. ` +
+ `Move the fence above the sentinel and re-save — leaving it in place ` +
+ `preserves the existing indexed facts but they will not update.`,
+ );
+ return null;
+ }
+ // v0.35.4 (D-ENG-1): page.effective_date is the fallback valid_from, so
+ // trajectory queries see claim dates rather than import dates.
+ const pageEffectiveDate = page.effective_date ? new Date(page.effective_date) : null;
+ // #1781: duplicate ACTIVE rows (same claim and source) index once.
+ const duplicates = duplicateActiveFenceRows(parsed.facts);
+ const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate })
+ .filter(f => !duplicates.has(f.row_num));
+ // Reconcile by row number, the fence's own unique identity. A DB row whose
+ // (row_num, claim) is still in the fence keeps its id and has its other
+ // cells updated in place; a row whose number disappeared or whose claim
+ // was rewritten is expired and detached (row_num NULL), never deleted.
+ const existing = await listExistingFactsForPage(db, slug, sourceId);
+ const desiredByRow = new Map(extracted.map(f => [f.row_num, f]));
+ const matched = new Map<number, ExistingPageFact>();
+ const stale: ExistingPageFact[] = [];
+ for (const fact of existing) {
+ const desired = fact.row_num == null ? undefined : desiredByRow.get(Number(fact.row_num));
+ if (desired && desired.fact === fact.fact) matched.set(desired.row_num, fact);
+ else stale.push(fact);
+ }
+ const updates = extracted.filter(f => {
+ const fact = matched.get(f.row_num);
+ return fact !== undefined && factCellsDiffer(fact, f);
+ });
+ const toInsert = extracted.filter(f => !matched.has(f.row_num));
+ const chain = supersessionChainOf(extracted, slug);
+ let inSync = false;
+ if (stale.length === 0 && updates.length === 0 && toInsert.length === 0) {
+ const byRow = new Map([...matched].map(([row, fact]) => [row, { id: Number(fact.id), struck: fact.expired_at != null }]));
+ inSync = extracted.every(f => {
+ const stored = matched.get(f.row_num)!.superseded_by;
+ return resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));
+ });
+ }
+ return { fenceRows: parsed.facts.length, extracted, matched, stale, updates, toInsert, chain, inSync };
+}
+
+/**
+ * The destructive half of a plan. A vector-bearing row is never replaced by
+ * a row that could not be embedded: until embedding succeeds, rows keep
+ * their positions (stale rows whose claim is still active in the fence stay,
+ * others are expired in place, new rows wait). In-place updates still apply.
+ */
+function reconcileWrites(plan: FenceReconcilePlan) {
+ const deferInserts = plan.toInsert.some(f => !f.embedding) && plan.stale.some(f => f.has_embedding);
+ const activeClaims = new Set(plan.extracted.filter(f => f.expired_at == null).map(f => `${f.fact}\u0000${f.source}`));
+ return {
+ deferInserts,
+ detach: deferInserts ? [] : plan.stale,
+ expireInPlace: deferInserts ? plan.stale.filter(f => f.expired_at == null && !activeClaims.has(`${f.fact}\u0000${f.source}`)) : [],
+ inserts: deferInserts ? [] : plan.toInsert,
+ };
+}
+
+/** One page's reconcile writes, inside a transaction that holds the page key. */
+async function writeFenceReconcile(tx: BrainEngine, sourceId: string, slug: string, plan: FenceReconcilePlan,
+ writes: ReturnType<typeof reconcileWrites>, signal?: AbortSignal): Promise<{ inserted: number; updated: number; warnings: string[] }> {
+ for (const fact of writes.expireInPlace) {
+ await tx.executeRaw('UPDATE facts SET expired_at = COALESCE(expired_at, now()) WHERE id = $1 AND source_id = $2', [fact.id, sourceId]);
+ }
+ for (const fact of writes.detach) {
+ await tx.executeRaw(
+ `UPDATE facts SET expired_at = COALESCE(expired_at, now()), row_num = NULL
+ WHERE id = $1 AND source_id = $2`,
+ [fact.id, sourceId],
+ );
+ }
+ for (const f of plan.updates) {
+ await tx.executeRaw(
+ `UPDATE facts SET kind = $3, visibility = $4, notability = $5, context = $6,
+ valid_from = COALESCE($7::timestamptz, valid_from),
+ valid_until = CASE WHEN $8::boolean THEN $9::timestamptz ELSE valid_until END,
+ expired_at = CASE WHEN $10::timestamptz IS NULL THEN NULL ELSE COALESCE(expired_at, $10::timestamptz) END,
+ source = $11, confidence = $12,
+ claim_metric = $13, claim_value = $14, claim_unit = $15, claim_period = $16
+ WHERE id = $1 AND source_id = $2`,
+ [plan.matched.get(f.row_num)!.id, sourceId, f.kind ?? 'fact', f.visibility ?? 'private', f.notability ?? 'medium',
+ f.context ?? null, f.valid_from?.toISOString() ?? null, f.expired_at == null,
+ f.valid_until?.toISOString() ?? null, f.expired_at?.toISOString() ?? null, f.source, f.confidence ?? 1.0,
+ f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],
+ );
+ }
+ const inserted = writes.inserts.length === 0
+ ? { inserted: 0 }
+ : await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
+ writes.inserts.map(f => ({ ...f, superseded_by_row: undefined })),
+ { source_id: sourceId },
+ );
+ const insertedRows = new Set(writes.inserts.map(f => f.row_num));
+ const linked = await syncSupersession(tx, sourceId, slug, plan.extracted, plan.chain, insertedRows);
+ signal?.throwIfAborted();
+ const updated = new Set([...plan.updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);
+ return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };
+}
+
+export const FENCE_FACTS_INTENT = 'managed_maintenance_fence_facts';
+export const DELETED_PAGE_FACTS_INTENT = 'managed_maintenance_deleted_page_facts_expire';
+
+function maintenanceRequestIdFor(parts: unknown[]): string {
+ const h = digest(parts);
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+/**
+ * Managed brains: one page's reconcile as a database-only request bound to
+ * the page revision. The vectors embedded for new rows ride along; the
+ * preparer replans under the page lock and uses a vector only for the same
+ * (row, claim) under the brain's current embedding model. Null when the page
+ * changed or the request is still pending (the next run retries).
+ */
+async function publishFenceReconcile(engine: BrainEngine, authority: MaintenanceAuthority, page: { id: number; knowledge_revision?: string | null },
+ slug: string, toInsert: FenceExtractedFact[]): Promise<{ inserted: number; updated: number; deleted: number; deferred: boolean; warnings: string[] } | null> {
+ const sourceId = authority.writer.sourceId;
+ const revision = page.knowledge_revision ?? REVISION_BACKFILL_PENDING;
+ const embeddings = toInsert.filter(f => f.embedding).map(f => ({ row_num: f.row_num, fact: f.fact, model: f.embedding_model ?? null, vector: Array.from(f.embedding!) }));
+ for (let attempt = 0; ; attempt++) {
+ const requestId = maintenanceRequestIdFor(['extract-facts-fence-v1', authority.writer.sourceIncarnation, sourceId, slug, revision, digest(embeddings), attempt]);
+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;
+ try {
+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,
+ { kind: FENCE_FACTS_INTENT, expected_revision: revision, page_id: page.id, embeddings }, requestId);
+ return { inserted: Number(receipt.inserted ?? 0), updated: Number(receipt.updated ?? 0), deleted: Number(receipt.deleted ?? 0),
+ deferred: receipt.deferred === true, warnings: Array.isArray(receipt.warnings) ? receipt.warnings.map(String) : [] };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'write_pending'].includes(error.code)) return null;
+ throw error;
+ }
+ }
+}
+
+/** Preparer for `managed_maintenance_fence_facts`: replans the page's reconcile under its key and applies it. */
+export async function prepareFenceFactsReconcile(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
+ const intent = row.intent as { page_id?: unknown; expected_revision?: unknown; embeddings?: Array<{ row_num: number; fact: string; model: string | null; vector: number[] }> } | null;
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id) || Number(intent?.page_id) !== snapshot.page.id) {
+ throw opError('page_identity_changed', 'The page was deleted or replaced before its facts fence was reconciled.',
+ `Page ${row.slug} in source ${row.source_id} changed before request ${row.request_id} ran, so its fact index was left as it was. The next extract_facts run reconciles the current page.`);
+ }
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const current = await tx.getPage(row.slug, { sourceId: row.source_id });
+ const warnings: string[] = [];
+ const plan = current ? await planFenceReconcile(tx, current, row.slug, row.source_id, warnings) : null;
+ if (!plan || plan.inSync) return { status: 'completed', inserted: 0, updated: 0, deleted: 0, deferred: false, warnings };
+ const signature = await resolveManagedFactsEmbedding(tx, config, true);
+ const vectors = new Map((intent?.embeddings ?? [])
+ .filter(e => signature && e.model === signature.model && e.vector.length === signature.dimensions && e.vector.every(Number.isFinite))
+ .map(e => [`${e.row_num}\u0000${e.fact}`, e]));
+ for (const fact of plan.toInsert) {
+ const vector = vectors.get(`${fact.row_num}\u0000${fact.fact}`);
+ if (vector) { fact.embedding = new Float32Array(vector.vector); fact.embedding_model = vector.model; }
+ }
+ const writes = reconcileWrites(plan);
+ const written = await writeFenceReconcile(tx, row.source_id, row.slug, plan, writes);
+ return { status: 'completed', ...written, deleted: writes.detach.length + writes.expireInPlace.length, deferred: writes.deferInserts,
+ warnings: [...warnings, ...written.warnings] };
+ } };
+}
+
+/**
+ * Managed brains: expire the active fence-owned rows of one soft-deleted
+ * page as a database-only request. It admits only a page that is still
+ * soft-deleted, never restores it, and the apply rechecks the deletion under
+ * the page key, so a concurrent restore wins. Returns the expired ids.
+ */
+async function expireDeletedPageFactsManaged(engine: BrainEngine, authority: MaintenanceAuthority, slug: string): Promise<number[]> {
+ const sourceId = authority.writer.sourceId;
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ if (!snapshot?.page.deleted_at) return [];
+ for (let attempt = 0; ; attempt++) {
+ const requestId = maintenanceRequestIdFor(['extract-facts-deleted-page-v1', authority.writer.sourceIncarnation, sourceId, slug, snapshot.revision, attempt]);
+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;
+ try {
+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,
+ { kind: DELETED_PAGE_FACTS_INTENT, expected_revision: snapshot.revision, page_id: snapshot.page.id, deleted_page: true }, requestId);
+ return Array.isArray(receipt.expired) ? receipt.expired.map(Number) : [];
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed', 'write_pending'].includes(error.code)) return [];
+ throw error;
+ }
+ }
+}
+
+/** Preparer for `managed_maintenance_deleted_page_facts_expire`. */
+export async function prepareDeletedPageFactsExpiry(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id) || !snapshot.page.deleted_at) {
+ throw opError('page_identity_changed', 'The deleted page was restored, purged or replaced before its facts were expired.',
+ `Page ${row.slug} in source ${row.source_id} is no longer the soft-deleted page request ${row.request_id} was admitted for, so its facts were left as they are. No action is needed; extract_facts reconciles a restored page from its fence.`);
+ }
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const expired = await tx.executeRaw<{ id: number }>(
+ `UPDATE facts f SET expired_at = now()
+ WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL
+ AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.id = $3 AND p.deleted_at IS NOT NULL)
+ RETURNING f.id`,
+ [row.source_id, row.slug, Number(row.page_id)]);
+ return { status: 'completed', expired: expired.map(e => Number(e.id)) };
+ } };
+}
+
export interface ExtractFactsOpts {
/** Subset of slugs to reconcile. undefined = walk every page in the brain. */
slugs?: string[];
@@ -449,11 +707,13 @@ export async function runExtractFacts(
opts: ExtractFactsOpts = {},
): Promise<ExtractFactsResult> {
const sourceId = opts.sourceId ?? 'default';
- // Managed brains reconcile the same way, but each database write commits
- // inside the coordinator's source capability under the page key.
- const managed = await managedDerivedFactsPreflight(engine, sourceId);
- const transact = <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>): Promise<T> =>
- managed ? withDerivedFactsWrite(engine, sourceId, slugs, fn) : maintenanceTransaction(engine, fn);
+ // Managed brains reconcile the same way, but each page's writes publish as
+ // a receipted database-only maintenance request. The authority is
+ // preflighted on the first page that needs a write, so a run with nothing
+ // to change never needs one.
+ const managed = await managedPersistenceEnabled(engine);
+ let authority: Promise<MaintenanceAuthority | null> | undefined;
+ const managedAuthority = () => managed ? authority ??= maintenancePreflight(engine, sourceId) : Promise.resolve(null);
const result: ExtractFactsResult = {
pagesScanned: 0,
pagesWithFacts: 0,
@@ -603,9 +863,10 @@ export async function runExtractFacts(
RETURNING f.id`,
[sourceId],
);
- // Managed: one page at a time under its key, so a concurrent restore is
- // either seen as restored or waited for, never expired underneath it.
- const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, transact) : await maintenanceTransaction(engine, expireDeleted);
+ // Managed: one receipted request per page, rechecked under its key, so a
+ // concurrent restore is either seen as restored or waited for, never
+ // expired underneath it.
+ const expired = managed ? await expireDeletedPagesManaged(engine, sourceId, managedAuthority) : await maintenanceTransaction(engine, expireDeleted);
result.factsExpiredForDeletedPages = expired.length;
}
@@ -658,98 +919,12 @@ export async function runExtractFacts(
}
revision = page.knowledge_revision ?? null;
- const body = page.compiled_truth ?? '';
- const parsed = parseFactsFence(body);
- if (parsed.warnings.length > 0) {
- result.warnings.push(
- ...parsed.warnings.map(w => `${slug}: ${w}`),
- );
- // The parser deliberately skips malformed rows and returns any rows it
- // could still recover. That partial result is not authoritative: using
- // it for reconciliation would interpret skipped rows as deletions.
- // Preserve this page's existing index and continue with other pages.
- return 'invalid';
- }
-
- // #3625: splitBody() puts everything below the timeline sentinel into
- // page.timeline, not compiled_truth — a `## Facts` fence written there
- // (agent-composed bodies commonly append it at the bottom) is invisible
- // to the parseFactsFence(body) call above. Without this check,
- // parsed.facts.length === 0 reads as "the user deleted the fence" and
- // the block below prunes every previously-indexed row for the page —
- // when the fence is actually just misplaced, not absent. Distinguish
- // the two by checking whether a fence marker ALSO landed in
- // page.timeline: if so, the page is non-authoritative — malformed
- // placement (loud warning, preserve the existing index), never treated
- // as absence (destructive delete). Checked unconditionally on
- // parsed.facts.length (not just when it's 0): a page can have a valid
- // fence above the sentinel AND a stray/duplicate one below it (e.g. a
- // partial hand-edit), in which case parsed.facts.length > 0 but
- // reconciling from compiled_truth alone would still misread the
- // below-sentinel rows as deleted. Uses timelineHasGenuineFactsFenceMarker
- // rather than a raw .includes() (adversarial review finding: the naive
- // substring check false-positives on the marker text merely being
- // mentioned in a doc code-block or quoted prose, wrongly blocking a
- // genuine deletion and leaving stale facts indexed indefinitely).
- if (timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {
- result.warnings.push(
- `${slug}: FACTS_FENCE_BELOW_SENTINEL: a ## Facts fence was found below ` +
- `the <!-- timeline --> sentinel, where extract_facts cannot see it. ` +
- `Move the fence above the sentinel and re-save — leaving it in place ` +
- `preserves the existing indexed facts but they will not update.`,
- );
- return 'invalid';
- }
-
- if (parsed.facts.length > 0) result.pagesWithFacts += 1;
-
- // v0.35.4 (D-ENG-1) — thread page.effective_date as the fallback
- // valid_from. Without this, fence rows without explicit `validFrom:`
- // land with `valid_from = now()` (import timestamp) and every
- // trajectory query against the page returns import dates instead of
- // claim dates.
- const pageEffectiveDate = page.effective_date ? new Date(page.effective_date) : null;
- // #1781: duplicate ACTIVE rows (same claim and source) index once.
- const duplicates = duplicateActiveFenceRows(parsed.facts);
- const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate })
- .filter(f => !duplicates.has(f.row_num));
-
+ const plan = await planFenceReconcile(engine, page, slug, sourceId, result.warnings);
+ if (!plan) return 'invalid';
+ if (plan.fenceRows > 0) result.pagesWithFacts += 1;
if (opts.dryRun) return 'skipped';
-
- // Reconcile by row number, the fence's own unique identity (the parser
- // refuses duplicate row numbers). A DB row whose (row_num, claim) is still
- // in the fence keeps its id and has its other cells updated in place, so
- // ids handed out by recall keep working for forget and consolidation,
- // source_session, created_at and embeddings survive an edit. A row whose
- // number disappeared or whose claim was rewritten is expired and detached
- // (row_num NULL), never deleted: the same rule the managed projection
- // applies. Keying on row number also keeps a claim that reverts to an
- // earlier value (NYC -> SF -> NYC) active instead of folding it onto the
- // struck history row with the same text.
- const existing = await listExistingFactsForPage(engine, slug, sourceId);
- const desiredByRow = new Map(extracted.map(f => [f.row_num, f]));
- const matched = new Map<number, ExistingPageFact>();
- const stale: ExistingPageFact[] = [];
- for (const fact of existing) {
- const desired = fact.row_num == null ? undefined : desiredByRow.get(Number(fact.row_num));
- if (desired && desired.fact === fact.fact) matched.set(desired.row_num, fact);
- else stale.push(fact);
- }
- const updates = extracted.filter(f => {
- const fact = matched.get(f.row_num);
- return fact !== undefined && factCellsDiffer(fact, f);
- });
- const toInsert = extracted.filter(f => !matched.has(f.row_num));
- const chain = supersessionChainOf(extracted, slug);
-
- if (stale.length === 0 && updates.length === 0 && toInsert.length === 0) {
- const byRow = new Map([...matched].map(([row, fact]) => [row, { id: Number(fact.id), struck: fact.expired_at != null }]));
- const inSync = extracted.every(f => {
- const stored = matched.get(f.row_num)!.superseded_by;
- return resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));
- });
- if (inSync) return 'unchanged';
- }
+ if (plan.inSync) return 'unchanged';
+ const { toInsert } = plan;
// v0.35.4 (D-CDX-3) — batch-embed new rows before insert so
// consolidate's cosine clustering and find_trajectory's drift_score see
@@ -792,66 +967,25 @@ export async function runExtractFacts(
return 'stop';
}
- // A vector-bearing row is never replaced by a row that could not be
- // embedded. Until embedding succeeds, rows keep their positions: stale
- // rows whose claim is still active in the fence stay as they are, others
- // are expired in place, and new rows wait. In-place updates (privacy,
- // notability, strikes) still apply.
- const deferInserts = toInsert.some(f => !f.embedding) && stale.some(f => f.has_embedding);
- const activeClaims = new Set(extracted.filter(f => f.expired_at == null).map(f => `${f.fact}\u0000${f.source}`));
- const detach = deferInserts ? [] : stale;
- const expireInPlace = deferInserts
- ? stale.filter(f => f.expired_at == null && !activeClaims.has(`${f.fact}\u0000${f.source}`))
- : [];
- const inserts = deferInserts ? [] : toInsert;
+ const writes = reconcileWrites(plan);
+ const { detach, expireInPlace, deferInserts } = writes;
if (deferInserts) {
result.warnings.push(`${slug}: destructive fact reconciliation deferred; existing vectors preserved until embedding succeeds`);
}
- const apply = async () => {
+ type Written = { inserted: number; updated: number; warnings: string[]; deleted?: number; deferred?: boolean };
+ const apply = async (): Promise<Written | null> => {
+ const authority = await managedAuthority();
+ if (authority) return publishFenceReconcile(engine, authority, page, slug, toInsert);
try {
- return await transact([slug], async tx => {
+ return await maintenanceTransaction(engine, async tx => {
opts.signal?.throwIfAborted();
if (watermark && !await lockReconcileRevision(tx, sourceId, slug, page.knowledge_revision ?? null)) return null;
const current = await tx.getPage(slug, { sourceId });
if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;
- for (const fact of expireInPlace) {
- await tx.executeRaw('UPDATE facts SET expired_at = COALESCE(expired_at, now()) WHERE id = $1 AND source_id = $2', [fact.id, sourceId]);
- }
- for (const fact of detach) {
- await tx.executeRaw(
- `UPDATE facts SET expired_at = COALESCE(expired_at, now()), row_num = NULL
- WHERE id = $1 AND source_id = $2`,
- [fact.id, sourceId],
- );
- }
- for (const f of updates) {
- await tx.executeRaw(
- `UPDATE facts SET kind = $3, visibility = $4, notability = $5, context = $6,
- valid_from = COALESCE($7::timestamptz, valid_from),
- valid_until = CASE WHEN $8::boolean THEN $9::timestamptz ELSE valid_until END,
- expired_at = CASE WHEN $10::timestamptz IS NULL THEN NULL ELSE COALESCE(expired_at, $10::timestamptz) END,
- source = $11, confidence = $12,
- claim_metric = $13, claim_value = $14, claim_unit = $15, claim_period = $16
- WHERE id = $1 AND source_id = $2`,
- [matched.get(f.row_num)!.id, sourceId, f.kind ?? 'fact', f.visibility ?? 'private', f.notability ?? 'medium',
- f.context ?? null, f.valid_from?.toISOString() ?? null, f.expired_at == null,
- f.valid_until?.toISOString() ?? null, f.expired_at?.toISOString() ?? null, f.source, f.confidence ?? 1.0,
- f.claim_metric ?? null, f.claim_value ?? null, f.claim_unit ?? null, f.claim_period ?? null],
- );
- }
- const inserted = inserts.length === 0
- ? { inserted: 0 }
- : await tx.insertFacts( // gbrain-allow-direct-insert: extract_facts cycle phase reconciles fence → DB
- inserts.map(f => ({ ...f, superseded_by_row: undefined })),
- { source_id: sourceId },
- );
- const insertedRows = new Set(inserts.map(f => f.row_num));
- const linked = await syncSupersession(tx, sourceId, slug, extracted, chain, insertedRows);
- opts.signal?.throwIfAborted();
- const updated = new Set([...updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);
+ const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal);
if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);
- return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };
+ return written;
});
} catch (error) {
if (!isAborted(opts.signal)) throw error;
@@ -859,7 +993,7 @@ export async function runExtractFacts(
return null;
}
};
- const outcome = detach.length === 0 && expireInPlace.length === 0 && updates.length === 0
+ const outcome = detach.length === 0 && expireInPlace.length === 0 && plan.updates.length === 0
? await apply()
: await underPageLock(slug, async () => {
if (await refuseDestructiveReconcileOnStaleCache(
@@ -871,10 +1005,10 @@ export async function runExtractFacts(
if (!outcome) return isAborted(opts.signal) ? 'cancelled' : 'deferred';
result.factsInserted += outcome.inserted;
result.factsUpdated += outcome.updated;
- result.factsDeleted += detach.length + expireInPlace.length;
+ result.factsDeleted += outcome.deleted ?? detach.length + expireInPlace.length;
// resolveSupersededByRow prefixes each message with the slug + row.
for (const w of outcome.warnings) result.warnings.push(w);
- return deferInserts ? 'deferred' : 'complete';
+ return (outcome.deferred ?? deferInserts) ? 'deferred' : 'complete';
};
for (const slug of slugs) {
@@ -946,7 +1080,7 @@ export async function runExtractFacts(
}
async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,
- transact: <T>(slugs: string[], fn: (tx: BrainEngine) => Promise<T>) => Promise<T>): Promise<Array<{ id: number }>> {
+ managedAuthority: () => Promise<MaintenanceAuthority | null>): Promise<Array<{ id: number }>> {
const pages = await engine.executeRaw<{ slug: string }>(
`SELECT DISTINCT f.source_markdown_slug AS slug FROM facts f
WHERE f.source_id = $1 AND f.row_num IS NOT NULL AND f.expired_at IS NULL
@@ -955,13 +1089,8 @@ async function expireDeletedPagesManaged(engine: BrainEngine, sourceId: string,
);
const expired: Array<{ id: number }> = [];
for (const { slug } of pages) {
- expired.push(...await transact([slug], tx => tx.executeRaw<{ id: number }>(
- `UPDATE facts f SET expired_at = now()
- WHERE f.source_id = $1 AND f.source_markdown_slug = $2 AND f.row_num IS NOT NULL AND f.expired_at IS NULL
- AND EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NOT NULL)
- RETURNING f.id`,
- [sourceId, slug],
- )));
+ const authority = (await managedAuthority())!;
+ expired.push(...(await expireDeletedPageFactsManaged(engine, authority, slug)).map(id => ({ id })));
}
return expired;
}
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index d27d48fc07..6cae97f472 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -122,8 +122,13 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuth
return writeResponse(wait.observe(await waitForWrite(engine, prior, loadConfig() ?? { engine: engine.kind }, wait.ms())));
}
const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId, includeDeleted: true });
+ // A deleted-page intent (extract_facts expiring a soft-deleted page's facts) admits only a page that is still soft-deleted.
+ if (intent.deleted_page === true && !snapshot?.page.deleted_at) {
+ throw opError('page_identity_changed', 'The deleted page was restored or purged before maintenance admitted its request.',
+ `Page ${slug} in '${authority.writer.sourceId}' is no longer soft-deleted, so nothing was submitted for it. Run maintenance again to plan from the current pages.`);
+ }
// #5876: only a Life Chronicle event its extractor retired may be restored by a later generation.
- if (snapshot?.page.deleted_at && !(intent.restore_retired === true && snapshot.page.frontmatter?.retired_by === 'life-chronicle')) {
+ if (snapshot?.page.deleted_at && intent.deleted_page !== true && !(intent.restore_retired === true && snapshot.page.frontmatter?.retired_by === 'life-chronicle')) {
throw opError('page_not_found', 'Maintenance cannot restore a deleted page.',
`Page ${slug} in '${authority.writer.sourceId}' was deleted after maintenance read it, and maintenance never recreates deleted pages; nothing was submitted. Run maintenance again to plan from the current pages.`);
}
@@ -339,6 +344,11 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Write
if (row.authority.remote) throw trustedCliRequired('Remote maintenance publication is not supported.');
if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);
if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_conversation_facts') return (await import('../facts/conversation-publication.ts')).prepareConversationFactsPublication(engine, row, config);
+ if (row.intent?.kind === 'managed_maintenance_fence_facts') return (await import('../cycle/extract-facts.ts')).prepareFenceFactsReconcile(engine, row, config);
+ if (row.intent?.kind === 'managed_maintenance_deleted_page_facts_expire') return (await import('../cycle/extract-facts.ts')).prepareDeletedPageFactsExpiry(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_takes_reextract') return (await import('../cycle/extract-takes.ts')).prepareTakesReextract(engine, row);
+ if (row.intent?.kind === 'managed_maintenance_take_reproject') return (await import('../repair/take-supersession.ts')).prepareTakeReprojection(engine, row);
if (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);
if (row.intent?.kind === 'managed_maintenance_page') {
const prepared = await preparePageMutation(engine, row.intent.expected_revision === null