Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): loops_close retires the commitment fact through the coordinator (#5869)
garrytan38db5411624a
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 42c4b63f99..7fcabd43e9 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -69,6 +69,7 @@ src/core/facts/fence-write.ts 2 coordinator Managed brains publish fence rows thsrc/core/facts/forget.ts 4 filesystem_guard Managed callers journal withdrawal; legacy filesystem helper and the supersession-only expiry require coordinated write.src/core/facts/proposal-supersede.ts 4 filesystem_guard System One S9 accept/undo (local CLI only): unmanaged brains update the two facts rows and strike or restore the fence row in one transaction under the source filesystem lock and page lock, publishing the file last; managed brains run the same change as the coordinator mutation decide_proposal.src/core/facts/relink-publish.ts 2 coordinator #5836 facts relink (local CLI only, managed or not): the coordinator mutation relink_facts re-locks each pinned unlinked fact, moves linked rows onto their entity fence positions (and retires exact duplicates expired and detached) ahead of the page's canonical projection in the same publication, then restores take resolutions and records the attempt and conflict-sweep handoff in that transaction.+src/core/persistence/loop-fact-retirement.ts 1 coordinator #5869 loops_close fact retirement (managed or not, local or write-bound remote): the coordinator mutation (operation loops_close, intent retire_loop_fact) expires the commitment fact and strikes its fence row through the entity page publication in one transaction, only when the fact is in the loop's source and no other open loop references it.src/core/facts/withdrawal-schema.ts 1 schema Migration v174 DDL/backfill expires fact rows that match a folded withdrawal fingerprint; schema installation runs under coordinated activation, which quiesces canonical writers.src/core/facts/withdrawal.ts 2 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.src/core/facts/write-single.ts 2 coordinator Managed brains publish the single fact through the managed_facts_entity intent before the legacy supersession or DB-only insert; those legacy writes run only unmanaged and stay trigger-guarded.@@ -82,7 +83,6 @@ src/core/minions/handlers/ingest-capture.ts 3 engine_guard Canonical table SQL tsrc/core/onboard/checks.ts 2 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.src/core/ops/extraction.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/ops/links.ts 3 coordinator Unmanaged add_link/remove_link keep the engine calls; a managed brain takes coordinatedManualLinkWrite, which checks durable write authority for the from page and commits the database-only edge inside a source-scoped withCoordinatedWrite transaction holding both endpoint page keys.-src/core/ops/loops.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/ops/pages.ts 0 coordinator Page mutations delegate to persistence modules; purge_deleted_pages runs purgeDeletedPagesCoordinated.src/core/output/writer.ts 6 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/page-state/materialize.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex 633dbdaa52..e12a13787d 100644--- a/docs/architecture/managed-mutating-writers.tsv+++ b/docs/architecture/managed-mutating-writers.tsv@@ -60,7 +60,7 @@ op migrate_embeddings no_canonical_write Embedding projections under the migratiop schema_apply_mutations no_canonical_write Schema-pack files outside the brain database.op run_onboard no_canonical_write Runs remediation steps; each step keeps its own writer boundary.op run_skillopt no_canonical_write Skill files and proposals outside the brain database.-op loops_close no_canonical_write open_loops state rows.+op loops_close coordinator open_loops state rows; the commitment fact is retired (expired, fence row struck) through the loop-fact-retirement coordinator mutation (#5869).op loops_mute no_canonical_write Loop suppression rows.op loops_unmute no_canonical_write Loop suppression rows.cli src/commands/enrich.ts coordinator gbrain enrich preflights maintenance authority, then publishMaintenancePage per page.diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 5f61fa6f51..979425ba8f 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -22,6 +22,7 @@import { OperationError, type Operation, type OperationContext } from './contract.ts';import { resolveRequestedScope, sourceScopeOpts } from './context.ts';import { validateSourceId } from '../utils.ts';+import { closedLoopWithActiveFact, retireLoopFact } from '../persistence/loop-fact-retirement.ts';import {addSuppression,closeOpenLoop,@@ -538,19 +539,15 @@ const loops_close: Operation = {p.id as number,p.status as 'done' | 'dropped',(p.note as string | undefined)?.slice(0, 200) || 'manual',- );+ ) ?? await closedLoopWithActiveFact(ctx.engine, sourceId, p.id as number);if (!row) return { closed: false, reason: 'not_found_or_already_closed' };- // A closed commitment loop expires its projected fact so entity cards- // stop carrying it (fence round-trip happens on the next facts sweep).- if (row.fact_id !== null) {- try {- await ctx.engine.executeRaw(- `UPDATE facts SET expired_at = now() WHERE id = $1 AND expired_at IS NULL`,- [row.fact_id],- );- } catch { /* best-effort */ }- }- return { closed: true, id: row.id, status: row.status, fact_expired: row.fact_id !== null };+ // #5869: a closed commitment loop retires its fact (expired + fence row+ // struck) through one coordinated publication. A loop already closed whose+ // fact is still active re-attempts it, so a refused retirement is retryable.+ if (row.fact_id === null) return { closed: true, id: row.id, status: row.status, fact_expired: false, retryable: false };+ const retired = await retireLoopFact(ctx, row.id);+ return { closed: true, id: row.id, status: row.status, fact_expired: retired.fact_expired, retryable: retired.retryable,+ ...(retired.reason && retired.reason !== 'already_expired' ? { reason: retired.reason } : {}) };},};diff --git a/src/core/persistence/loop-fact-retirement.ts b/src/core/persistence/loop-fact-retirement.tsnew file mode 100644index 0000000000..a4ae8d112d--- /dev/null+++ b/src/core/persistence/loop-fact-retirement.ts@@ -0,0 +1,195 @@+/**+ * Loop fact retirement (#5869): when a commitment loop closes, its projected+ * commitment fact is expired and its `## Facts` fence row struck, as one+ * coordinated publication on every brain (managed or not).+ *+ * `loops_close` used to expire the fact with raw SQL that `managed_writer_guard`+ * refuses on managed brains; the error was swallowed and the receipt said+ * `fact_expired: true`. It also never struck the fence row, so the database+ * row and the page diverged on unmanaged brains too. The retirement here is a+ * coordinator mutation (operation `loops_close`, intent `retire_loop_fact`),+ * following the `decide_proposal` and `relink_facts` precedent: the fact's+ * `expired_at`/`valid_until` and the struck fence row (a page publication of+ * the entity page) commit together or not at all. It is not a withdrawal: no+ * `fact_withdrawals` tombstone is written, so the same promise made again+ * later is stored normally.+ *+ * One rule, shared by `loops_close`, `gbrain repair loop-facts` and the doctor+ * check `loop_facts_drift`: a commitment fact is retired only when it belongs+ * to the loop's source (E26) and no other open loop references it (E8);+ * otherwise the loop closes and the fact stays active with the reason+ * `shared_with_open_loop`. Both conditions are re-checked under row locks in+ * the publication transaction.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { formatFenceDate, type ParsedFact } from '../facts-fence.ts';+import { strikeFenceRow } from '../facts/forget.ts';+import type { PreparedMutation } from './coordinator.ts';+import type { WriteRequest } from './model.ts';++/** The coordinator operation: the MCP op the caller was granted, so remote grants authorize it unchanged. */+export const LOOP_FACT_RETIREMENT_OPERATION = 'loops_close';+export const LOOP_FACT_RETIREMENT_KIND = 'retire_loop_fact';++export interface LoopFactRetirement {+ fact_expired: boolean;+ retryable: boolean;+ reason?: string;+ fence_struck?: boolean;+}++interface LoopFactState {+ loop: { id: number; source_id: string; status: string; fact_id: number | null } | null;+ fact: { id: number; source_id: string; expired_at: string | null; row_num: number | null; source_markdown_slug: string | null; fact: string } | null;+ shared: boolean;+}++/** The loop, its fact and whether another open loop references that fact; `lock` takes row locks for the publication. */+export async function loopFactState(db: BrainEngine, loopId: number, lock = false): Promise<LoopFactState> {+ const suffix = lock ? ' FOR UPDATE' : '';+ const [loop] = await db.executeRaw<{ id: number; source_id: string; status: string; fact_id: number | null }>(+ `SELECT id, source_id, status, fact_id FROM open_loops WHERE id=$1${suffix}`, [loopId]);+ if (!loop || loop.fact_id === null) return { loop: loop ? { ...loop, id: Number(loop.id), fact_id: null } : null, fact: null, shared: false };+ const [fact] = await db.executeRaw<{ id: number; source_id: string; expired_at: string | null; row_num: number | null; source_markdown_slug: string | null; fact: string }>(+ `SELECT id, source_id, expired_at, row_num, source_markdown_slug, fact FROM facts WHERE id=$1${suffix}`, [loop.fact_id]);+ const others = await db.executeRaw(`SELECT 1 FROM open_loops WHERE fact_id=$1 AND id<>$2 AND status='open' LIMIT 1`, [loop.fact_id, loop.id]);+ return {+ loop: { ...loop, id: Number(loop.id), fact_id: Number(loop.fact_id) },+ fact: fact ? { ...fact, id: Number(fact.id), row_num: fact.row_num === null ? null : Number(fact.row_num),+ expired_at: fact.expired_at === null ? null : new Date(fact.expired_at).toISOString() } : null,+ shared: others.length > 0,+ };+}++/** Why the loop's fact is not retired now, or null when it should be. */+function heldReason(state: LoopFactState): 'loop_not_found' | 'no_fact' | 'fact_missing' | 'source_mismatch' | 'already_expired' | 'shared_with_open_loop' | 'loop_open' | null {+ if (!state.loop) return 'loop_not_found';+ if (state.loop.status !== 'done' && state.loop.status !== 'dropped') return 'loop_open';+ if (state.loop.fact_id === null) return 'no_fact';+ if (!state.fact) return 'fact_missing';+ if (state.fact.source_id !== state.loop.source_id) return 'source_mismatch';+ if (state.fact.expired_at !== null) return 'already_expired';+ if (state.shared) return 'shared_with_open_loop';+ return null;+}++const stateKey = (s: LoopFactState) => JSON.stringify([s.loop?.status, s.loop?.fact_id, s.fact?.source_id, s.fact?.expired_at, s.fact?.row_num, s.fact?.source_markdown_slug, s.shared]);++/** A closed loop's fence row: struck, valid until today, with the close recorded in its context. */+function closedLoopRow(fact: ParsedFact, today: string, status: string): ParsedFact {+ const context = [`loop closed: ${status}`, fact.context?.trim()].filter(Boolean).join(' | ');+ const validUntil = fact.validUntil && /^\d{4}-\d{2}-\d{2}$/.test(fact.validUntil) && fact.validUntil < today ? fact.validUntil : today;+ return { ...fact, active: false, validUntil, context };+}++/** Coordinator preparer for intent `retire_loop_fact`. */+export async function prepareLoopFactRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const intent = row.intent as { kind?: string; loop_id?: number } | null;+ const loopId = Number(intent?.loop_id);+ if (row.operation !== LOOP_FACT_RETIREMENT_OPERATION || intent?.kind !== LOOP_FACT_RETIREMENT_KIND || !Number.isSafeInteger(loopId)) {+ throw new OperationError('invalid_params', 'Unsupported loop fact retirement intent.');+ }+ const state = await loopFactState(engine, loopId);+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ const observedRevision = snapshot?.revision ?? null;+ const held = state.loop && state.loop.source_id !== row.source_id ? 'loop_not_found' : heldReason(state);+ if (held) return { observedRevision, noop: true, apply: async () => ({ fact_expired: held === 'already_expired', retryable: false, reason: held }) };+ const fact = state.fact!;+ const struck = fact.row_num !== null && fact.source_markdown_slug === row.slug && snapshot+ ? strikeFenceRow(snapshot.page.compiled_truth, fact.row_num, f => closedLoopRow(f, formatFenceDate(new Date()), state.loop!.status)) : null;+ const page = struck !== null ? await (await import('./page-prepare.ts')).preparePageMutation(engine, { ...row, intent: {+ content: serializePageToMarkdown({ ...snapshot!.page, compiled_truth: struck }, snapshot!.tags), expected_revision: observedRevision, force: false,+ } }, config) : undefined;+ if (page && page.observedRevision !== observedRevision) throw new OperationError('revision_conflict', 'The fact page changed during preparation.');+ const validate = async (tx: BrainEngine) => {+ if (stateKey(await loopFactState(tx, loopId, true)) !== stateKey(state)) {+ throw new OperationError('revision_conflict', 'The loop or its commitment fact changed during preparation.');+ }+ await page?.validate?.(tx);+ };+ const apply = async (tx: BrainEngine): Promise<Record<string, unknown>> => {+ const expired = await tx.executeRaw(`UPDATE facts SET expired_at=now(), valid_until=LEAST(COALESCE(valid_until, now()), now())+ WHERE id=$1 AND source_id=$2 AND expired_at IS NULL RETURNING id`, [fact.id, fact.source_id]);+ if (expired.length !== 1) throw new OperationError('revision_conflict', 'The commitment fact changed during publication.');+ const published = page ? await page.apply(tx) : {};+ return { ...published, fact_expired: true, retryable: false, fence_struck: page !== undefined, fact_id: fact.id, loop_id: loopId };+ };+ return page ? { ...page, validate, apply } : { observedRevision, validate, apply };+}++/**+ * Admit and wait for one loop's fact retirement. `ctx` is the caller's+ * context (its grant is the publication's authority). A refusal or a write+ * still pending returns `fact_expired: false, retryable: true` with the code.+ */+export async function retireLoopFact(ctx: OperationContext, loopId: number): Promise<LoopFactRetirement> {+ const engine = ctx.engine;+ const state = await loopFactState(engine, loopId);+ const held = heldReason(state);+ if (held) return { fact_expired: held === 'already_expired', retryable: false, reason: held };+ const fact = state.fact!;+ const sourceId = state.loop!.source_id;+ const { initializeLocalPersistence, requestPrincipalForContext } = await import('./page-mutations.ts');+ const { submissionAuthority } = await import('./authority.ts');+ const { admitWrite } = await import('./journal.ts');+ const { assertPersistenceAccepting, waitForWrite, writeResponse } = await import('./service.ts');+ const { resolveFactWriteTarget } = await import('./fact-write-target.ts');+ const config = ctx.config ?? ({ engine: engine.kind } as GBrainConfig);+ try {+ assertPersistenceAccepting(engine);+ const scoped = { ...ctx, sourceId } as OperationContext;+ await initializeLocalPersistence(scoped);+ const principal = await requestPrincipalForContext(scoped);+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(+ "SELECT incarnation, archived, local_path, config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ if (!source || source.archived) return { fact_expired: false, retryable: false, reason: 'source_changed' };+ const slug = fact.source_markdown_slug ?? 'memory/unattributed';+ const target = await resolveFactWriteTarget(engine, sourceId, source);+ if (target.kind === 'unbound') return { fact_expired: false, retryable: true, reason: 'owner_unavailable' };+ const authority = await submissionAuthority(scoped, LOOP_FACT_RETIREMENT_OPERATION, sourceId, source.incarnation, slug);+ if (target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ const intent = { kind: LOOP_FACT_RETIREMENT_KIND, loop_id: loopId };+ const row = await admitWrite(engine, {+ principal, operation: LOOP_FACT_RETIREMENT_OPERATION, sourceId, sourceIncarnation: source.incarnation, slug, pageId: snapshot?.page.id ?? null,+ requestId: randomUUID(), callerIntent: intent, intent, authority,+ worktreeId: target.binding?.worktree_id ?? null, topologyGeneration: target.binding?.topology_generation ?? null,+ });+ const finished = await waitForWrite(engine, row, config, 30_000);+ writeResponse(finished);+ const out = finished.outcome as unknown as LoopFactRetirement;+ return { fact_expired: out.fact_expired === true, retryable: false, ...(out.reason ? { reason: out.reason } : {}),+ ...(out.fence_struck !== undefined ? { fence_struck: out.fence_struck } : {}) };+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ return { fact_expired: false, retryable: true, reason: error.code };+ }+}++/**+ * Closed loops whose commitment fact is still active and retirable under the+ * shared rule (same source, no other open loop references it): what+ * `loop_facts_drift` counts and `repair loop-facts` retires, in id order.+ */+export async function loopFactDrift(db: BrainEngine, sourceIds: string[], loopId?: number): Promise<Array<{ loop_id: number; source_id: string; fact_id: number; status: string; slug: string | null }>> {+ const rows = await db.executeRaw<{ loop_id: number; source_id: string; fact_id: number; status: string; slug: string | null }>(+ `SELECT l.id AS loop_id, l.source_id, l.fact_id, l.status, f.source_markdown_slug AS slug+ FROM open_loops l JOIN facts f ON f.id=l.fact_id AND f.source_id=l.source_id+ WHERE l.source_id=ANY($1::text[]) AND l.status IN ('done','dropped') AND f.expired_at IS NULL+ AND ($2::bigint IS NULL OR l.id=$2::bigint)+ AND NOT EXISTS (SELECT 1 FROM open_loops o WHERE o.fact_id=l.fact_id AND o.status='open')+ ORDER BY l.id`, [sourceIds, loopId ?? null]);+ return rows.map(r => ({ ...r, loop_id: Number(r.loop_id), fact_id: Number(r.fact_id) }));+}++/** A loop already closed whose commitment fact is still active (the retry path of `loops_close`); `sourceId` null is unscoped. */+export async function closedLoopWithActiveFact(db: BrainEngine, sourceId: string | null, loopId: number): Promise<{ id: number; status: string; fact_id: number } | null> {+ const [row] = await db.executeRaw<{ id: number; status: string; fact_id: number }>(+ `SELECT l.id, l.status, l.fact_id FROM open_loops l JOIN facts f ON f.id=l.fact_id+ WHERE l.id=$1 AND ($2::text IS NULL OR l.source_id=$2) AND l.status IN ('done','dropped') AND f.expired_at IS NULL`, [loopId, sourceId]);+ return row ? { id: Number(row.id), status: row.status, fact_id: Number(row.fact_id) } : null;+}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex e147fc3897..8b8ac68c75 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -41,6 +41,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_maintenance_')) return (await import('./prepared-maintenance.ts')).prepareMaintenanceMutation(e, row, cfg);if (row.operation === 'put_page' && row.intent?.kind === 'managed_file_import') return (await import('./import-prepare.ts')).prepareManagedImportMutation(e, row, cfg);if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg, signal);+ if (row.operation === 'loops_close' && row.intent?.kind === 'retire_loop_fact') return (await import('./loop-fact-retirement.ts')).prepareLoopFactRetirement(e, row, cfg);if (row.operation === 'decide_proposal') return (await import('../facts/proposal-supersede.ts')).prepareProposalMutation(e, row, cfg);if (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);if (['takes_add','takes_update','takes_supersede','takes_resolve'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);diff --git a/test/e2e/loops-close-fact-postgres.test.ts b/test/e2e/loops-close-fact-postgres.test.tsnew file mode 100644index 0000000000..bd8f9a68c1--- /dev/null+++ b/test/e2e/loops-close-fact-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../loops-close-fact.serial.test.ts'));diff --git a/test/loops-close-fact.serial.test.ts b/test/loops-close-fact.serial.test.tsnew file mode 100644index 0000000000..17746b5811--- /dev/null+++ b/test/loops-close-fact.serial.test.ts@@ -0,0 +1,175 @@+/**+ * #5869: `loops_close` retires the commitment fact through one coordinated+ * publication (fact expired + fence row struck) on managed and unmanaged+ * brains, reports the real outcome, and stays retryable until it commits.+ *+ * Authoring gate. (1) Protects closing a commitment loop: the promise must+ * leave entity cards and recall, and the page's `## Facts` fence must agree+ * with the database. (2) Fails on the baseline: on a managed brain the raw+ * `UPDATE facts` was refused by `managed_writer_guard`, swallowed, and the op+ * still answered `fact_expired: true`; the fence row was never struck in+ * either mode; a second call could never retry. (3) `ops-loops.test.ts`+ * covers loops_close on a bare facts row in an unmanaged in-memory brain+ * only. (4) Serial: the chat transport is the gateway's process-global seam,+ * and the fixture toggles the brain-wide persistence switch.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { runLoopsExtract } from '../src/core/google/loops-extract.ts';+import { loopsOperations } from '../src/core/ops/loops.ts';+import { upsertOpenLoop } from '../src/core/loops/loops-store.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';+import { createConnectorFixture, googleConfig } from './helpers/connector-fixture.ts';++const fixture = createConnectorFixture();+const { engines, env, source } = fixture;+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };+beforeAll(fixture.setup, 120_000);+afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await fixture.teardown(); });++const loopsClose = loopsOperations.find((o) => o.name === 'loops_close')!;+const ctxFor = (engine: BrainEngine, sourceId: string, over: Partial<OperationContext> = {}) => ({+ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} }, ...over,+}) as unknown as OperationContext;++type CloseResult = { closed: boolean; id?: number; status?: string; fact_expired?: boolean; retryable?: boolean; reason?: string };++/** A connector source with one commitment loop and its fact, made by the real extractor. */+async function seedCommitment(engine: BrainEngine, managed: boolean) {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: JSON.stringify({ commitments: [{ text: 'Send the deck by Friday', direction: 'owed_by_me',+ counterparty_name: 'people/alice-example', counterparty_email: '', due_iso: null, quote: 'I will send the deck by Friday.' }], decisions_pending: [] }),+ blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }));+ const f = await source(engine, googleConfig);+ await engine.setConfig('loops.extraction_enabled', 'true');+ const ctx = ctxFor(engine, f.id);+ if (managed) {+ const put = (slug: string, content: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, content, request_id: randomUUID() } });+ await put('people/alice-example', '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n');+ await put('emails/example', '---\ntitle: Synthetic exchange\ntype: email\nthread_id: example\nfrom: [email protected]\n---\nI will send the deck by Friday.\n');+ } else {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.putPage('people/alice-example', { title: 'Alice Example', type: 'person', compiled_truth: '# Alice Example' }, { sourceId: f.id });+ await engine.putPage('emails/example', { title: 'Synthetic exchange', type: 'email', compiled_truth: 'I will send the deck by Friday.',+ frontmatter: { thread_id: 'example', from: '[email protected]' } }, { sourceId: f.id });+ }+ const extracted = await runLoopsExtract(engine, { slug: 'emails/example', sourceId: f.id });+ expect(extracted).toMatchObject({ status: 'extracted', commitments: 1 });+ const [loop] = await engine.executeRaw<{ id: number; fact_id: number }>('SELECT id, fact_id FROM open_loops WHERE source_id=$1 AND fact_id IS NOT NULL', [f.id]);+ expect(loop?.fact_id).not.toBeNull();+ return { sourceId: f.id, ctx, loopId: Number(loop.id), factId: Number(loop.fact_id) };+}++async function factState(engine: BrainEngine, sourceId: string, factId: number) {+ const [fact] = await engine.executeRaw<{ expired_at: unknown; row_num: number | null; source_markdown_slug: string | null }>(+ 'SELECT expired_at, row_num, source_markdown_slug FROM facts WHERE id=$1', [factId]);+ const page = fact.source_markdown_slug ? await engine.getPage(fact.source_markdown_slug, { sourceId }) : null;+ const row = page ? parseFactsFence(page.compiled_truth).facts.find((r) => r.rowNum === fact.row_num) : undefined;+ return { expired: fact.expired_at !== null, fenced: row !== undefined, rowActive: row?.active ?? null };+}++async function restore(engine: BrainEngine) {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+}++/** A real database refusal inside the publication (no mock): any expiry of a facts row raises. */+const BLOCK_EXPIRY = [`CREATE OR REPLACE FUNCTION test_block_fact_expiry() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN IF OLD.expired_at IS NULL AND NEW.expired_at IS NOT NULL THEN RAISE EXCEPTION 'test refusal: fact expiry blocked'; END IF; RETURN NEW; END $fn$`,+'DROP TRIGGER IF EXISTS test_block_fact_expiry ON facts',+'CREATE TRIGGER test_block_fact_expiry BEFORE UPDATE ON facts FOR EACH ROW EXECUTE FUNCTION test_block_fact_expiry()'];++describe('#5869 loops_close retires the commitment fact through the coordinator', () => {+ for (const managed of [true, false]) {+ const mode = managed ? 'managed' : 'unmanaged';+ test(`${mode}: the fact is expired, its fence row struck, and fact_expired is the real outcome`, async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, ctx, loopId, factId } = await seedCommitment(engine, managed);+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: false, fenced: true, rowActive: true });+ const res = await loopsClose.handler(ctx, { id: loopId, status: 'done' }) as CloseResult;+ expect(res).toMatchObject({ closed: true, status: 'done', fact_expired: true, retryable: false });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: true, fenced: true, rowActive: false });+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [sourceId])).toHaveLength(0);+ await restore(engine);+ }+ }), 180_000);++ test(`${mode}: a refused retirement answers retryable and the next call expires the fact`, async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, ctx, loopId, factId } = await seedCommitment(engine, managed);+ for (const sql of BLOCK_EXPIRY) await engine.executeRaw(sql);+ let res: CloseResult;+ try {+ res = await loopsClose.handler(ctx, { id: loopId, status: 'done' }) as CloseResult;+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS test_block_fact_expiry ON facts');+ }+ expect(res).toMatchObject({ closed: true, fact_expired: false, retryable: true });+ expect(typeof res.reason).toBe('string');+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: false, rowActive: true });+ const retry = await loopsClose.handler(ctx, { id: loopId, status: 'done' }) as CloseResult;+ expect(retry).toMatchObject({ closed: true, fact_expired: true, retryable: false });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: true, rowActive: false });+ const third = await loopsClose.handler(ctx, { id: loopId, status: 'done' }) as CloseResult;+ expect(third).toEqual({ closed: false, reason: 'not_found_or_already_closed' });+ await restore(engine);+ }+ }), 180_000);+ }++ test('E8: a fact shared by two open loops stays active until the last one closes', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, ctx, loopId, factId } = await seedCommitment(engine, true);+ const { id: twin } = await upsertOpenLoop(engine, { sourceId, dedupKey: 'commit:twin', loopType: 'commitment_owed_by_me',+ summary: 'Send the deck by Friday', evidence: [], threadId: 'example-2', pageSlug: 'emails/example', detector: 'llm_extract', factId });+ const first = await loopsClose.handler(ctx, { id: loopId, status: 'done' }) as CloseResult;+ expect(first).toMatchObject({ closed: true, fact_expired: false, retryable: false, reason: 'shared_with_open_loop' });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: false, rowActive: true });+ const second = await loopsClose.handler(ctx, { id: twin, status: 'dropped' }) as CloseResult;+ expect(second).toMatchObject({ closed: true, fact_expired: true, retryable: false });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: true, rowActive: false });+ await restore(engine);+ }+ }), 180_000);++ test('E26: a remote read-only federated grant is refused; the write-bound OAuth caller retires the fact', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, loopId, factId } = await seedCommitment(engine, true);+ const clientId = `loops-close-${sourceId}`;+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,scope,source_id,allowed_operations)+ VALUES($1,'loops_close fixture','read write',$2,$3)`, [clientId, sourceId, ['loops_close']]);+ const remoteCtx = (writeSource: string) => ctxFor(engine, writeSource, { remote: true, auth: { token: 'synthetic-token', clientId,+ principal: { kind: 'oauth_client', id: clientId }, sourceId: writeSource, scopes: ['read', 'write'], allowedOperations: ['loops_close'],+ allowedSources: [writeSource, sourceId] } as never });+ await expect(loopsClose.handler(remoteCtx('default'), { id: loopId, status: 'done', source_id: sourceId })).rejects.toThrow(/permission_denied|outside the caller's write scope/);+ const foreign = await loopsClose.handler(remoteCtx('default'), { id: loopId, status: 'done' }) as CloseResult;+ expect(foreign).toEqual({ closed: false, reason: 'not_found_or_already_closed' });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: false, rowActive: true });+ const res = await loopsClose.handler(remoteCtx(sourceId), { id: loopId, status: 'done' }) as CloseResult;+ expect(res).toMatchObject({ closed: true, fact_expired: true, retryable: false });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: true, rowActive: false });+ await restore(engine);+ }+ }), 180_000);++ test('E26: a loop whose fact lives in another source never retires that fact', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, ctx, factId } = await seedCommitment(engine, true);+ const other = await source(engine, googleConfig);+ const { id } = await upsertOpenLoop(engine, { sourceId: other.id, dedupKey: 'commit:foreign', loopType: 'commitment_owed_by_me',+ summary: 'Send the deck by Friday', evidence: [], threadId: 'foreign', pageSlug: null, detector: 'llm_extract', factId });+ const res = await loopsClose.handler({ ...ctx, sourceId: other.id } as OperationContext, { id, status: 'done', source_id: other.id }) as CloseResult;+ expect(res).toMatchObject({ closed: true, fact_expired: false, retryable: false, reason: 'source_mismatch' });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: false, rowActive: true });+ await restore(engine);+ }+ }), 180_000);+});