Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(facts): mirror the #6333 same-page shadow counter into the managed preparer

garrytan62cb115c8aaf
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index bf16c696f6..6abfb13698 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -46,7 +46,7 @@ link it here rather than raising the cap.
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, attribution, purge-deleted, fact retirement, sync orphans |
-| [Core Persistence (managed facts)](key-files/core-persistence-facts.md) | `facts-maintenance.ts`, `facts-prepare.ts`, `derived-facts.ts`, `src/core/facts/conversation-publication.ts` |
+| [Core Persistence (managed facts)](key-files/core-persistence-facts.md) | `facts-maintenance.ts`, `facts-prepare.ts`, `derived-facts.ts`, `src/core/facts/{conversation-publication,same-page-shadow}.ts` |
| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, its doctor finding |
| [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `journal.ts`, `diagnostics.ts`, `worktree-manifest.ts` |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/read-policy-sql.ts` |
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 0707d64ddf..d996a7ee50 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -5,5 +5,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Managed facts extraction: the entity-intent preparer and publisher, conversation facts batches and the unmanaged derived index. The extraction pipeline itself is in [Google and Loops (continued)](google-and-loops-continued.md) (`src/core/facts/backstop.ts`) and [Core Services (2/3)](core-services-2.md) (`src/core/facts/extract.ts`).
- `src/core/persistence/{facts-maintenance,facts-prepare}.ts` — the managed facts publisher and preparer behind the backstop's `publishManagedFacts` / `resumeManagedFacts` and the explicit fact writers (`managed-fact-write.ts`, `remember`); the shared maintenance dispatch they ride is in [Core Persistence](core-persistence.md). `facts-maintenance.ts` / `facts-prepare.ts` (#6506): an automatic extraction's entity intent carries `withdrawn: 'skip'` (set by the backstop's `publishManagedFacts` call, never by `managed-fact-write.ts` or `remember`), under which `prepareManagedFactsMutation` skips a candidate `isFactWithdrawn` matches (after `assertFactNotPurged`, which still refuses `purged_content`) and counts it as `withdrawn_skipped` on the entity outcome, summed into the completion outcome, `ManagedFactsResult` and the `extract_facts` result (the unmanaged pipeline counts its own B-10 skip into the same field); without the flag the refusal stands. At locked validation the per-entry purge and withdrawal checks run before the page's fence re-validation, and under the flag a claim forgotten since preparation refuses `revision_conflict` with `error.withdrawn` (so the receipt's `error_detail.origin` is `withdrawal`); no `extract_facts` request is re-prepared. `resumeManagedFacts` runs `followWithdrawalRefusals` for an input-keyed session (`inputKeyed`, no request id): the `followFileRefusals` walk generalized as `followRefusals`, matching entity refusals by `withdrawnFromDetail(error_detail)` or the pre-detail `invalid_params` + `FACT_WITHDRAWN_MESSAGE` pair, re-admitting the retained facts under `digest([batchKey, 'withdrawal-retry', n])` with the flag (`readmitWithdrawnFacts`: a fact forgotten at its retained visibility keeps that visibility so preparation skips it instead of narrowing it to private), bounded by `MAX_FILE_REFUSAL_RETRIES`, historical receipts untouched. Tests: `test/managed-facts-withdrawn-skip-6506.test.ts`, `test/managed-facts-withdrawal-recovery-6506.test.ts` (PGLite and Postgres).
+- `src/core/facts/same-page-shadow.ts` — #6333 the shadow counter both fact writers share. `samePageRewording(engine, sourceId, fact, embedding)` re-reads the entity's nearest live same-visibility candidate (`listSupersessionCandidates`, the pool and filters of `decideSingleFact`'s cosine pass) and answers whether `wouldDedupSamePage` (capture-dedup.ts: same lane, same `source_session`, same visibility, cosine ≥ 0.85, no diverging guard token) would have called the fact a rewording; `warnSamePageShadow` is the one stderr spelling (`[facts-backstop] #6333 shadow: …; both kept`). `facts-prepare.ts` calls it for every candidate `decideSingleFact` did not match and counts `would_dedup_same_page` on the entity outcome, the completion outcome, `ManagedFactsResult` and the `extract_facts` result; the count is frozen in the receipt, so a replay reports it and does not recount. Nothing is dropped; this is the managed mirror of the unmanaged backstop's counter (`backstop.ts`), which never fired on a managed brain. Tests: `test/backstop-same-page-shadow-managed-6333.test.ts` (PGLite and Postgres), `test/backstop-same-page-shadow-6333.test.ts` (unmanaged).
- `src/core/persistence/derived-facts.ts` — `writeDerivedFacts`: the unmanaged conversation fact index commits in one maintenance transaction under the maintenance principal; on a managed brain it refuses with `writer_coordinator_required`, because every managed facts/takes writer publishes a receipted maintenance request (`test/receipt-coverage.test.ts` lists every coordinated write site). Tests: `test/write-attribution-misc.test.ts`.
- `src/core/facts/conversation-publication.ts` — managed conversation facts as database-only `managed_maintenance_conversation_facts` batch requests (`submitDatabaseMaintenanceIntent` on `ANCHOR_SLUG`, a dot-led slug no page can hold, dispatched from `prepareMaintenanceMutation`). Each page's frozen entry (`buildConversationPage`: `FrozenExtractedFact` rows, its generation and attempt, vectors only under the brain's facts embedding signature) joins the run's batch; `enqueueManagedPage` publishes it once `DEFAULT_BATCH_CAPS` is reached (25 pages, 10 with extracted facts, 8 MiB) and `flushManagedBatch` at the end of the run. The generation key (protocol, source incarnation, page id, revision, parser-input version token, `CONVERSATION_EXTRACTOR_VERSION`, selectors, newest extractor row id) is checked before model work by `startManagedPage` against `loadGenerationIndex` (the writer's unsettled and failed batches on the anchor, read once per run): a member of an unsettled batch waits and replays its receipt, a member of a retryably failed batch is resubmitted from its stored entry, a deterministic failure or three failed batches block it; all without model calls. The batch request id digests its members' (generation, attempt) pairs. The preparer locks every member's key and applies each on its own (`applyEntry`): a deleted, replaced or moved page is skipped and reported, a page whose rows fail validation gets a durable `blocked:` not-extractable outcome, vectors under another signature are dropped; none fails the batch. `estimateConversationIntentBytes`/`conversationIntentByteLimit` skip a page whose largest entry cannot fit before any model call; `assertConversationAdmissionHeadroom` stops admitting at 80% of the writer's outstanding requests, reserved receipt bytes or lifetime ids (`maintenance_backpressure`, exit 12, naming the resource and a `--limit` that fits), up front for the run's planned batches and before each new batch. `replaceConversationFacts` deletes the page's extractor rows (expiring referenced and keeping label-retired ones) and inserts the entry numbered above every remaining row, failing on a lost insert. Tests: `test/conversation-facts-managed.test.ts` (+ Postgres arm), managed-connector contract cases `extract_conversation_facts*`.
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index f11784c728..c5567cdfc0 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -50,6 +50,7 @@ import { isAvailable } from '../ai/gateway.ts';
import { withAIInvocationPreflight } from '../ai/invocation-guard.ts';
import { decideSingleFact } from './single-prepare.ts';
import { cosineVerdict, dedupCapturedFacts, withCaptureDrops, wouldDedupSamePage } from './capture-dedup.ts';
+import { warnSamePageShadow } from './same-page-shadow.ts';
import { readSupersessionThreshold } from './supersession-threshold.ts';
import { assertAmbientCaptureAdmissible, type FactsBackstopSource } from './capture-sources.ts';
import { appendContextNote, type InferredVia } from './subject-infer.ts';
@@ -227,10 +228,6 @@ function warnOnce(key: string, msg: string): void {
console.warn(msg);
}
/** #6333 [UC2] shadow only: name the pair the same-page rewording rule would have deduplicated; the fact is inserted as today. */
-function warnSamePageShadow(sessionId: string | null, matchedId: number, score: number): void {
- // eslint-disable-next-line no-console
- console.warn(`[facts-backstop] #6333 shadow: new fact in session ${sessionId} rewords fact ${matchedId} (cosine ${score.toFixed(3)}); both kept`);
-}
/** Test-only: reset the once-per-process warning memo. */
export function __resetBackstopWarningsForTests(): void {
_warnedKeys.clear();
diff --git a/src/core/facts/same-page-shadow.ts b/src/core/facts/same-page-shadow.ts
new file mode 100644
index 0000000000..b04e47a716
--- /dev/null
+++ b/src/core/facts/same-page-shadow.ts
@@ -0,0 +1,48 @@
+/**
+ * #6333 shadow counter, shared by both fact writers. The unmanaged backstop
+ * counts `would_dedup_same_page` inline (its candidate loop already holds the
+ * nearest row); the managed preparer (`facts-prepare.ts`) scores its
+ * candidate through `decideSingleFact`, which exposes a candidate only on a
+ * duplicate verdict, so the mirror re-reads the nearest live candidate here.
+ * The counter measures; it never drops a fact (see capture-dedup.ts).
+ */
+import type { BrainEngine, FactAttribution, FactVisibility } from '../engine.ts';
+import { cosineSimilarity } from './classify.ts';
+import { listSupersessionCandidates } from './single-prepare.ts';
+import { wouldDedupSamePage } from './capture-dedup.ts';
+
+export interface SamePageShadowFact {
+ entity_slug: string | null;
+ fact: string;
+ visibility: FactVisibility;
+ source: string;
+ source_session?: string | null;
+ embedding_model?: string | null;
+ attributed_to?: FactAttribution | null;
+}
+
+/**
+ * The entity's nearest live candidate under the fact's visibility when the
+ * same-page rule would have called the fact a rewording of it, else null.
+ * The candidate pool and the visibility/expiry filters match
+ * `decideSingleFact`'s cosine pass; the fence-page check it adds is for
+ * supersession and does not apply to a measurement.
+ */
+export async function samePageRewording(engine: BrainEngine, sourceId: string, fact: SamePageShadowFact, embedding: Float32Array | null): Promise<{ id: number; score: number } | null> {
+ if (!embedding || !fact.entity_slug || !fact.source_session) return null;
+ const candidates = await listSupersessionCandidates(engine, sourceId, fact.entity_slug, fact.fact, embedding, fact.embedding_model, undefined, fact.attributed_to ?? null);
+ let top: { row: typeof candidates[number]; score: number } | null = null;
+ for (const row of candidates) {
+ if (!row.embedding || row.expired_at || row.visibility !== fact.visibility) continue;
+ const score = cosineSimilarity(embedding, row.embedding);
+ if (!top || score > top.score) top = { row, score };
+ }
+ if (!top || !wouldDedupSamePage({ source: fact.source, sessionId: fact.source_session, visibility: fact.visibility }, top.row, top.score, fact.fact)) return null;
+ return { id: top.row.id, score: top.score };
+}
+
+/** The one stderr spelling of a counted rewording; the evidence line the measurement collects. */
+export function warnSamePageShadow(sessionId: string | null, matchedId: number, score: number): void {
+ // eslint-disable-next-line no-console
+ console.warn(`[facts-backstop] #6333 shadow: new fact in session ${sessionId} rewords fact ${matchedId} (cosine ${score.toFixed(3)}); both kept`);
+}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 8ac30f11a8..1db8b5ae22 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -192,6 +192,7 @@ const extract_facts: Operation = {
fact_ids: r.fact_ids,
...(r.write_requests ? { write_requests: r.write_requests } : {}),
...(r.withdrawn_skipped ? { withdrawn_skipped: r.withdrawn_skipped } : {}),
+ ...(r.would_dedup_same_page ? { would_dedup_same_page: r.would_dedup_same_page } : {}),
...hintAccounting,
};
},
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index c438880fd6..7e7b20e394 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -38,6 +38,8 @@ export interface ManagedFactsResult {
inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; write_requests: WriteReceipt[];
/** #6506: candidates the automatic extraction skipped because the exact claim was forgotten in this source and visibility. */
withdrawn_skipped?: number;
+ /** #6333 shadow: same-page rewordings the managed preparer counted; nothing was dropped. */
+ would_dedup_same_page?: number;
}
export interface ManagedFactOrigin { slug: string; pageId: number; revision: string; }
export type FrozenExtractedFact = Omit<NewFact, 'embedding' | 'valid_from' | 'valid_until' | 'expired_at'> & {
@@ -296,6 +298,7 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes
result.superseded += Number(out.superseded ?? 0);
result.fact_ids.push(...(out.fact_ids as number[] ?? []));
if (out.withdrawn_skipped) result.withdrawn_skipped = (result.withdrawn_skipped ?? 0) + Number(out.withdrawn_skipped);
+ if (out.would_dedup_same_page) result.would_dedup_same_page = (result.would_dedup_same_page ?? 0) + Number(out.would_dedup_same_page);
if (out.inserted && out.fenced) result.entity_slugs.push(row.slug);
}
}
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index 96a604b03a..236f743121 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -9,6 +9,7 @@ import { parseFactsFence, upsertFactRow, formatFenceDate, renderFactsTable, repl
import { serializePageToMarkdown } from '../markdown.ts';
import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';
import { assertFactNotPurged, isFactWithdrawn } from '../facts/withdrawal.ts';
+import { samePageRewording, warnSamePageShadow } from '../facts/same-page-shadow.ts';
import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';
import { authorizeWrite } from './authority.ts';
import { authorizePageVisibility } from './page-visibility.ts';
@@ -117,16 +118,18 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const additionalPageKeys = p.origin ? [{ sourceId: row.source_id, slug: p.origin.slug }] : [];
if (p.kind === 'managed_facts_complete') return { observedRevision: null, noop: true, additionalPageKeys, validate, apply: async tx => {
const children = p.children ?? [];
- const done = await tx.executeRaw<{ outcome: { inserted?: number; duplicate?: number; fact_ids?: number[]; withdrawn_skipped?: number } }>(`SELECT outcome FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuid
+ const done = await tx.executeRaw<{ outcome: { inserted?: number; duplicate?: number; fact_ids?: number[]; withdrawn_skipped?: number; would_dedup_same_page?: number } }>(`SELECT outcome FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuid
AND state='committed' AND COALESCE(intent->>'batchKey',outcome->>'batch_key')=$3 AND operation='extract_facts'`, [children, row.source_incarnation, p.batchKey]);
if (done.length !== children.length) throw factsRefusal('revision_conflict', 'Some extracted facts have not committed.', row,
`${children.length - done.length} of the batch's ${children.length} per-entity fact requests have not committed, so the extraction cannot be recorded as complete.`,
'once the entity requests are final, run extract_facts again for the same turn with a new request_id only if facts are still missing.');
const withdrawnSkipped = done.reduce((sum, item) => sum + Number(item.outcome.withdrawn_skipped ?? 0), 0);
+ const wouldDedupSamePage = done.reduce((sum, item) => sum + Number(item.outcome.would_dedup_same_page ?? 0), 0);
return { status: 'completed', entity_requests: children.length, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,
inserted: done.reduce((sum, item) => sum + Number(item.outcome.inserted ?? 0), 0),
duplicate: done.reduce((sum, item) => sum + Number(item.outcome.duplicate ?? 0), 0),
...(withdrawnSkipped ? { withdrawn_skipped: withdrawnSkipped } : {}),
+ ...(wouldDedupSamePage ? { would_dedup_same_page: wouldDedupSamePage } : {}),
fact_ids: done.flatMap(item => item.outcome.fact_ids ?? []) };
} };
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
@@ -158,6 +161,9 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
// #6506: automatic extraction skips a forgotten claim and keeps the rest of the group; a purge tombstone still
// refuses the group, as it does for every writer; explicit writers (no flag) refuse the forgotten claim.
let withdrawnSkipped = 0;
+ // #6333 shadow (managed mirror of the backstop's counter): a same-page rewording is counted on the entity outcome
+ // and named on stderr; nothing is dropped. The count is frozen in the receipt, so a replay reports it, not recounts it.
+ let wouldDedupSamePage = 0;
for (const fact of facts) {
if (p.withdrawn === 'skip') {
await assertFactNotPurged(engine, row.source_id, fact);
@@ -168,6 +174,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }
seen.set(key, [...(seen.get(key) ?? []), entries.length]);
const decision = await decideSingleFact(engine, row.source_id, fact, dedupEmbedding(fact), fact.embedding_model, fact.source);
+ const shadow = decision.candidate ? null : await samePageRewording(engine, row.source_id, fact, dedupEmbedding(fact));
+ if (shadow) { wouldDedupSamePage++; warnSamePageShadow(fact.source_session ?? null, shadow.id, shadow.score); }
const supersedes = p.supersede === true && decision.status === 'superseded' ? decision.candidate! : undefined;
if (decision.candidate && !supersedes) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }
const gate = taint ? decideFactWrite(fact, { sourceId: row.source_id, slug: row.slug, payload: { ...fact, embedding: null },
@@ -260,6 +268,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
for (const gate of blocked) await applyGateDecision(tx, gate, { table: 'facts', sourceId: row.source_id }, async () => null, write_gate);
return { status: 'completed', inserted, duplicate: entries.length - inserted, superseded, fact_ids: ids, ...(blocked.length ? { write_gate } : {}),
...(withdrawnSkipped ? { withdrawn_skipped: withdrawnSkipped } : {}),
+ ...(wouldDedupSamePage ? { would_dedup_same_page: wouldDedupSamePage } : {}),
fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,
...(page && target?.fixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,
writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {}) };
diff --git a/test/backstop-same-page-shadow-managed-6333.test.ts b/test/backstop-same-page-shadow-managed-6333.test.ts
new file mode 100644
index 0000000000..4927484c03
--- /dev/null
+++ b/test/backstop-same-page-shadow-managed-6333.test.ts
@@ -0,0 +1,190 @@
+/**
+ * #6333 (wave 16 G2.5, T2/R30): the same-page rewording shadow counter lived
+ * only in the unmanaged backstop loop; on a managed brain
+ * (`persistence_brain.enabled`) extraction publishes through
+ * `publishManagedFacts` and `facts-prepare.ts`, so the counter never fired
+ * and the measurement the parked rule waits for could not accumulate on a
+ * managed brain. The managed preparer now mirrors the predicate: a rewording
+ * is counted as `would_dedup_same_page` on the entity receipt, the completion
+ * receipt and the extraction result, and named on stderr; both facts are kept.
+ *
+ * Negatives (0): another visibility, another lane, another session. A replay
+ * under the same request id reports the frozen count with no model call. No dedup
+ * behaviour changes; zero model calls (stub transports). PGLite and Postgres.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+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 { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const DIMS = 1536;
+const ENTITY = 'people/alice-example';
+const LONG_BODY = 'this is a real meeting note longer than 80 chars '.repeat(3);
+
+const engines: BrainEngine[] = [];
+const dbDir = mkdtempSync(join(tmpdir(), 'gbrain-shadow-managed-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+let calls = 0;
+
+/** Unit vectors at cosine exactly 0.9 within one page and orthogonal across pages (as in the unmanaged test). */
+let nextDim = 0;
+const pageDim = new Map<string, number>();
+function vectorFor(key: string): number[] {
+ if (!pageDim.has(key)) pageDim.set(key, nextDim++);
+ const v = new Array<number>(DIMS).fill(0);
+ v[pageDim.get(key)!] = Math.sqrt(0.9);
+ v[nextDim++] = Math.sqrt(0.1);
+ return v;
+}
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dbDir });
+ await engine.initSchema();
+ engines.push(engine);
+ } else {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(isolated.engine);
+ closePostgres = isolated.close;
+ }
+ }
+}, 120_000);
+afterEach(() => { __setChatTransportForTests(null); __setEmbedTransportForTests(null); });
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ resetGateway();
+ rmSync(dbDir, { recursive: true, force: true });
+});
+
+function stub(fact: string, vector: number[]) {
+ __setChatTransportForTests(async (): Promise<ChatResult> => {
+ calls++;
+ return { text: JSON.stringify({ facts: [{ fact, kind: 'fact', entity: ENTITY, confidence: 1, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' };
+ });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => vector) })) as never);
+}
+
+type Extracted = { inserted: number; duplicate: number; would_dedup_same_page?: number };
+type Seed = { fact: string; visibility?: 'world' | 'private'; source?: string; session?: string | null };
+
+/**
+ * A managed, database-only source with the entity page and, optionally, earlier facts about it (seeded before the
+ * brain turns managed, each with the page vector so it is the nearest candidate of the next extraction).
+ */
+async function managedSource(engine: BrainEngine, seeds: Seed[] = []) {
+ const sourceId = `w6333-${Math.random().toString(36).slice(2, 10)}`;
+ const session = `sync:${sourceId}`;
+ const vector = () => Float32Array.from(vectorFor(sourceId));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example is a person.', timeline: '', frontmatter: {} }, { sourceId });
+ for (const seed of seeds) {
+ await engine.insertFact({ fact: seed.fact, entity_slug: ENTITY, kind: 'fact', visibility: seed.visibility ?? 'world', source: seed.source ?? 'mcp:extract_facts',
+ source_session: seed.session === undefined ? session : seed.session, embedding: vector(), embedding_model: 'openai:text-embedding-3-small' }, { source_id: sourceId });
+ }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, config: { engine: engine.kind }, remote: false as const, sourceId, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const extract = async (fact: string, requestId?: string): Promise<Extracted> => {
+ stub(fact, vectorFor(sourceId));
+ return operationsByName.extract_facts.handler(ctx, { turn_text: `Synthetic meeting record. ${fact}`, visibility: 'world', session_id: session,
+ ...(requestId ? { request_id: requestId } : {}) }) as Promise<Extracted>;
+ };
+ const rows = () => engine.executeRaw<{ id: number; fact: string }>(
+ 'SELECT id, fact FROM facts WHERE source_id=$1 AND expired_at IS NULL ORDER BY id', [sourceId]);
+ const receipts = () => engine.executeRaw<{ slug: string; state: string; shadow: string | null }>(
+ `SELECT slug, state, outcome->>'would_dedup_same_page' AS shadow FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence`, [sourceId]);
+ return { sourceId, session, extract, rows, receipts };
+}
+
+async function onEachEngine(body: (engine: BrainEngine) => Promise<void>) {
+ for (const engine of engines) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-shadow-managed-'));
+ calls = 0;
+ try { await withEnv({ GBRAIN_HOME: home }, () => body(engine)); }
+ finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+ }
+}
+
+describe('#6333 shadow counter on a managed brain', () => {
+ test('a same-page rewording is counted once on the entity receipt, the completion and the result; both facts are kept; the replay reports the frozen count', async () => {
+ await onEachEngine(async engine => {
+ const s = await managedSource(engine);
+ const warned: string[] = [];
+ const original = console.warn;
+ console.warn = (...args: unknown[]) => { warned.push(args.map(String).join(' ')); };
+ try {
+ const first = await s.extract('Alice Example leads the platform team at the example company');
+ expect(first.inserted).toBe(1);
+ expect(first.would_dedup_same_page ?? 0).toBe(0);
+ const requestId = randomUUID();
+ const second = await s.extract('Alice Example is the lead of the example company platform team', requestId);
+ expect(second.would_dedup_same_page).toBe(1);
+ expect(second.inserted).toBe(1);
+ expect(second.duplicate).toBe(0);
+ const rows = await s.rows();
+ expect(rows.map(row => row.fact)).toEqual([
+ 'Alice Example leads the platform team at the example company',
+ 'Alice Example is the lead of the example company platform team',
+ ]);
+ expect(warned.filter(line => line.includes('#6333 shadow'))).toEqual([
+ `[facts-backstop] #6333 shadow: new fact in session ${s.session} rewords fact ${rows[0].id} (cosine 0.900); both kept`,
+ ]);
+ const receipts = await s.receipts();
+ expect(receipts.map(row => [row.slug, row.state, row.shadow])).toEqual([
+ [ENTITY, 'committed', null], ['__managed_facts_complete__', 'committed', null],
+ [ENTITY, 'committed', '1'], ['__managed_facts_complete__', 'committed', '1'],
+ ]);
+ expect(calls).toBe(2);
+
+ const replay = await s.extract('Alice Example is the lead of the example company platform team', requestId);
+ expect(replay.would_dedup_same_page).toBe(1);
+ expect(replay.inserted).toBe(1);
+ expect(calls).toBe(2);
+ expect(await s.rows()).toEqual(rows);
+ expect(await s.receipts()).toEqual(receipts);
+ expect(warned.filter(line => line.includes('#6333 shadow'))).toHaveLength(1);
+ } finally { console.warn = original; }
+ });
+ }, 120_000);
+
+ test('another visibility, another lane and another session are never counted; every fact is kept', async () => {
+ await onEachEngine(async engine => {
+ for (const [label, seed] of [
+ ['visibility', { fact: 'Alice Example moved the weekly sync to Tuesday mornings', visibility: 'private' as const }],
+ ['lane', { fact: 'Alice Example moved the weekly sync to Tuesday mornings', source: 'fixture:import' }],
+ ['session', { fact: 'Alice Example moved the weekly sync to Tuesday mornings', session: 'sync:another-example' }],
+ ] as const) {
+ const s = await managedSource(engine, [seed]);
+ const r = await s.extract('Alice Example shifted the weekly sync to Tuesday mornings');
+ expect(r.would_dedup_same_page ?? 0, label).toBe(0);
+ expect(r.inserted, label).toBe(1);
+ expect((await s.rows()).map(row => row.fact), label).toEqual([seed.fact, 'Alice Example shifted the weekly sync to Tuesday mornings']);
+ expect((await s.receipts()).map(row => row.shadow), label).toEqual([null, null]);
+ }
+ const same = await managedSource(engine, [{ fact: 'Alice Example moved the weekly sync to Tuesday mornings' }]);
+ const counted = await same.extract('Alice Example shifted the weekly sync to Tuesday mornings');
+ expect(counted.would_dedup_same_page).toBe(1);
+ expect(await same.rows()).toHaveLength(2);
+ });
+ }, 120_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index eff284878b..51841cc892 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -14,6 +14,7 @@
test/activation-unbound-rooted-6449.test.ts
test/alias-source-cascade-5094.test.ts
test/attribution-backfill-history.test.ts
+test/backstop-same-page-shadow-managed-6333.test.ts
test/behavior-change-notice.test.ts
test/capture-consent-admission.test.ts
test/capture-dispatch-provenance-6524.test.ts