Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(decide): relinked-fact sweep handoff, fair deferred queue, chronological pair order (#5836)

garrytan6b72794008f5
diff --git a/docs/architecture/key-files/core-decide.md b/docs/architecture/key-files/core-decide.md
index 1388fd009d..3ff299883c 100644
--- a/docs/architecture/key-files/core-decide.md
+++ b/docs/architecture/key-files/core-decide.md
@@ -67,9 +67,9 @@ The capability contract (API, providers, egress, extension points) is `docs/arch
- `src/commands/decide/writepath.ts` — write-path lane registrations (what-if reducers for triage and grounding, dataset adapters; S9 subcommands), loaded by `loadDecideLanes()` in `src/commands/decide.ts` before any subcommand or help.
-- `src/core/ai/decide/conflict.ts` — S9's question (`duplicate | supersede | independent`, state = the new fact, one choice per candidate), the ONE pair reducer `reduceConflict` (chosen duplicate at or above threshold → duplicate; else P(supersede) at or above `decide.slots.conflict.proposal_floor` → proposal; else independent), candidate eligibility (the `decideSingleFact` guards, self-exclusion, cosine ≥ 0.80), unordered pair keys, proposal direction and `sweepWindow` (stops at the first fact younger than 60 s).
+- `src/core/ai/decide/conflict.ts` — S9's question (`duplicate | supersede | independent`, state = the new fact, one choice per candidate), the ONE pair reducer `reduceConflict` (chosen duplicate at or above threshold → duplicate; else P(supersede) at or above `decide.slots.conflict.proposal_floor` → proposal; else independent), candidate eligibility (the `decideSingleFact` guards, self-exclusion, cosine ≥ 0.80), unordered pair keys, proposal direction, chronology (`isOlderFact`: valid_from, then created_at, then id; `datedConflictState`/`datedConflictQuestion` add `fact_time`/`candidate_time` evidence for a reordered pair) and `sweepWindow` (stops at the first fact younger than 60 s).
-- `src/core/ai/decide/sweep.ts` (+ `proposals-store.ts`) — `runConflictSweep`: per-source watermark in `decide_state` (first run records the max fact id unless `since`), deferred retries first (attempt cap 5), neighbours filtered BEFORE the k=5 limit by one `executeRaw` query, pairs deduped within the sweep and across sweeps (answered receipts by hashed pair subject, existing proposals), one background-lane request per fact, drift and inactive policy run with off behavior, pending `decide_proposals` rows in `on` mode only; never supersedes. `conflictSweepTail` is the `extract_facts` phase tail: undefined when the slot is off. `proposals-store.ts` holds the watermark, deferred, dedup and proposal SQL. Tests: `test/decide/conflict-sweep.serial.test.ts`.
+- `src/core/ai/decide/sweep.ts` (+ `proposals-store.ts`) — `runConflictSweep`: per-source watermark in `decide_state` (first run records the max fact id unless `since`), deferred retries first (attempt cap 5, oldest due first so a relinked backlog never starves a transient retry), neighbours filtered BEFORE the k=5 limit by one `executeRaw` query, pairs deduped within the sweep and across sweeps (answered receipts by hashed pair subject, existing proposals), one background-lane request per fact for its older neighbours plus one per neighbour newer than the fact (that neighbour is presented as the new claim with both timestamps, so a proposal always retires the older fact), drift and inactive policy run with off behavior, pending `decide_proposals` rows in `on` mode only; never supersedes. `conflictSweepTail` is the `extract_facts` phase tail: undefined when the slot is off. `proposals-store.ts` holds the watermark, deferred, dedup and proposal SQL, and `enqueueRelinked(engine, sourceId, factIds)` (the `gbrain facts relink` handoff: attempts 0, due now, reason `relinked`, `ON CONFLICT DO NOTHING`, run on the caller's transaction engine). Tests: `test/decide/conflict-sweep.serial.test.ts`, `test/decide/conflict-relink-handoff.serial.test.ts`.
- `src/core/ai/decide/datasets-conflict.ts` — `registerConflictDatasets()` (called by `src/commands/decide/writepath.ts`): the conflict dataset adapter (production request shape, no harmful-action reducer) and the `facts-fixtures` builder (labelled fact-pair JSONL; label `true` exactly for `duplicate`, the calibrated threshold). Calibration thresholds the reducer-consistent `duplicateValue` (P(chosen) only when duplicate is chosen) and `calibrateProposalFloor` picks the F1-best P(supersede) floor on the choice label kept in `slice` (≥ 10 supersede labels), stored in the row's notes. Tests: `test/decide/conflict-calibration.test.ts`.
diff --git a/src/core/ai/decide/conflict.ts b/src/core/ai/decide/conflict.ts
index 92fda030d4..ee87b5ecc4 100644
--- a/src/core/ai/decide/conflict.ts
+++ b/src/core/ai/decide/conflict.ts
@@ -40,6 +40,29 @@ export function factEvidence(f: ConflictFact): EvidenceItem {
return { text: f.fact, class: 'facts', fact_id: f.id, source_id: f.source_id, visibility: f.visibility };
}
+/** A fact with the timestamps the sweep orders a pair by. */
+export interface DatedConflictFact extends ConflictFact {
+ valid_from: Date | string;
+ created_at: Date | string;
+}
+
+const iso = (v: Date | string) => new Date(v).toISOString();
+
+/** The fact's timestamps as evidence with the fact's own provenance (egress judges it exactly like the fact). */
+function timeEvidence(f: DatedConflictFact): EvidenceItem {
+ return { ...factEvidence(f), text: `valid from ${iso(f.valid_from)}; recorded ${iso(f.created_at)}` };
+}
+
+/**
+ * True when `a` is older than `b`: valid_from, then created_at, then id. The sweep presents the newer fact of a pair
+ * as `fact`, so a proposal always retires the older one, even when the older fact is the one being swept (a fact
+ * that just gained an entity through `gbrain facts relink`).
+ */
+export function isOlderFact(a: DatedConflictFact, b: DatedConflictFact): boolean {
+ const ms = (v: Date | string) => new Date(v).getTime();
+ return (ms(a.valid_from) - ms(b.valid_from) || ms(a.created_at) - ms(b.created_at) || a.id - b.id) < 0;
+}
+
export function conflictState(f: ConflictFact): Record<string, EvidenceItem> {
return { fact: factEvidence(f) };
}
@@ -48,6 +71,17 @@ export function conflictQuestion(id: string, rank: number, candidate: ConflictFa
return { id, kind: 'choice', rank, instructions: CONFLICT_INSTRUCTIONS, options: { ...CONFLICT_OPTIONS }, inputs: { candidate: factEvidence(candidate) } };
}
+/** The state of a pair the sweep reordered by chronology: the newer fact plus its timestamps (`fact_time`). */
+export function datedConflictState(f: DatedConflictFact): Record<string, EvidenceItem> {
+ return { ...conflictState(f), fact_time: timeEvidence(f) };
+}
+
+/** The question of a reordered pair: the older (swept) fact as `candidate` plus its timestamps (`candidate_time`). */
+export function datedConflictQuestion(id: string, rank: number, candidate: DatedConflictFact): DecideQuestion {
+ const q = conflictQuestion(id, rank, candidate);
+ return { ...q, inputs: { ...q.inputs, candidate_time: timeEvidence(candidate) } };
+}
+
/** P(supersede) for the proposal floor: the reported probability, else the confidence when supersede was chosen. */
export function supersedeProbability(answer: ChoiceAnswer): number {
return answer.probabilities.supersede ?? (answer.choice === 'supersede' ? answer.confidence : 0);
diff --git a/src/core/ai/decide/proposals-store.ts b/src/core/ai/decide/proposals-store.ts
index b31bf38660..1582e90402 100644
--- a/src/core/ai/decide/proposals-store.ts
+++ b/src/core/ai/decide/proposals-store.ts
@@ -35,11 +35,12 @@ export interface SweepFact {
entity_slug: string | null;
fact: string;
visibility: 'private' | 'world';
+ valid_from: Date | string;
created_at: Date | string;
has_embedding: boolean;
}
-const SWEEP_FACT_COLUMNS = `id, source_id, entity_slug, fact, visibility, created_at,
+const SWEEP_FACT_COLUMNS = `id, source_id, entity_slug, fact, visibility, valid_from, created_at,
(embedding IS NOT NULL AND embedding_model IS NOT NULL AND embedded_text_hash = md5(fact)) AS has_embedding`;
const ACTIVE = `expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) AND source <> ALL($2::text[])`;
@@ -74,6 +75,8 @@ export interface ConflictCandidateRow {
expired_at: Date | string | null;
valid_until: Date | string | null;
source_markdown_slug: string | null;
+ valid_from: Date | string;
+ created_at: Date | string;
similarity: number;
}
@@ -87,7 +90,7 @@ export interface ConflictCandidateRow {
export async function conflictNeighbours(engine: BrainEngine, factId: number, sourceId: string): Promise<ConflictCandidateRow[]> {
const rows = await engine.executeRaw<ConflictCandidateRow>(
`SELECT c.id, c.source_id, c.entity_slug, c.fact, c.visibility, c.expired_at, c.valid_until, c.source_markdown_slug,
- (1 - (c.embedding <=> n.embedding))::float8 AS similarity
+ c.valid_from, c.created_at, (1 - (c.embedding <=> n.embedding))::float8 AS similarity
FROM facts n JOIN facts c
ON c.source_id = n.source_id AND c.entity_slug = n.entity_slug AND c.visibility = n.visibility AND c.id <> n.id
WHERE n.id = $1 AND n.source_id = $3
@@ -103,14 +106,16 @@ export async function conflictNeighbours(engine: BrainEngine, factId: number, so
}
// ---------------------------------------------------------------------------
-// Deferred retries (transient skips: no_embedding, provider failure)
+// Deferred retries (transient skips: no_embedding, provider failure) and
+// relinked facts handed over by `gbrain facts relink`
// ---------------------------------------------------------------------------
+/** Due retries, oldest due first (fact id breaks ties), so a large relinked backlog never starves a transient retry. */
export async function dueDeferred(engine: BrainEngine, sourceId: string, limit: number): Promise<Array<{ fact_id: number; attempts: number }>> {
const rows = await engine.executeRaw<{ fact_id: number | string; attempts: number | string }>(
`SELECT fact_id, attempts FROM decide_sweep_deferred
WHERE slot = 'conflict' AND source_id = $1 AND attempts < $2 AND next_attempt_at <= now()
- ORDER BY fact_id LIMIT $3`,
+ ORDER BY next_attempt_at, fact_id LIMIT $3`,
[sourceId, DEFERRED_MAX_ATTEMPTS, limit],
);
return rows.map((r) => ({ fact_id: Number(r.fact_id), attempts: Number(r.attempts) }));
@@ -127,6 +132,22 @@ export async function deferFact(engine: BrainEngine, sourceId: string, factId: n
);
}
+/**
+ * Queue facts that just gained an entity for the next conflict sweep: attempts 0, due now, reason `relinked`.
+ * An existing row (a pending transient retry) is left untouched. Pass the caller's transaction engine so the
+ * handoff commits with the relink write. Returns the number of rows queued.
+ */
+export async function enqueueRelinked(engine: BrainEngine, sourceId: string, factIds: readonly number[]): Promise<number> {
+ if (factIds.length === 0) return 0;
+ const rows = await engine.executeRaw<{ fact_id: number | string }>(
+ `INSERT INTO decide_sweep_deferred (source_id, fact_id, slot, reason, attempts, next_attempt_at)
+ SELECT $1, ids.id::bigint, 'conflict', 'relinked', 0, now() FROM unnest($2::text[]) AS ids(id)
+ ON CONFLICT (slot, source_id, fact_id) DO NOTHING RETURNING fact_id`,
+ [sourceId, factIds.map(String)],
+ );
+ return rows.length;
+}
+
export async function clearDeferred(engine: BrainEngine, sourceId: string, factId: number): Promise<void> {
await engine.executeRaw(`DELETE FROM decide_sweep_deferred WHERE slot = 'conflict' AND source_id = $1 AND fact_id = $2`, [sourceId, factId]);
}
diff --git a/src/core/ai/decide/sweep.ts b/src/core/ai/decide/sweep.ts
index 788a4e418a..2b590ac48c 100644
--- a/src/core/ai/decide/sweep.ts
+++ b/src/core/ai/decide/sweep.ts
@@ -11,22 +11,25 @@
* Scope: the first run records the current max fact id and sweeps nothing
* unless `since` is given. The watermark only advances past facts created
* more than 60 s ago. Transient skips (no embedding, provider failure) go to
- * decide_sweep_deferred and are retried with an attempt cap.
+ * decide_sweep_deferred and are retried with an attempt cap; `gbrain facts
+ * relink` queues facts that just gained an entity there too (enqueueRelinked).
+ * A pair is always presented newer fact first (valid_from, then created_at),
+ * so a relinked older fact never becomes the claim that retires a newer one.
*/
import { randomBytes } from 'node:crypto';
import type { BrainEngine } from '../../engine.ts';
import { loadConfigSnapshot } from '../../config-snapshot.ts';
import { readDecideConfig, type DecideConfig } from './config.ts';
import {
- CONFLICT_INSTRUCTIONS, CONFLICT_OPTIONS, DEFAULT_PROPOSAL_FLOOR, conflictQuestion, conflictState, eligibleCandidate, pairKey,
- proposalDirection, reduceConflict, supersedeProbability, sweepWindow, type ConflictOutcome,
+ CONFLICT_INSTRUCTIONS, CONFLICT_OPTIONS, DEFAULT_PROPOSAL_FLOOR, conflictQuestion, conflictState, datedConflictQuestion,
+ datedConflictState, eligibleCandidate, isOlderFact, pairKey, proposalDirection, reduceConflict, supersedeProbability, sweepWindow, type ConflictOutcome,
} from './conflict.ts';
import { hasTypesafeKey, runDecide } from './index.ts';
import { packShape } from './pack.ts';
import { driftReason, resolveSlotPolicy, type SlotPolicy } from './policy.ts';
import {
answeredPairRefs, clearDeferred, conflictNeighbours, deferFact, dueDeferred, factsAfter, factsByIds, getSweepWatermark,
- insertProposal, maxFactId, proposedPairs, setSweepWatermark, type SweepFact,
+ insertProposal, maxFactId, proposedPairs, setSweepWatermark, type ConflictCandidateRow, type SweepFact,
} from './proposals-store.ts';
import { writeReceipts } from './receipts.ts';
import { flushDecideWrites, hmacRef, listCalibrations, receiptSalt, recentResolvedModels } from './store.ts';
@@ -135,31 +138,20 @@ function fallbackPolicyFor(ctx: SweepContext): SlotPolicy {
});
}
-/** Judge one fact; returns false when the sweep must stop (daily budget spent, caller abort). */
-async function sweepFact(ctx: SweepContext, fact: SweepFact, retry: boolean): Promise<boolean> {
+type PairFact = SweepFact | ConflictCandidateRow;
+
+/**
+ * One request: `claim` is presented as `fact` and judged against each of `others` as `candidate`. A proposal
+ * would retire the `candidate`. `dated` marks a pair reordered by chronology (the swept fact is the older one),
+ * whose evidence carries both facts' timestamps. Returns 'error' after a failed request (the swept fact is
+ * deferred unless the failure is permanent) and 'stop' when the sweep must stop.
+ */
+async function judgePairs(ctx: SweepContext, fact: SweepFact, claim: PairFact, others: readonly PairFact[], dated: boolean):
+ Promise<'answered' | 'unanswered' | 'error' | 'stop'> {
const { engine, result } = ctx;
- result.facts++;
- if (!fact.entity_slug) {
- factReceipt(ctx, fact, 'skipped', 'no_entity');
- result.skipped++;
- if (retry) await clearDeferred(engine, fact.source_id, fact.id);
- return true;
- }
- if (!fact.has_embedding) {
- factReceipt(ctx, fact, 'skipped', 'no_embedding');
- await deferFact(engine, fact.source_id, fact.id, 'no_embedding');
- result.skipped++;
- result.deferred++;
- return true;
- }
- const candidates = await candidatesFor(ctx, fact);
- if (candidates.length === 0) {
- if (retry) await clearDeferred(engine, fact.source_id, fact.id);
- return true;
- }
- const questions = candidates.map((c, i) => conflictQuestion(`conflict:${i}`, i, c));
- const subjects = Object.fromEntries(candidates.map((c, i) => [`conflict:${i}`, pairKey(fact.source_id, fact.id, c.id)]));
- const state = conflictState(fact);
+ const questions = others.map((c, i) => dated ? datedConflictQuestion(`conflict:${i}`, i, c) : conflictQuestion(`conflict:${i}`, i, c));
+ const subjects = Object.fromEntries(others.map((c, i) => [`conflict:${i}`, pairKey(fact.source_id, claim.id, c.id)]));
+ const state = dated ? datedConflictState(claim) : conflictState(claim);
const base = { slot: 'conflict' as const, callSite: 'sweep', lane: 'background' as const, state, subjects, sourceId: fact.source_id };
let r: DecideResult;
try {
@@ -173,8 +165,8 @@ async function sweepFact(ctx: SweepContext, fact: SweepFact, retry: boolean): Pr
await deferFact(engine, fact.source_id, fact.id, reason);
result.deferred++;
}
- if (reason === 'budget_exhausted' || ctx.signal?.aborted) { result.stopped = ctx.signal?.aborted ? 'aborted' : reason; return false; }
- return true;
+ if (reason === 'budget_exhausted' || ctx.signal?.aborted) { result.stopped = ctx.signal?.aborted ? 'aborted' : reason; return 'stop'; }
+ return 'error';
}
const primaryIds = questions.filter((q) => !r.fallback?.answers[q.id]).map((q) => q.id);
const fallbackIds = questions.filter((q) => r.fallback?.answers[q.id]).map((q) => q.id);
@@ -186,19 +178,19 @@ async function sweepFact(ctx: SweepContext, fact: SweepFact, retry: boolean): Pr
for (const id of ids) {
const answer = sub.answers[id];
if (skip || !answer || answer.kind !== 'choice') continue;
- const candidate = candidates[Number(id.split(':')[1])]!;
+ const candidate = others[Number(id.split(':')[1])]!;
const outcome = reduceConflict(answer, { threshold: policy.threshold, proposalFloor: ctx.floor });
outcomes[id] = outcome;
answeredAny = true;
- ctx.judged.add(pairKey(fact.source_id, fact.id, candidate.id));
+ ctx.judged.add(pairKey(fact.source_id, claim.id, candidate.id));
result.pairs++;
if (outcome === 'duplicate') result.duplicates++;
else if (outcome === 'independent') result.independents++;
else if (policy.effective !== 'on') result.shadow_proposals++;
else {
const proposalId = await insertProposal(engine, {
- source_id: fact.source_id, sweep_id: ctx.sweepId, pair_index: ctx.pairIndex++, new_fact_id: fact.id, old_fact_id: candidate.id,
- direction: proposalDirection(fact.id, candidate.id), p_supersede: supersedeProbability(answer), threshold: policy.threshold ?? null,
+ source_id: fact.source_id, sweep_id: ctx.sweepId, pair_index: ctx.pairIndex++, new_fact_id: claim.id, old_fact_id: candidate.id,
+ direction: proposalDirection(claim.id, candidate.id), p_supersede: supersedeProbability(answer), threshold: policy.threshold ?? null,
proposal_floor: ctx.floor, model_resolved: sub.model_resolved || null,
});
if (proposalId !== null) result.proposals++;
@@ -211,6 +203,47 @@ async function sweepFact(ctx: SweepContext, fact: SweepFact, retry: boolean): Pr
};
await judge(primaryIds, ctx.policy, r);
if (r.fallback) await judge(fallbackIds, fallbackPolicyFor(ctx), r.fallback);
+ return answeredAny ? 'answered' : 'unanswered';
+}
+
+/**
+ * Judge one fact; returns false when the sweep must stop (daily budget spent, caller abort). Neighbours older than
+ * the fact share one request with the fact as the new claim; each neighbour newer than the fact gets its own
+ * request with that neighbour as the new claim, so a proposal never retires the newer fact.
+ */
+async function sweepFact(ctx: SweepContext, fact: SweepFact, retry: boolean): Promise<boolean> {
+ const { engine, result } = ctx;
+ result.facts++;
+ if (!fact.entity_slug) {
+ factReceipt(ctx, fact, 'skipped', 'no_entity');
+ result.skipped++;
+ if (retry) await clearDeferred(engine, fact.source_id, fact.id);
+ return true;
+ }
+ if (!fact.has_embedding) {
+ factReceipt(ctx, fact, 'skipped', 'no_embedding');
+ await deferFact(engine, fact.source_id, fact.id, 'no_embedding');
+ result.skipped++;
+ result.deferred++;
+ return true;
+ }
+ const candidates = await candidatesFor(ctx, fact);
+ if (candidates.length === 0) {
+ if (retry) await clearDeferred(engine, fact.source_id, fact.id);
+ return true;
+ }
+ const older = candidates.filter((c) => !isOlderFact(fact, c));
+ const requests: Array<[PairFact, readonly PairFact[], boolean]> = [
+ ...(older.length > 0 ? [[fact, older, false] as [PairFact, readonly PairFact[], boolean]] : []),
+ ...candidates.filter((c) => isOlderFact(fact, c)).map((c): [PairFact, readonly PairFact[], boolean] => [c, [fact], true]),
+ ];
+ let answeredAny = false;
+ for (const [claim, others, dated] of requests) {
+ const outcome = await judgePairs(ctx, fact, claim, others, dated);
+ if (outcome === 'stop') return false;
+ if (outcome === 'error') return true;
+ answeredAny ||= outcome === 'answered';
+ }
if (!answeredAny) result.skipped++;
if (retry) await clearDeferred(engine, fact.source_id, fact.id);
return true;
diff --git a/test/decide/conflict-relink-handoff.serial.test.ts b/test/decide/conflict-relink-handoff.serial.test.ts
new file mode 100644
index 0000000000..9594e9496f
--- /dev/null
+++ b/test/decide/conflict-relink-handoff.serial.test.ts
@@ -0,0 +1,195 @@
+/**
+ * #5836 conflict-sweep handoff for relinked facts, on PGLite with a fixture
+ * decide transport (no provider is called).
+ *
+ * Protects: enqueueRelinked queues facts with attempts 0, due now, reason
+ * `relinked`, inside the caller's transaction, and never touches an existing
+ * deferred row; dueDeferred orders by due time so a large relinked backlog
+ * never starves a transient retry; the sweep picks a relinked fact up through
+ * the deferred path and judges it; when the swept fact is older than its
+ * neighbour (valid_from, then created_at) the newer fact is presented as the
+ * new claim, both timestamps ride in the evidence, and a proposal would
+ * retire the older fact.
+ * Serial: mutates the process-global gateway.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { writeSingleFact } from '../../src/core/facts/write-single.ts';
+import { configureGateway, resetGateway, __setDecideTransportForTests, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';
+import { deferFact, dueDeferred, enqueueRelinked, maxFactId, setSweepWatermark } from '../../src/core/ai/decide/proposals-store.ts';
+import { SWEEP_MAX_FACTS, runConflictSweep } from '../../src/core/ai/decide/sweep.ts';
+
+let engine: PGLiteEngine;
+const SLUG = 'people/alice-example';
+const DIM = 1536;
+const LATER = () => Date.now() + 120_000;
+
+function embed(text: string): number[] {
+ const v = new Array(DIM).fill(0);
+ const g = /\[g(\d+)\]/.exec(text);
+ const m = /\[v(\d+)\]/.exec(text);
+ if (!g) { v[1000 + ([...text].reduce((n, c) => n + c.charCodeAt(0), 0) % 400)] = 1; return v; }
+ v[Number(g[1]) * 20] = 1;
+ if (m) v[Number(g[1]) * 20 + 1 + Number(m[1])] = 0.4;
+ return v;
+}
+
+let bodies: any[] = [];
+function supersedeTransport() {
+ __setDecideTransportForTests(async (_url, init) => {
+ const body = JSON.parse(init.body as string);
+ bodies.push(body);
+ const probabilities = { duplicate: 0.1, supersede: 0.8, independent: 0.1 };
+ const answers = Object.fromEntries(Object.keys(body.questions).map((id) => [id, { type: 'choice', choice: 'supersede', confidence: 0.8, probabilities }]));
+ return new Response(JSON.stringify({ model: 'jev-1.13.0', answers, usage: { input_tokens: 50, output_tokens: 5 } }));
+ });
+}
+
+const ON = {
+ 'decide.provider': 'typesafe:jev-1.13.0', 'decide.slots.conflict.mode': 'on', 'decide.slots.conflict.threshold': '0.8',
+ 'decide.egress.typesafe.facts': 'allow', 'decide.egress.private': 'allow',
+};
+
+async function remember(fact: string, entity: string | null = SLUG): Promise<number> {
+ const r = await writeSingleFact(engine, 'default', { fact, provenance: 'test', entity, kind: 'fact' });
+ expect(r.status).toBe('inserted');
+ return r.id;
+}
+
+async function deferredRows() {
+ return (await engine.executeRaw<{ fact_id: string; reason: string; attempts: number; due: boolean }>(
+ `SELECT fact_id, reason, attempts, next_attempt_at <= now() AS due FROM decide_sweep_deferred ORDER BY fact_id`))
+ .map((r) => ({ fact_id: Number(r.fact_id), reason: r.reason, attempts: Number(r.attempts), due: r.due === true || (r.due as unknown) === 't' }));
+}
+
+/** A relinked fact: written without an entity (it never reached the sweep), backdated, then given its entity. */
+async function relinkedFact(fact: string, daysOld: number): Promise<number> {
+ const id = await remember(fact, null);
+ await engine.executeRaw(
+ `UPDATE facts SET entity_slug = $2, valid_from = now() - ($3::int * interval '1 day'), created_at = now() - ($3::int * interval '1 day') WHERE id = $1`,
+ [id, SLUG, daysOld]);
+ return id;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ __setDecideTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ __resetDecideStoreForTests();
+ bodies = [];
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIM, env: { OPENAI_API_KEY: 'sk-test', TYPESAFE_API_KEY: 'sk-test-typesafe' } });
+ __setEmbedTransportForTests((async (opts: { values: string[] }) => ({ embeddings: opts.values.map(embed) })) as never);
+ await importFromContent(engine, SLUG, `---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\nA person.\n`, { noEmbed: true, sourceId: 'default' });
+});
+
+afterEach(() => { __setDecideTransportForTests(null); });
+
+describe('enqueueRelinked', () => {
+ test('queues attempts 0, due now, reason relinked; an existing row is left unchanged', async () => {
+ await deferFact(engine, 'default', 7, 'no_embedding');
+ const before = await engine.executeRaw('SELECT * FROM decide_sweep_deferred WHERE fact_id = 7');
+ const queued = await engine.transaction((tx) => enqueueRelinked(tx, 'default', [5, 7, 9]));
+ expect(queued).toBe(2);
+ expect(await deferredRows()).toEqual([
+ { fact_id: 5, reason: 'relinked', attempts: 0, due: true },
+ { fact_id: 7, reason: 'no_embedding', attempts: 1, due: false },
+ { fact_id: 9, reason: 'relinked', attempts: 0, due: true },
+ ]);
+ expect(await engine.executeRaw('SELECT * FROM decide_sweep_deferred WHERE fact_id = 7')).toEqual(before);
+ expect((await dueDeferred(engine, 'default', 10)).map((d) => d.fact_id)).toEqual([5, 9]);
+ expect(await enqueueRelinked(engine, 'default', [5, 9])).toBe(0);
+ expect((await deferredRows()).filter((r) => r.reason === 'relinked').every((r) => r.attempts === 0)).toBe(true);
+ expect(await enqueueRelinked(engine, 'default', [])).toBe(0);
+ });
+
+ test('rides the caller transaction: a rolled-back relink queues nothing', async () => {
+ await expect(engine.transaction(async (tx) => {
+ await enqueueRelinked(tx, 'default', [11, 12]);
+ throw new Error('relink write failed');
+ })).rejects.toThrow('relink write failed');
+ expect(await deferredRows()).toEqual([]);
+ });
+});
+
+describe('deferred-queue fairness', () => {
+ test('500 relinked rows and one transient retry: the transient drains within one sweep quota', async () => {
+ await deferFact(engine, 'default', 10_000, 'timeout');
+ await engine.executeRaw(`UPDATE decide_sweep_deferred SET next_attempt_at = now() - interval '1 minute' WHERE fact_id = 10000`);
+ await enqueueRelinked(engine, 'default', Array.from({ length: 500 }, (_, i) => i + 1));
+ const due = await dueDeferred(engine, 'default', SWEEP_MAX_FACTS);
+ expect(due).toHaveLength(SWEEP_MAX_FACTS);
+ expect(due[0]).toEqual({ fact_id: 10_000, attempts: 1 });
+ expect(due.slice(1).map((d) => d.fact_id)).toEqual(Array.from({ length: SWEEP_MAX_FACTS - 1 }, (_, i) => i + 1));
+ });
+});
+
+describe('sweep pickup and chronology', () => {
+ test('a relinked fact with an embedding is picked up from the deferred queue and judged', async () => {
+ const neighbour = await remember('[g1][v1] Alice leads research');
+ const relinked = await relinkedFact('[g1][v2] Alice leads design', 0);
+ await engine.executeRaw(`UPDATE facts SET valid_from = now() - interval '1 day', created_at = now() - interval '1 day' WHERE id = $1`, [neighbour]);
+ const [row] = await engine.executeRaw<{ ok: boolean }>(`SELECT (embedding IS NOT NULL AND embedded_text_hash = md5(fact)) AS ok FROM facts WHERE id = $1`, [relinked]);
+ expect(row!.ok).toBe(true);
+ for (const [k, v] of Object.entries(ON)) await engine.setConfig(k, v);
+ await setSweepWatermark(engine, 'default', await maxFactId(engine, 'default'));
+ expect(await enqueueRelinked(engine, 'default', [relinked])).toBe(1);
+ supersedeTransport();
+ const r = await runConflictSweep(engine, { now: LATER });
+ expect(r).toMatchObject({ retried: 1, facts: 1, pairs: 1, proposals: 1 });
+ expect(bodies).toHaveLength(1);
+ expect(await deferredRows()).toEqual([]);
+ const [p] = await engine.executeRaw<{ new_fact_id: string; old_fact_id: string }>('SELECT new_fact_id, old_fact_id FROM decide_proposals');
+ expect([Number(p!.new_fact_id), Number(p!.old_fact_id)]).toEqual([relinked, neighbour]);
+ });
+
+ test('an older relinked fact judged against a newer neighbour: the newer fact is the claim and the proposal retires the older one', async () => {
+ const newer = await remember('[g1][v1] Alice now leads design');
+ const older = await relinkedFact('[g1][v2] Alice leads research', 30);
+ expect(older).toBeGreaterThan(newer);
+ for (const [k, v] of Object.entries(ON)) await engine.setConfig(k, v);
+ await setSweepWatermark(engine, 'default', await maxFactId(engine, 'default'));
+ await enqueueRelinked(engine, 'default', [older]);
+ supersedeTransport();
+ const r = await runConflictSweep(engine, { now: LATER });
+ expect(r).toMatchObject({ retried: 1, pairs: 1, proposals: 1 });
+ const [p] = await engine.executeRaw<{ new_fact_id: string; old_fact_id: string; direction: string }>('SELECT new_fact_id, old_fact_id, direction FROM decide_proposals');
+ expect({ new: Number(p!.new_fact_id), retires: Number(p!.old_fact_id) }).toEqual({ new: newer, retires: older });
+ const [body] = bodies;
+ expect(body.state.fact).toBe('[g1][v1] Alice now leads design');
+ const [q] = Object.values(body.questions) as any[];
+ expect(q.instructions.candidate).toBe('[g1][v2] Alice leads research');
+ const [times] = await engine.executeRaw<{ newer_from: Date; older_from: Date }>(
+ 'SELECT n.valid_from AS newer_from, o.valid_from AS older_from FROM facts n, facts o WHERE n.id = $1 AND o.id = $2', [newer, older]);
+ expect(body.state.fact_time).toContain(`valid from ${new Date(times!.newer_from).toISOString()}`);
+ expect(q.instructions.candidate_time).toContain(`valid from ${new Date(times!.older_from).toISOString()}`);
+ });
+
+ test('a fact newer than its neighbours keeps the packed request with no timestamps (unchanged shape)', async () => {
+ const old = await remember('[g1][v1] Alice leads research');
+ await engine.executeRaw(`UPDATE facts SET valid_from = now() - interval '1 day', created_at = now() - interval '1 day' WHERE id = $1`, [old]);
+ const fresh = await remember('[g1][v2] Alice now leads design');
+ await engine.executeRaw(`UPDATE facts SET created_at = now() - interval '5 minutes' WHERE id = $1`, [fresh]);
+ for (const [k, v] of Object.entries(ON)) await engine.setConfig(k, v);
+ supersedeTransport();
+ const r = await runConflictSweep(engine, { since: fresh - 1, now: LATER });
+ expect(r).toMatchObject({ facts: 1, proposals: 1 });
+ expect(Object.keys(bodies[0].state)).toEqual(['fact']);
+ expect(Object.keys((Object.values(bodies[0].questions)[0] as any).instructions)).toEqual(['task', 'candidate']);
+ const [p] = await engine.executeRaw<{ new_fact_id: string; old_fact_id: string }>('SELECT new_fact_id, old_fact_id FROM decide_proposals');
+ expect([Number(p!.new_fact_id), Number(p!.old_fact_id)]).toEqual([fresh, old]);
+ });
+});