Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(receipts): contract harness enforcement, coverage table, managed receipt cases
time-attack25398866dba3
diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.tsindex 86360c3e21..9026a67dd7 100644--- a/src/core/persistence/derived-facts.ts+++ b/src/core/persistence/derived-facts.ts@@ -1,100 +1,21 @@-import type { BrainEngine, NewFact } from '../engine.ts';-import type { Action } from '../agent-output.ts';+import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';-import { readFix, trustedCliRequired } from '../ops/op-fix.ts';-import { currentSubmissionAuthority } from '../minions/submission-authority.ts';-import { withCoordinatedWrite } from './context.ts';-import { maintenanceAttribution, maintenanceTransaction } from './attribution.ts';-import { currentVerifiedLocalWriter } from './identity.ts';+import { maintenanceTransaction } from './attribution.ts';import { managedPersistenceEnabled } from './ownership.ts';-import { assertPersistenceAccepting } from './service.ts';--const sourcesFix = (sourceId: string): Action => readFix(`Lists sources with their archived state, including ${sourceId}.`, { argv: ['gbrain', 'sources', 'list', '--json'] });--/**- * Database-only fact rows derived from page text (the fence reconcile, the- * conversation fact index) never touch a canonical file, so a managed brain- * publishes them like derived links: inside the coordinator's source- * capability, serialized on the page key. Returns false on an unmanaged brain.- * Runs before any provider spend.- */-export async function managedDerivedFactsPreflight(engine: BrainEngine, sourceId: string): Promise<boolean> {- if (!await managedPersistenceEnabled(engine)) return false;- assertPersistenceAccepting(engine);- const job = currentSubmissionAuthority();- if (job && job.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {- throw trustedCliRequired('Managed fact maintenance requires a local writer; remote maintenance jobs are not supported.');- }- const [source] = await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);- if (!source || source.archived) {- throw opError('source_changed', 'The fact maintenance source is not active.',- `Source ${sourceId} is archived or missing, so its facts were not maintained and no model was called. Restore the source first if it should be maintained.`,- { fix: sourcesFix(sourceId) });- }- return true;-}--/**- * One committed transaction holding the source capability and the page keys,- * after revalidating (under a shared source lock, before the page locks) that- * the source is still active: model work may have outlived an archive.- */-export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: string, slugs: readonly string[],- fn: (tx: BrainEngine) => Promise<T>): Promise<T> {- const attribution = await maintenanceAttribution(engine);- return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {- const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);- if (!source || source.archived) {- throw opError('source_changed', 'The fact maintenance source changed during extraction; nothing was written.',- `Source ${sourceId} was archived or removed while its facts were extracted, so nothing was written. Restore the source before maintaining its facts again.`,- { fix: sourcesFix(sourceId) });- }- await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));- return fn(tx);- }, attribution));-}/**- * Legacy writers run in one maintenance transaction on unmanaged brains. On a- * managed brain the page must still be live under its lock, so rows are never- * published for a page deleted or purged while the model ran.+ * Unmanaged brains: database-only fact rows derived from page text (the+ * conversation fact index) commit in one maintenance transaction under the+ * maintenance principal. A managed brain publishes them as receipted+ * maintenance requests instead (facts/conversation-publication.ts,+ * cycle/extract-facts.ts), so this refuses there rather than write a guarded+ * table without a receipt.*/export async function writeDerivedFacts<T>(engine: BrainEngine, sourceId: string, slug: string,fn: (db: BrainEngine) => Promise<T>): Promise<T> {- if (!await managedPersistenceEnabled(engine)) return maintenanceTransaction(engine, fn);- return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {- const [page] = await tx.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);- if (!page) {- throw opError('page_not_found', 'The page was deleted during fact extraction; nothing was written.',- `Page ${slug} in source ${sourceId} was deleted while its facts were extracted, so nothing was written. No action is needed unless the page should still exist.`);- }- return fn(tx);- });-}--/**- * Managed replacement of one page's derived fact batch. Nothing is written- * while the model runs; afterwards, under the source capability and page key,- * `isCurrent` rechecks the page the batch was extracted from, then the rows- * whose `source` starts with `sourcePrefix` are deleted and `build(tx)`'s rows- * inserted in the same transaction. A failed extraction or a changed page- * leaves the prior batch in place.- */-export async function replaceDerivedFactsForPage(engine: BrainEngine, sourceId: string, slug: string, input: {- sourcePrefix: string;- isCurrent: (tx: BrainEngine) => Promise<boolean>;- build: (tx: BrainEngine) => Promise<Array<NewFact & { row_num: number; source_markdown_slug: string }>>;-}): Promise<{ deleted: number; inserted: number }> {- return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {- if (!await input.isCurrent(tx)) {- throw opError('revision_conflict', 'The page changed during fact extraction; its prior facts were kept.',- `Page ${slug} in source ${sourceId} changed while its facts were extracted, so its prior facts were kept. The next fact maintenance pass extracts from the current page.`);- }- const [deleted] = await tx.executeRaw<{ count: string }>(- `WITH del AS (DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE $3 RETURNING 1)- SELECT COUNT(*)::text AS count FROM del`, [sourceId, slug, `${input.sourcePrefix}%`]);- const rows = await input.build(tx);- const { inserted } = rows.length ? await tx.insertFacts(rows, { source_id: sourceId }) : { inserted: 0 }; // gbrain-allow-direct-insert: managed replacement of a page's derived fact batch inside the coordinator transaction that deleted the prior batch- return { deleted: Number(deleted?.count ?? 0), inserted };- });+ if (await managedPersistenceEnabled(engine)) {+ throw opError('writer_coordinator_required', 'Managed brains publish derived facts through receipted maintenance requests.',+ `The derived facts of ${slug} in source ${sourceId} were not written: a managed brain publishes them through the coordinator, which this caller bypassed. Run the extraction command again; report this if it repeats.`);+ }+ return maintenanceTransaction(engine, fn);}diff --git a/test/helpers/managed-connector-job-contract.ts b/test/helpers/managed-connector-job-contract.tsindex aa8a28a39e..ccd769b04e 100644--- a/test/helpers/managed-connector-job-contract.ts+++ b/test/helpers/managed-connector-job-contract.ts@@ -55,6 +55,12 @@ import { runExtract } from '../../src/commands/extract.ts';import { runEmbed } from '../../src/commands/embed.ts';import { countExtractAtomsBacklog } from '../../src/core/cycle/extract-atoms.ts';import { operationsByName } from '../../src/core/operations.ts';+import { runExtractFacts, FENCE_FACTS_INTENT, DELETED_PAGE_FACTS_INTENT } from '../../src/core/cycle/extract-facts.ts';+import { extractTakes, TAKES_REEXTRACT_INTENT } from '../../src/core/cycle/extract-takes.ts';+import { takeSupersessionRepair, TAKE_REPROJECT_INTENT } from '../../src/core/repair/take-supersession.ts';+import { CONVERSATION_FACTS_INTENT } from '../../src/core/facts/conversation-publication.ts';+import { renderFactsTable } from '../../src/core/facts-fence.ts';+import { renderTakesFence } from '../../src/core/takes-fence.ts';import { json, googleConfig, withGoogleAccount } from './connector-fixture.ts';import { withEnv } from './with-env.ts';@@ -70,6 +76,13 @@ export const contractCases = ['cycle_extract_facts','extract_conversation_facts','extract_conversation_facts_thread',+ 'extract_conversation_facts_transcript',+ 'extract_conversation_facts_prose',+ 'extract_conversation_facts_race',+ 'cycle_extract_facts_fenced',+ 'cycle_extract_facts_deleted_page',+ 'takes_rebuild_db',+ 'take_supersession_reproject','facts_absorb','atom_drain_opted_out','atom_drain_default_on',@@ -284,6 +297,15 @@ BEGINIF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NULL; END IF;END IF;+ -- Decision 10 (wave 9 follow-ups): on a managed brain a facts or takes+ -- change must commit inside the publication of an admitted request. The+ -- harness refuses one that runs without gbrain.write_request (counted with+ -- the guard's refusals); production enforcement is a TODO.+ IF TG_TABLE_NAME IN ('facts','takes') AND COALESCE(current_setting('gbrain.write_request',true),'')=''+ AND EXISTS (SELECT 1 FROM persistence_brain WHERE singleton=1 AND enabled) THEN+ PERFORM nextval(('gbrain_contract_refusal_' || TG_TABLE_NAME)::regclass);+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='receipt_required: a managed '||TG_TABLE_NAME||' change ran without a persistence request';+ END IF;IF TG_TABLE_NAME='sources' THEN src := row_data->>'id';ELSIF row_data ? 'source_id' THEN src := row_data->>'source_id';ELSE SELECT source_id INTO src FROM pages WHERE id=(row_data->>'page_id')::integer; END IF;@@ -503,6 +525,47 @@ async function activeFacts(state: CaseState) {'SELECT id,fact,expired_at::text FROM facts WHERE source_id=$1 ORDER BY id', [state.sourceId]);}+async function outcomeRows(state: CaseState) {+ return state.brain.engine.executeRaw<{ fact: string }>(+ "SELECT fact FROM facts WHERE source_id=$1 AND source LIKE 'cli:extract-conversation-facts:%' AND expired_at IS NULL ORDER BY id", [state.sourceId]);+}++async function requestCount(state: CaseState): Promise<number> {+ return (await state.brain.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1', [state.sourceId]))[0]!.n;+}++/** A page in the case's connector source, published through the coordinator like any managed write. */+async function putConversationPage(state: CaseState, slug: string, content: string): Promise<void> {+ const current = await state.brain.engine.readPageSnapshot(slug, { sourceId: state.sourceId });+ await submitPageMutation(state.ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content,+ ...(current ? { expected_revision: current.revision } : {}) } });+ await disposePersistenceConsumer(state.brain.engine);+}++const TRANSCRIPT_SLUG = 'meetings/2026-09-28-plan-sync';+const TRANSCRIPT = [+ '---', 'title: Plan sync', 'type: meeting', 'date: 2026-09-28', '---',+ '**Alice Example:** Can you send me the quarterly plan before the review?',+ '**Owner Example:** Yes, I will send it on Thursday with the finance appendix.',+ '**Alice Example:** Good. I review plans on Mondays, so that works.',+ '**Owner Example:** I will flag any launch date changes in the summary.', '',+].join('\n');+const PROSE_MEETING = [+ '---', 'title: Planning notes', 'type: meeting', 'date: 2026-09-28', '---',+ '**Date:** 2026-09-28', '**Attendees:** Alice Example, Owner Example', '',+ '## Notes', 'We went through hiring, the support backlog and the two launch dates.', '',+ '## Action items', '- Owner Example sends the quarterly plan with the finance appendix.', '',+].join('\n');+const FENCED_SLUG = 'projects/plan-review';+const FENCED_PAGE = `---\ntitle: Plan review\ntype: project\n---\n# Plan review\n\n## Facts\n\n${renderFactsTable([+ { rowNum: 1, claim: 'Quarterly plans are reviewed on Mondays', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true },+] as never)}\n`;+const TAKES_SLUG = 'projects/launch-bets';+const TAKES_PAGE = `---\ntitle: Launch bets\ntype: project\n---\n# Launch bets\n\n## Takes\n\n${renderTakesFence([+ { rowNum: 1, claim: 'The launch ships in Q3', kind: 'bet', holder: 'world', weight: 0.6, sinceDate: '2026-02', source: 'call notes; superseded by #2', active: false },+ { rowNum: 2, claim: 'The launch ships in Q4', kind: 'bet', holder: 'world', weight: 0.7, sinceDate: '2026-03', source: 'call notes', active: true },+] as never)}\n`;+async function staleCount(state: CaseState): Promise<number> {return state.brain.engine.countStalePagesForExtraction({ sourceId: state.sourceId });}@@ -608,17 +671,23 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {expect(phase!.status).not.toBe('fail');},+ /** A single Gmail message is an email, not a conversation: its durable outcome publishes with a receipt and the rerun skips it. */async extract_conversation_facts(state) {await gmailSweep(state);const [job] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]);requireCompleted([job]);+ expect(job.result).toMatchObject({ pages_marked_non_extractable: 1, facts_inserted: 0 });+ const facts = (await changesSince(state)).filter(c => c.tbl === 'facts');+ expect(facts.length).toBe(1);+ expect(facts.every(c => c.request_kind === CONVERSATION_FACTS_INTENT)).toBe(true);+ expect((await outcomeRows(state)).map(r => r.fact)).toEqual(['EXTRACTION_NOT_APPLICABLE']);+ const [again] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]);+ requireCompleted([again]);+ expect(again.result).toMatchObject({ pages_skipped_non_extractable: 1, pages_marked_non_extractable: 0 });+ expect((await changesSince(state)).filter(c => c.tbl === 'facts').length).toBe(1);},- /**- * #5025: a multi-message Gmail thread parses into turns. Replacing a page's- * conversation facts has no persistence request, so on a managed brain the- * page is skipped without writing and stays retryable.- */+ /** #5025 / wave 9 follow-ups item 1: a multi-message Gmail thread extracts on a managed brain, every row receipted. */async extract_conversation_facts_thread(state) {await gmailSweep(state, { reply: true });// The sweep queued loops_extract (priority 5). Left waiting, this case's worker can@@ -626,7 +695,68 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {await state.brain.engine.executeRaw("UPDATE minion_jobs SET status='cancelled' WHERE id > $1 AND status IN ('waiting','delayed')", [state.detector.jobsFrom]);const [job] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]);requireCompleted([job]);- expect((await changesSince(state)).filter(c => c.tbl === 'facts')).toEqual([]);+ expect(job.result).toMatchObject({ pages_processed: 1, facts_inserted: 1 });+ const facts = (await changesSince(state)).filter(c => c.tbl === 'facts');+ expect(facts.length).toBeGreaterThan(0);+ expect(facts.every(c => c.request_kind === CONVERSATION_FACTS_INTENT)).toBe(true);+ expect((await outcomeRows(state)).map(r => r.fact)).toEqual(['EXTRACTION_COMPLETE']);+ },++ /** A dated two-speaker meeting transcript: its facts and EXTRACTION_COMPLETE commit with one receipt. */+ async extract_conversation_facts_transcript(state) {+ await putConversationPage(state, TRANSCRIPT_SLUG, TRANSCRIPT);+ const [job] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]);+ requireCompleted([job]);+ expect(job.result).toMatchObject({ pages_processed: 1, facts_inserted: 1, pages_failed: 0 });+ const facts = (await changesSince(state)).filter(c => c.tbl === 'facts');+ expect(facts.length).toBe(2);+ expect(facts.every(c => c.request_kind === CONVERSATION_FACTS_INTENT)).toBe(true);+ const [{ n }] = await state.brain.engine.executeRaw<{ n: number }>(+ "SELECT count(DISTINCT c.txid)::int AS n FROM gbrain_contract_changes c WHERE c.id > $1 AND c.tbl='facts' AND c.source_id=$2", [state.detector.auditFrom, state.sourceId]);+ expect(n).toBe(1);+ },++ /** A prose meeting page: a receipted EXTRACTION_NOT_APPLICABLE, counted as skipped (no model call) on the next run. */+ async extract_conversation_facts_prose(state) {+ await putConversationPage(state, 'meetings/2026-09-28-planning-notes', PROSE_MEETING);+ let calls = 0;+ __setChatTransportForTests(async opts => { calls++; return fakeChat(opts); });+ const [job] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]);+ requireCompleted([job]);+ expect(job.result).toMatchObject({ pages_marked_non_extractable: 1 });+ expect(calls).toBe(0);+ const facts = (await changesSince(state)).filter(c => c.tbl === 'facts');+ expect(facts.length).toBe(1);+ expect(facts[0]!.request_kind).toBe(CONVERSATION_FACTS_INTENT);+ const [again] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]);+ requireCompleted([again]);+ expect(again.result).toMatchObject({ pages_skipped_non_extractable: 1 });+ expect(calls).toBe(0);+ },++ /** An edit while the model runs: nothing publishes, the prior batch stays, and the next run extracts the edit. */+ async extract_conversation_facts_race(state) {+ await putConversationPage(state, TRANSCRIPT_SLUG, TRANSCRIPT);+ requireCompleted(await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]));+ const prior = await activeFacts(state);+ expect(prior.length).toBe(2);+ let edited = false;+ __setChatTransportForTests(async opts => {+ if (!edited) {+ edited = true;+ await putConversationPage(state, TRANSCRIPT_SLUG, TRANSCRIPT.replace('Thursday', 'Friday'));+ }+ return fakeChat(opts);+ });+ const [job] = await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId, force: true } }]);+ expect(edited).toBe(true);+ expect((job.result as { pages_failed?: number } | null)?.pages_failed ?? 1).toBeGreaterThan(0);+ expect(await activeFacts(state)).toEqual(prior);+ __setChatTransportForTests(async opts => fakeChat(opts));+ requireCompleted(await runJobs(state.brain.engine, [{ name: 'extract-conversation-facts', data: { sourceId: state.sourceId } }]));+ const after = await activeFacts(state);+ expect(after.length).toBe(2);+ expect(after.map(f => f.id)).not.toEqual(prior.map(f => f.id));},async facts_absorb(state) {@@ -814,6 +944,95 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {expect(rows.length).toBe(1);},+ /** extract_facts fence reconcile on a fenced page: the reinserted rows commit with a managed_maintenance_fence_facts receipt. */+ async cycle_extract_facts_fenced(state) {+ const { engine } = state.brain;+ await putConversationPage(state, FENCED_SLUG, FENCED_PAGE);+ const count = async () => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND expired_at IS NULL',+ [state.sourceId, FENCED_SLUG]))[0]!.n;+ expect(await count()).toBe(1);+ // Model a page whose fence was never projected (the work the reconcile exists for), outside the protocol as the fixture does.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [state.sourceId, FENCED_SLUG]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ state.detector = { ...await startDetector(engine), output: state.detector.output };+ const result = await runExtractFacts(engine, { sourceId: state.sourceId, slugs: [FENCED_SLUG] });+ expect(result).toMatchObject({ factsInserted: 1, pagesFailed: 0 });+ expect(await count()).toBe(1);+ const changes = (await changesSince(state)).filter(c => c.tbl === 'facts');+ expect(changes.length).toBe(1);+ expect(changes[0]!.request_kind).toBe(FENCE_FACTS_INTENT);+ // In sync now: the next run admits nothing.+ const requests = await requestCount(state);+ expect((await runExtractFacts(engine, { sourceId: state.sourceId, slugs: [FENCED_SLUG] })).factsInserted).toBe(0);+ expect(await requestCount(state)).toBe(requests);+ },++ /** A soft-deleted page whose fence rows are still active: expired under a receipt, never restored; a no-op admits nothing. */+ async cycle_extract_facts_deleted_page(state) {+ const { engine } = state.brain;+ await putConversationPage(state, FENCED_SLUG, FENCED_PAGE);+ const live = (await engine.readPageSnapshot(FENCED_SLUG, { sourceId: state.sourceId }))!;+ await submitPageMutation(state.ctx, { operation: 'delete_page', params: { slug: FENCED_SLUG, expected_revision: live.revision, request_id: randomUUID() } });+ // Model rows left active by a deletion that predates the expiry pass, outside the protocol.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE facts SET expired_at=NULL WHERE source_id=$1 AND source_markdown_slug=$2 AND row_num IS NOT NULL', [state.sourceId, FENCED_SLUG]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ state.detector = { ...await startDetector(engine), output: state.detector.output };+ const result = await runExtractFacts(engine, { sourceId: state.sourceId, slugs: [] });+ expect(result.factsExpiredForDeletedPages).toBe(1);+ const changes = (await changesSince(state)).filter(c => c.tbl === 'facts');+ expect(changes.length).toBe(1);+ expect(changes[0]!.request_kind).toBe(DELETED_PAGE_FACTS_INTENT);+ const page = await engine.readPageSnapshot(FENCED_SLUG, { sourceId: state.sourceId, includeDeleted: true });+ expect(page?.page.deleted_at).toBeTruthy();+ const requests = await requestCount(state);+ expect((await runExtractFacts(engine, { sourceId: state.sourceId, slugs: [] })).factsExpiredForDeletedPages).toBe(0);+ expect(await requestCount(state)).toBe(requests);+ },++ /** `extract takes --source db --rebuild` (takes rebuild): a page whose takes left the index republishes them with a receipt; in sync admits nothing. */+ async takes_rebuild_db(state) {+ const { engine } = state.brain;+ await putConversationPage(state, TAKES_SLUG, TAKES_PAGE);+ const takes = async () => engine.executeRaw<{ row_num: number }>('SELECT t.row_num FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2 ORDER BY t.row_num', [state.sourceId, TAKES_SLUG]);+ expect((await takes()).length).toBe(2);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('DELETE FROM takes WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2) AND row_num=2', [state.sourceId, TAKES_SLUG]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ state.detector = { ...await startDetector(engine), output: state.detector.output };+ const result = await extractTakes(engine, { source: 'db', rebuild: true, sourceId: state.sourceId });+ expect(result.takesUpserted).toBe(2);+ expect((await takes()).map(t => t.row_num)).toEqual([1, 2]);+ const changes = (await changesSince(state)).filter(c => c.tbl === 'takes');+ expect(changes.length).toBeGreaterThan(0);+ expect(changes.every(c => c.request_kind === TAKES_REEXTRACT_INTENT)).toBe(true);+ const requests = await requestCount(state);+ expect((await extractTakes(engine, { source: 'db', rebuild: true, sourceId: state.sourceId })).takesUpserted).toBe(0);+ expect(await requestCount(state)).toBe(requests);+ },++ /** `gbrain repair take-supersession` database branch: the stored pointer is reprojected under a receipt. */+ async take_supersession_reproject(state) {+ const { engine } = state.brain;+ await putConversationPage(state, TAKES_SLUG, TAKES_PAGE);+ const pointer = async () => (await engine.executeRaw<{ superseded_by: number | null }>(+ 'SELECT t.superseded_by FROM takes t JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug=$2 AND t.row_num=1', [state.sourceId, TAKES_SLUG]))[0]!.superseded_by;+ expect(await pointer()).toBe(2);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE takes SET superseded_by=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2) AND row_num=1', [state.sourceId, TAKES_SLUG]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ state.detector = { ...await startDetector(engine), output: state.detector.output };+ const plan = await takeSupersessionRepair.plan(engine, { source_ids: [state.sourceId] } as never, null);+ expect(plan.items.length).toBe(1);+ const outcome = await takeSupersessionRepair.apply(state.ctx, plan.items[0]!);+ expect(outcome).toMatchObject({ applied: true, outcome: 'reprojected' });+ expect(await pointer()).toBe(2);+ const changes = (await changesSince(state)).filter(c => c.tbl === 'takes');+ expect(changes.length).toBe(1);+ expect(changes[0]!.request_kind).toBe(TAKE_REPROJECT_INTENT);+ },+async handler_enumeration(state) {const names: string[] = [];const worker = { register: (name: string) => { names.push(name); } } as unknown as MinionWorker;@@ -830,7 +1049,8 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {};const ATOM_CASES: ReadonlySet<ContractCase> = new Set(['atom_drain_opted_out', 'atom_drain_default_on', 'atom_dispatch']);-const FACTS_CASES: ReadonlySet<ContractCase> = new Set(['cycle_extract_facts', 'extract_conversation_facts', 'extract_conversation_facts_thread', 'facts_absorb']);+const FACTS_CASES: ReadonlySet<ContractCase> = new Set(['cycle_extract_facts', 'extract_conversation_facts', 'extract_conversation_facts_thread',+ 'extract_conversation_facts_transcript', 'extract_conversation_facts_prose', 'extract_conversation_facts_race', 'facts_absorb']);async function runCase(brain: ContractBrain, id: ContractCase): Promise<void> {const { model, dimensions } = brain.embedding;diff --git a/test/receipt-coverage.test.ts b/test/receipt-coverage.test.tsnew file mode 100644index 0000000000..4cbc942e9b--- /dev/null+++ b/test/receipt-coverage.test.ts@@ -0,0 +1,95 @@+/**+ * Receipt coverage (wave 9 follow-ups, Decision 10): every coordinated write+ * site, each with the guarded tables it changes and whether its rows commit+ * with a receipt.+ *+ * Protects: on a managed brain, facts and takes change only inside the+ * coordinator's publication of an admitted request (a receipt in the same+ * transaction). Fails when a new `withCoordinatedWrite` site appears without+ * an entry here, when a listed site disappears or moves, or when an entry+ * writing facts or takes is not receipted (the one listed exception names+ * its TODO). The pages, timeline and alias writers are listed with their+ * TODO: they still commit as coordinated maintenance without a request.+ * Runtime enforcement lives in the managed-connector contract harness+ * (test/helpers/managed-connector-job-contract.ts); production fail-closed+ * enforcement is a TODO.+ */+import { expect, test } from 'bun:test';+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';++type GuardedTable = 'pages' | 'tags' | 'slug_aliases' | 'page_aliases' | 'facts' | 'takes' | 'timeline_entries' | 'sources';+type Coverage =+ /** Runs inside the coordinator's publication of an admitted request (or a topology receipt). */+ | { sites: number; receipted: string }+ /** Commits coordinated maintenance without a request; `todo` names the follow-up. */+ | { sites: number; tables: GuardedTable[]; todo: string }+ /** Changes no knowledge rows of a guarded table (unguarded tables, physical columns, the source freshness stamp). */+ | { sites: number; tables: GuardedTable[]; other: string };++const RECEIPT_COVERAGE: Record<string, Coverage> = {+ 'src/core/persistence/coordinator.ts': { sites: 1, receipted: 'the publication of an admitted request: every maintenance intent (conversation facts, fence reconcile, deleted-page expiry, takes reextract, take reprojection) applies here' },+ 'src/core/persistence/group-publish.ts': { sites: 1, receipted: 'the grouped publication of admitted requests; each member is the attributed actor' },+ 'src/core/persistence/memory-mutations.ts': { sites: 1, receipted: 'forget/withdraw: admitWriteInTransaction admits the request in the same transaction' },+ 'src/core/shared-skills/publication.ts': { sites: 1, receipted: 'shared-skill revision pruning inside an admitted skill publication' },+ 'src/core/persistence/source-lifecycle.ts': { sites: 1, receipted: 'source add/claim/remove under a persistence_topology_changes receipt' },+ 'src/core/persistence/topology-recovery.ts': { sites: 1, receipted: 'topology recovery under its persistence_topology_changes receipt' },+ 'src/core/page-state/materialize.ts': { sites: 1, tables: ['pages'], todo: 'TODO(receipts): derived page materialization should publish as a maintenance intent' },+ 'src/core/timeline-extract.ts': { sites: 1, tables: ['timeline_entries'], todo: 'TODO(receipts): timeline retraction should publish like managed_maintenance_timeline_extract' },+ 'src/commands/reindex-aliases.ts': { sites: 1, tables: ['page_aliases', 'slug_aliases'], todo: 'TODO(receipts): reindex --aliases should publish per page as a maintenance intent' },+ 'src/core/mentions/pass.ts': { sites: 1, tables: ['page_aliases'], todo: 'TODO(receipts): derived alias rows should publish per page as a maintenance intent' },+ 'src/core/bootstrap/verify.ts': { sites: 1, tables: ['facts'], todo: 'TODO(receipts): bootstrap verify deletes its own probe facts without a request; publish the cleanup as a maintenance intent' },+ 'src/core/cycle/concept-publication.ts': { sites: 1, tables: [], other: 'concept provenance links (links is not a guarded table)' },+ 'src/core/persistence/links-maintenance.ts': { sites: 1, tables: [], other: 'derived links and the pages attendance-blocked stamp (a physical column the guard exempts)' },+ 'src/core/persistence/database-write.ts': { sites: 1, tables: [], other: 'manual links and chronicle ontology observations (unguarded tables)' },+ 'src/core/shared-skills/retention.ts': { sites: 1, tables: [], other: 'shared-skill revision retention (unguarded table)' },+ 'src/core/persistence/connector-path.ts': { sites: 1, tables: ['sources'], other: 'clears an unbound connector source local_path (source registration, not knowledge)' },+ 'src/core/persistence/connector-sync.ts': { sites: 1, tables: ['sources'], other: 'the connector lease freshness stamp on its own source row' },+ 'src/core/persistence/sync-run.ts': { sites: 1, tables: ['sources'], other: 'the managed sync freshness heartbeat on its own source row' },+};++/** Facts/takes writers allowed without a receipt this wave, each with its TODO above. */+const RECEIPT_EXCEPTIONS = new Set(['src/core/bootstrap/verify.ts']);++const ROOT = join(import.meta.dir, '..');++function sourceFiles(dir: string): string[] {+ return readdirSync(dir).flatMap(name => {+ const path = join(dir, name);+ return statSync(path).isDirectory() ? sourceFiles(path) : path.endsWith('.ts') ? [path] : [];+ });+}++function callSites(): Map<string, number> {+ const sites = new Map<string, number>();+ for (const path of sourceFiles(join(ROOT, 'src'))) {+ const count = readFileSync(path, 'utf8').split('\n')+ .filter(line => /\b(withCoordinatedWrite|withDerivedFactsWrite)\(/.test(line) && !/export (async )?function /.test(line)).length;+ if (count) sites.set(relative(ROOT, path), count);+ }+ return sites;+}++test('every coordinated write site is listed with its receipt status', () => {+ const sites = callSites();+ const unlisted = [...sites.keys()].filter(file => !(file in RECEIPT_COVERAGE));+ expect(unlisted).toEqual([]);+ const moved = Object.entries(RECEIPT_COVERAGE).filter(([file, entry]) => sites.get(file) !== entry.sites).map(([file]) => file);+ expect(moved).toEqual([]);+});++test('facts and takes change only with a receipt; every other guarded writer names its TODO', () => {+ const unreceipted = Object.entries(RECEIPT_COVERAGE)+ .filter(([file, entry]) => !('receipted' in entry) && entry.tables.some(table => table === 'facts' || table === 'takes') && !RECEIPT_EXCEPTIONS.has(file))+ .map(([file]) => file);+ expect(unreceipted).toEqual([]);+ for (const [file, entry] of Object.entries(RECEIPT_COVERAGE)) {+ if ('todo' in entry) expect({ file, todo: entry.todo.startsWith('TODO(receipts): ') }).toEqual({ file, todo: true });+ if ('other' in entry) expect({ file, guardedKnowledge: entry.tables.filter(t => t !== 'sources') }).toEqual({ file, guardedKnowledge: [] });+ }+ for (const file of RECEIPT_EXCEPTIONS) expect('todo' in RECEIPT_COVERAGE[file]!).toBe(true);+});++test('the managed derived-facts write API is gone: no facts writer bypasses the coordinator', () => {+ expect([...callSites().keys()].filter(file => readFileSync(join(ROOT, file), 'utf8').includes('withDerivedFactsWrite('))).toEqual([]);+});diff --git a/test/write-attribution.test.ts b/test/write-attribution.test.tsindex 4479a832ed..94347229d5 100644--- a/test/write-attribution.test.ts+++ b/test/write-attribution.test.ts@@ -4,8 +4,8 @@** Protects: who wrote each page_versions row, live page revision, fact, take* and timeline row (created_by and last_mutated_by), on a managed brain, for- * journaled requests (OAuth client, legacy token, local CLI) and for- * coordinated maintenance with no request. Fails if the coordinator stops+ * journaled requests (OAuth client, legacy token, local CLI), for receipted+ * maintenance requests and for coordinated maintenance with no request. Fails if the coordinator stops* passing its request to withCoordinatedWrite, if a trigger is missing or* misclassifies a column, or if the managed guard refuses an attribution-only* update. Runs on PGLite, and on Postgres (direct and transaction-mode@@ -26,7 +26,9 @@ import { localHostId, registerLocalWriter, readLocalWriter } from '../src/core/pimport { getWriteRequest } from '../src/core/persistence/journal.ts';import { submitRememberMutation, submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { replaceDerivedFactsForPage } from '../src/core/persistence/derived-facts.ts';+import { maintenancePreflight } from '../src/core/persistence/prepared-maintenance.ts';+import { buildConversationIntent, startConversationGeneration, submitConversationIntent } from '../src/core/facts/conversation-publication.ts';+import { currentConversationVersionToken } from '../src/commands/extract-conversation-facts.ts';import type { Principal } from '../src/core/persistence/model.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';import { renderTakesFence } from '../src/core/takes-fence.ts';@@ -278,17 +280,22 @@ describe('write attribution on a managed brain', () => {}}, 120_000);- test('coordinated derived fact maintenance has no request and names the local writer', async () => {+ test('conversation fact maintenance publishes under its own request and names the local writer', async () => {for (const engine of engines) {const brain = await managedBrain(engine);const slug = 'notes/derived-example';await run(brain.local, 'put_page', { slug, content: page('Derived', 'Conversation notes') });- await replaceDerivedFactsForPage(engine, brain.sourceId, slug, { sourcePrefix: 'cli:extract-conversation-facts', isCurrent: async () => true,- build: async () => [{ fact: 'Derived example claim', kind: 'fact', visibility: 'world', notability: 'medium',- source: 'cli:extract-conversation-facts:test', entity_slug: slug, row_num: 1, source_markdown_slug: slug }] as never });+ const authority = (await maintenancePreflight(engine, brain.sourceId))!;+ const current = (await engine.getPage(slug, { sourceId: brain.sourceId }))!;+ const versionToken = await currentConversationVersionToken(engine, current);+ const start = await startConversationGeneration(engine, authority, brain.local.config, { slug, page: current, versionToken, since: null, segmentLimit: 0 });+ if (start.kind !== 'extract') throw new Error(`unexpected generation state ${start.kind}`);+ const intent = await buildConversationIntent(engine, brain.local.config, start, [{ fact: 'Derived example claim', kind: 'fact', notability: 'medium',+ source: 'cli:extract-conversation-facts', entity_slug: slug, row_num: 0, source_markdown_slug: slug }], { complete: false, newestEnd: null, visibility: 'world' });+ const receipt = await submitConversationIntent(engine, authority, slug, start, intent);const rows = await engine.executeRaw<RowActors>(`SELECT ${ROW_COLUMNS} FROM facts WHERE source_id=$1 AND fact='Derived example claim'`, [brain.sourceId]);expect(rows).toHaveLength(1);- expect(created(rows[0])).toEqual(actor(null, brain.principals.local));+ expect(created(rows[0])).toEqual(actor(await requestRow(brain, brain.local, receipt), brain.principals.local));}}, 120_000);@@ -356,10 +363,15 @@ describe('write attribution on a managed brain', () => {expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1', [sourceId])).toHaveLength(1);expect(await engine.executeRaw('SELECT id FROM takes WHERE page_id=$1', [alice.id])).toHaveLength(1);expect(await engine.executeRaw('SELECT id FROM timeline_entries WHERE page_id=$1', [alice.id])).toHaveLength(1);+ // Facts and takes publish as receipted maintenance requests of the local writer (wave 9+ // follow-ups, item 1); the timeline writer still runs as coordinated maintenance (TODO).const maintenance = actor(null, brain.principals.local);- for (const [table, where, key] of [['facts', 'source_id=$1', sourceId], ['takes', 'page_id=$1', alice.id], ['timeline_entries', 'page_id=$1', alice.id]] as const) {+ const receipted = { request: true, kind: brain.principals.local.kind, id: brain.principals.local.id };+ for (const [table, where, key, expected] of [['facts', 'source_id=$1', sourceId, receipted], ['takes', 'page_id=$1', alice.id, receipted],+ ['timeline_entries', 'page_id=$1', alice.id, maintenance]] as const) {const rows = await engine.executeRaw<RowActors>(`SELECT ${ROW_COLUMNS} FROM ${table} WHERE ${where}`, [key]);- expect({ table, created: rows.map(created) }).toEqual({ table, created: [maintenance] });+ const actors = rows.map(created).map(a => expected === receipted ? { ...a, request: a.request !== null } : a);+ expect({ table, created: actors }).toEqual({ table, created: [expected] });}const remembered = await submitRememberMutation(ctx, { fact: 'Leads the design review', provenance: 'test', entity: 'people/charlie-example', request_id: randomUUID() }, 30_000);