Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sweep): re-admit a refused window's retained facts once its page passes the file check (#6078)
time-attack0ad5911fb0bf
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 218d479d57..6ccc5fdd4d 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -136,6 +136,12 @@ export interface FactsBackstopCtx {sourceSlug?: string;/** #5888: when the source turn happened, for the capture-lane dedup window (default: now). */turnAt?: Date;+ /**+ * #6048: a caller without a request id (its batch replays by input digest)+ * admits the retained facts of entity requests the canonical file check+ * refused again, once those pages pass the check (persistence/facts-maintenance.ts).+ */+ retryClearedFileRefusals?: boolean;}/** Discriminated return shape based on FactsBackstopCtx.mode. */diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex e4c5e092ef..09c769bb08 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -15,6 +15,9 @@ import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';import { authorizePageVisibility } from './page-visibility.ts';import { initializeLocalPersistence } from './page-mutations.ts';+import { prepareFileTarget } from './page-prepare.ts';+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';+import { resolveDefaultVisibility } from '../facts/visibility.ts';import { currentVerifiedLocalWriter, localHostId } from './identity.ts';import { getWorktreeBinding, managedPersistenceEnabled, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';import { authorizeFactsBackstop } from './effect-facts.ts';@@ -52,8 +55,13 @@ export interface ManagedFactsSession {batchKey: string; inputDigest: string; origin: ManagedFactOrigin | null; originalRequestId: string | null;completionRequestId: string;embedding?: FactEmbeddingSignature | null;+ /** #6048: the batch seed is the input digest and the caller retries file refusals whose page passes the file check again. */+ retryFileRefusals?: true;}+/** #6048: new attempts a batch gets for entity requests the canonical file check refused. */+const FILE_REFUSAL_ATTEMPTS = 3;+const receiptFix = (requestId: string): Action => readFix('Reads the fact request\'s durable receipt: its operation, state and outcome, read-only.',{ argv: ['gbrain', 'write-request', '--', requestId], mcp: { tool: 'get_write_request', arguments: { request_id: requestId } } });const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`,@@ -63,15 +71,22 @@ const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${souconst embeddingsFix = (): Action => readFix('Reports the brain\'s embedding model, dimensions and vector columns, read-only.',{ argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'] });+/** The slug of a facts batch's completion request. */+const MANAGED_FACTS_COMPLETE_SLUG = '__managed_facts_complete__';+function managedFactRequestId(batchKey: string, slug: string): string {const hex = digest([batchKey, slug]);return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;}+function completionRequestIdFor(batchKey: string): string {+ return managedFactRequestId(batchKey, MANAGED_FACTS_COMPLETE_SLUG);+}+async function validateManagedFactsCompletion(engine: BrainEngine, session: ManagedFactsSession, prior: WriteRequest): Promise<void> {await authorizeStoredRequest(engine, prior);const inputDigest = prior.intent?.inputDigest ?? prior.outcome?.input_digest;- if (prior.operation !== 'extract_facts' || prior.slug !== '__managed_facts_complete__'+ if (prior.operation !== 'extract_facts' || prior.slug !== MANAGED_FACTS_COMPLETE_SLUG|| prior.source_id !== session.authority.sourceId || prior.source_incarnation !== session.authority.sourceIncarnation|| inputDigest !== undefined && inputDigest !== session.inputDigest) {throw opError('idempotency_conflict', 'This request ID already belongs to another operation or extraction input.',@@ -231,20 +246,26 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,const config = ctx.operationContext?.config ?? ctx.config ?? persistenceConsumerConfig(engine) ?? { engine: engine.kind } as GBrainConfig;const session: ManagedFactsSession = { authority, binding: writeThrough ? binding : null, config,batchKey, inputDigest, origin, originalRequestId: ctx.persistenceRequestId ?? null,- completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : managedFactRequestId(batchKey, '__managed_facts_complete__') };+ completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : completionRequestIdFor(batchKey),+ ...(ctx.retryClearedFileRefusals && seed === inputDigest ? { retryFileRefusals: true as const } : {}) };const prior = await getWriteRequest(engine, authority.principal, session.completionRequestId);if (prior) await validateManagedFactsCompletion(engine, session, prior);return session;}+/** Waits for an accepted request of this extraction to settle, once it is proven to carry this input and this writer's authority. */+async function settleManagedFact(engine: BrainEngine, session: ManagedFactsSession, row: WriteRequest): Promise<WriteRequest> {+ if ((row.intent?.inputDigest ?? row.outcome?.input_digest) !== session.inputDigest) throw opError('idempotency_conflict', 'The fact request ID was already used with different extraction input.',+ `Request ${row.request_id} in source ${row.source_id} was accepted for different extraction input, so this extraction was not merged into it. Give this extraction a new request_id; read the receipt to see the original.`,+ { fix: receiptFix(row.request_id) });+ await authorizeStoredRequest(engine, row);+ return waitForWrite(engine, row, session.config, maintenancePublishWaitMs());+}+async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSession, rows: WriteRequest[]): Promise<ManagedFactsResult> {const result: ManagedFactsResult = { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [], write_requests: [] };for (const row of rows) {- if ((row.intent?.inputDigest ?? row.outcome?.input_digest) !== session.inputDigest) throw opError('idempotency_conflict', 'The fact request ID was already used with different extraction input.',- `Request ${row.request_id} in source ${row.source_id} was accepted for different extraction input, so this extraction was not merged into it. Give this extraction a new request_id; read the receipt to see the original.`,- { fix: receiptFix(row.request_id) });- await authorizeStoredRequest(engine, row);- const finished = await waitForWrite(engine, row, session.config, maintenancePublishWaitMs());+ const finished = await settleManagedFact(engine, session, row);writeResponse(finished);result.write_requests.push(receiptFor(finished));if ((row.intent?.kind ?? row.outcome?.kind) === 'managed_facts_entity') {@@ -259,18 +280,133 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSesreturn result;}-export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFactsSession): Promise<ManagedFactsResult | null> {+/** The requests accepted under a facts batch key, with their validated completion; null when the batch was never accepted. */+async function acceptedManagedBatch(engine: BrainEngine, session: ManagedFactsSession, batchKey: string, completionRequestId: string): Promise<WriteRequest[] | null> {const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE operation='extract_facts'AND source_id=$1 AND source_incarnation=$2::uuid AND principal_kind=$3 AND principal_id=$4AND (request_id=$6::uuid OR COALESCE(intent->>'batchKey',outcome->>'batch_key')=$5) ORDER BY sequence`, [session.authority.sourceId, session.authority.sourceIncarnation,- session.authority.principal.kind, session.authority.principal.id, session.batchKey, session.completionRequestId]);+ session.authority.principal.kind, session.authority.principal.id, batchKey, completionRequestId]);if (!rows.length) return null;- const completion = rows.find(row => row.request_id === session.completionRequestId);+ const completion = rows.find(row => row.request_id === completionRequestId);if (!completion) throw opError('storage_error', 'The accepted facts batch has no completion receipt.',- `Facts batch requests were accepted in source ${session.authority.sourceId} but their completion request ${session.completionRequestId} was never journaled, so the outcome is unconfirmed. Inspect accepted request ${rows[0].request_id} before resubmitting anything.`,+ `Facts batch requests were accepted in source ${session.authority.sourceId} but their completion request ${completionRequestId} was never journaled, so the outcome is unconfirmed. Inspect accepted request ${rows[0].request_id} before resubmitting anything.`,{ fix: receiptFix(rows[0].request_id) });await validateManagedFactsCompletion(engine, session, completion);- return collectManagedFacts(engine, session, rows);+ return rows;+}++export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFactsSession): Promise<ManagedFactsResult | null> {+ const rows = await acceptedManagedBatch(engine, session, session.batchKey, session.completionRequestId);+ if (!rows) return null;+ return collectManagedFacts(engine, session, session.retryFileRefusals ? await retryClearedFileRefusals(engine, session, rows) : rows);+}++/**+ * #6048: a caller whose batch seed is its input digest (the sweep) cannot give+ * a refused extraction a new request id, so its stored terminal batch would+ * replay the refusal on every run. When every entity request the batch did not+ * commit was refused source_changed with its facts retained, and each of those+ * pages passes the canonical file check now, the retained facts are admitted+ * as the batch's next attempt; committed requests are kept, not admitted again.+ * A page that still fails the check admits nothing, and a batch gets at most+ * FILE_REFUSAL_ATTEMPTS new attempts. Returns the requests to collect: the kept+ * ones and the last attempt's.+ */+async function retryClearedFileRefusals(engine: BrainEngine, session: ManagedFactsSession, rows: WriteRequest[]): Promise<WriteRequest[]> {+ const kept: WriteRequest[] = [];+ let batch = rows;+ for (let attempt = 1; attempt <= FILE_REFUSAL_ATTEMPTS; attempt++) {+ // Decided on the stored states: a request still publishing ends the walk,+ // and collectManagedFacts waits for it once, as it does without a retry.+ if (!batch.every(isTerminal)) break;+ const entities = batch.filter(row => (row.intent?.kind ?? row.outcome?.kind) === 'managed_facts_entity');+ const refused = entities.filter(row => row.state !== 'committed');+ if (!refused.length || !refused.every(isRetainedFileRefusal)) break;+ for (const row of refused) await settleManagedFact(engine, session, row);+ const batchKey = digest([session.batchKey, 'file-refusal-attempt', attempt]);+ const completionRequestId = completionRequestIdFor(batchKey);+ const next = await acceptedManagedBatch(engine, session, batchKey, completionRequestId)+ ?? (await canonicalFilesPass(engine, session, refused.map(row => row.slug))+ ? await admitFileRefusalAttempt(engine, session, batchKey, completionRequestId, refused) : null);+ if (!next) break;+ kept.push(...entities.filter(row => row.state === 'committed'));+ batch = next;+ }+ return [...kept, ...batch];+}++function isRetainedFileRefusal(row: WriteRequest): boolean {+ return isTerminal(row) && row.error_code === 'source_changed' && !!(row.intent as ManagedFactIntent | null)?.facts?.length;+}++/** #6048: the file check publication runs before it writes a page, read-only; a refusal means the page still fails it. */+async function canonicalFilesPass(engine: BrainEngine, session: ManagedFactsSession, slugs: string[]): Promise<boolean> {+ const { sourceId, remote } = session.authority;+ // The same pack fallback as preparePageMutation, so the check parses the file as publication does.+ const activePack = (await loadActivePackForEngine(engine, { remote, sourceId }).catch(() => null))?.manifest;+ for (const slug of new Set(slugs)) {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot) return false;+ try {+ await prepareFileTarget(engine, { source_id: sourceId, worktree_id: session.binding?.worktree_id ?? null, slug }, snapshot, null, undefined, { activePack, remote });+ } catch (error) {+ // Still refused: the stored outcome stands, and the next run checks again.+ if (error instanceof OperationError) return false;+ throw error;+ }+ }+ return true;+}++/**+ * #6048: the refused requests' retained facts, admitted as the batch's next+ * attempt against each page's current revision, never wider than the brain's+ * current default visibility.+ */+async function admitFileRefusalAttempt(engine: BrainEngine, session: ManagedFactsSession, batchKey: string, completionRequestId: string,+ refused: WriteRequest[]): Promise<WriteRequest[]> {+ const narrow = await resolveDefaultVisibility(engine) === 'private';+ const inputs: ManagedFactsBatchInput[] = [];+ for (const row of refused) {+ await authorizeWrite(engine, session.authority, 'extract_facts', row.slug);+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: session.authority.sourceId, includeDeleted: true });+ const prior = row.intent as ManagedFactIntent;+ const intent: ManagedFactIntent = { ...prior, batchKey,+ facts: narrow ? prior.facts!.map(fact => ({ ...fact, visibility: 'private' as const })) : prior.facts };+ delete intent.expected_revision;+ if (snapshot) intent.expected_revision = snapshot.revision;+ inputs.push({ slug: row.slug, pageId: snapshot?.page.id ?? null, intent });+ }+ const embedded = inputs.some(input => input.intent.facts!.some(fact => fact.embedding !== null));+ return admitManagedFactsBatch(engine, session, { batchKey, completionRequestId, embedded,+ embedding: (refused[0].intent as ManagedFactIntent).embedding }, inputs);+}++interface ManagedFactsBatchInput { slug: string; pageId: number | null; intent: ManagedFactIntent }++/** Admits a facts batch, its per-entity requests and its completion request, in one transaction. */+async function admitManagedFactsBatch(engine: BrainEngine, session: ManagedFactsSession,+ batch: { batchKey: string; completionRequestId: string; embedded: boolean; embedding: FactEmbeddingSignature | null | undefined },+ inputs: ManagedFactsBatchInput[], abortSignal?: AbortSignal): Promise<WriteRequest[]> {+ return engine.transaction(async tx => {+ if (batch.embedded) await assertManagedFactsEmbedding(tx, session.config, batch.embedding, true);+ const children: string[] = [];+ const accepted: WriteRequest[] = [];+ for (const input of [...inputs, { slug: MANAGED_FACTS_COMPLETE_SLUG, pageId: null, intent: {+ kind: 'managed_facts_complete', batchKey: batch.batchKey, inputDigest: session.inputDigest,+ origin: session.origin, originalRequestId: session.originalRequestId, children } as ManagedFactIntent }]) {+ if (abortSignal?.aborted) throw new DOMException('Fact extraction was aborted before admission.', 'AbortError');+ await authorizePageVisibility(tx, session.authority, input.slug);+ const requestId = input.intent.kind === 'managed_facts_complete' ? batch.completionRequestId : managedFactRequestId(batch.batchKey, input.slug);+ const row = await admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,+ operation: 'extract_facts', sourceId: session.authority.sourceId, sourceIncarnation: session.authority.sourceIncarnation,+ worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,+ requestId, slug: input.slug, pageId: input.pageId, callerIntent: input.intent, intent: input.intent });+ accepted.push(row);+ if (input.intent.kind === 'managed_facts_entity') children.push(row.id);+ }+ return accepted;+ });}export async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,@@ -297,7 +433,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedFvalid_from: (fact.valid_from ?? ctx.validFrom ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });groups.set(slug, group);}- const inputs: Array<{ slug: string; pageId: number | null; intent: ManagedFactIntent }> = [];+ const inputs: ManagedFactsBatchInput[] = [];for (const [slug, group] of groups) {const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug === slug) && !snapshot) throw opError('page_identity_changed', 'The resolved fact entity was removed.',@@ -309,24 +445,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF...(options.attributeFallback ? { attribute_fallback: true as const } : {}),...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });}- const rows = await engine.transaction(async tx => {- if (embedded) await assertManagedFactsEmbedding(tx, session.config, session.embedding, true);- const children: string[] = [];- const accepted: WriteRequest[] = [];- for (const input of [...inputs, { slug: '__managed_facts_complete__', pageId: null, intent: {- kind: 'managed_facts_complete', batchKey: session.batchKey, inputDigest: session.inputDigest,- origin: session.origin, originalRequestId: session.originalRequestId, children } as ManagedFactIntent }]) {- if (ctx.abortSignal?.aborted) throw new DOMException('Fact extraction was aborted before admission.', 'AbortError');- await authorizePageVisibility(tx, session.authority, input.slug);- const requestId = input.intent.kind === 'managed_facts_complete' ? session.completionRequestId : managedFactRequestId(session.batchKey, input.slug);- const row = await admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,- operation: 'extract_facts', sourceId, sourceIncarnation: session.authority.sourceIncarnation,- worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,- requestId, slug: input.slug, pageId: input.pageId, callerIntent: input.intent, intent: input.intent });- accepted.push(row);- if (input.intent.kind === 'managed_facts_entity') children.push(row.id);- }- return accepted;- });+ const rows = await admitManagedFactsBatch(engine, session, { batchKey: session.batchKey, completionRequestId: session.completionRequestId,+ embedded, embedding: session.embedding }, inputs, ctx.abortSignal);return collectManagedFacts(engine, session, rows);}diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 7d4789eb0a..22d4929b67 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -744,6 +744,7 @@ async function runCorpusIngestPass(abortSignal: signal,// #5888: the file's write time anchors the capture dedup window, not the (possibly late) sweep.turnAt: await stat(full).then(st => st.mtime, () => undefined),+ retryClearedFileRefusals: true, // #6048: no request id to give a refused window...(wbMeta && wbCfg.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),// visibility deliberately unset → resolveDefaultVisibility [ENG-8]};diff --git a/test/managed-sweep-file-refusal-retry.test.ts b/test/managed-sweep-file-refusal-retry.test.tsnew file mode 100644index 0000000000..cf4aa4ca0a--- /dev/null+++ b/test/managed-sweep-file-refusal-retry.test.ts@@ -0,0 +1,347 @@+/**+ * #6048 on a managed brain: a corpus window whose facts batch the canonical file+ * check refused is extracted again once that page's file passes the check.+ *+ * 1. Protects: the sweep cannot give a refused window a new request id, so when+ * every uncommitted entity request of the stored batch was refused+ * `source_changed` and each such page's file now passes the check, the+ * retained facts of those requests are admitted as the batch's next attempt+ * (no new LLM call) at the page's current revision, never wider than the+ * current default visibility; committed siblings are kept, and the file+ * finishes. A page that still fails the check, or a batch with another+ * refusal, admits nothing, and new attempts stop at 3.+ * 2. Fails when: the sweep replays the stored terminal conflict forever (the+ * window and every later window of the file never ingest), re-extracts or+ * re-admits committed siblings, pins the refused revision, widens a fact's+ * visibility, mints a new batch while the page still drifts or beside+ * another refusal, keeps retrying a page whose publication keeps refusing,+ * or admits a retry under a writer grant narrowed since the refused attempt.+ * 3. managed-sweep-corpus-windows.test.ts covers windows that commit; no test+ * resumes a terminal facts batch.+ * 4. No new seam: gateway test transports, and the persistence fault hook the+ * crash robot installs, to edit the file after an attempt is prepared.+ *+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';+import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';+import type { CapabilityReport } from '../src/core/capability.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { waitFor } from './helpers/wait-for.ts';++const KEYED: CapabilityReport = {+ embeddings: { available: false },+ extraction: { available: true, provider: 'anthropic' },+ search: 'keyword-only',+ mode: 'keyed',+};+const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-file-refusal-db-'));+let closePostgres: (() => Promise<void>) | undefined;+let inputs: string[] = [];+/** Entities every extracted window names, one fact per entity and workstream tag. */+let entities: Array<{ slug: string; name: string }> = [];++const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };+beforeAll(async () => {+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });+ __setChatTransportForTests(async (request): Promise<ChatResult> => {+ const content = String(request.messages[0].content);+ const text = content.slice(content.indexOf('<turn>\n') + '<turn>\n'.length, content.lastIndexOf('\n</turn>'));+ inputs.push(text);+ const facts = [...new Set(text.match(/\bT\d\d\b/g) ?? [])].flatMap((m) => entities.map((e) => ({+ fact: `${e.name} works on workstream ${m}`, kind: 'fact', entity: e.slug, confidence: 0.9, notability: 'high',+ })));+ return { text: JSON.stringify({ facts }), blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };+ });+ // Orthogonal vectors per distinct text, so cosine dedup never merges different facts.+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map((v) => {+ const vec = Array(1536).fill(0);+ vec[[...v].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 1536, 7)] = 1;+ return vec;+ }) })) as never);+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ installFaultHook(undefined);+ __setChatTransportForTests(null); __setEmbedTransportForTests(null);+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); resetGateway(); rmSync(dataDir, { recursive: true, force: true });+});++const body = (tag: string): string => {+ let s = `${tag} `;+ while (s.length < 5000) s += `${tag.toLowerCase()} detail words\n`;+ return s.slice(0, 5000);+};+const corpus = (count: number): string =>+ toCorpusText(Array.from({ length: count }, (_, i) => ({ role: i % 2 === 0 ? 'user' as const : 'assistant' as const, text: body(`T${String(i).padStart(2, '0')}`) })));++const ACME = { slug: 'companies/acme-example', name: 'Acme Example' };+const ALICE = { slug: 'people/alice-example', name: 'Alice Example' };+const FACTS_COMPLETE = '__managed_facts_complete__';++/** A managed source with committed entity pages, its corpus dir and sweep helpers. */+async function managedSource(engine: BrainEngine, dir: string, pages: Array<{ slug: string; name: string; type: string; body?: string }>) {+ const root = join(dir, 'brain'); mkdirSync(root);+ const corpusDir = join(dir, 'corpus'); mkdirSync(corpusDir);+ const sourceId = `refusal-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await engine.setConfig('facts.extraction_enabled', 'true');+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpusDir);+ await claimWorktree(engine, sourceId, root);+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ for (const page of pages) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug,+ content: `---\ntitle: ${page.name}\ntype: ${page.type}\n---\n${page.body ?? `# ${page.name}\n`}`, request_id: randomUUID() } });+ }+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const logs: string[] = [];+ // The sweep returns at the first refused request; its siblings keep publishing in this process.+ const settled = () => waitFor(async () => Number((await engine.executeRaw<{ n: string }>(+ `SELECT COUNT(*) AS n FROM persistence_requests WHERE source_id=$1+ AND state IN ('queued','running','recovering')`, [sourceId]))[0].n) === 0, { timeoutMs: 30_000, label: 'requests settled' });+ return {+ sourceId, root, corpusDir, logs, ctx: ctx as unknown as OperationContext, settled,+ sweep: async () => {+ const report = await runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000, log: (m) => logs.push(m) });+ await settled();+ return report;+ },+ requests: () => engine.executeRaw<{ slug: string; state: string; error_code: string | null; updated_at: string }>(+ `SELECT slug,state,error_code,updated_at::text AS updated_at FROM persistence_requests+ WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence`, [sourceId]),+ facts: () => engine.executeRaw<{ fact: string; visibility: string }>(+ `SELECT fact,visibility FROM facts WHERE source_id=$1 AND source='sweep:corpus' AND expired_at IS NULL ORDER BY fact`, [sourceId])+ .then((rows) => rows.map((r) => `${r.fact} (${r.visibility})`)),+ revision: (slug: string) => engine.executeRaw<{ revision: string }>(+ 'SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]).then((rows) => rows[0].revision),+ };+}++test('managed: a refused window is extracted again once its page passes the file check, never while it drifts', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-file-refusal-'));+ inputs = [];+ entities = [ACME, ALICE];+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ const s = await managedSource(engine, dir, [{ ...ACME, type: 'company' }, { ...ALICE, type: 'person' }]);+ await engine.setConfig('facts.default_visibility', 'world');+ const acmeFile = join(s.root, 'companies', 'acme-example.md');+ const good = readFileSync(acmeFile);+ appendFileSync(acmeFile, '\nAn uncoordinated local edit.\n');+ const file = join(s.corpusDir, 'refused-session.txt');+ writeFileSync(file, corpus(2));++ // Window 1: the Acme request is refused, the Alice request commits, the file stops there.+ const r1 = await s.sweep();+ expect(r1.corpusIngested).toBe(0);+ expect(inputs.length).toBe(1);+ expect(s.logs.at(-1)).toContain('The canonical file contains an uncoordinated local edit.');+ const refused = await s.requests();+ expect(refused.map((r) => [r.slug, r.state, r.error_code])).toEqual([+ [ACME.slug, 'conflict', 'source_changed'],+ [ALICE.slug, 'committed', null],+ [FACTS_COMPLETE, 'conflict', 'revision_conflict'],+ ]);++ // Still drifting: the stored outcome stands and nothing new is admitted.+ const r2 = await s.sweep();+ expect(r2.corpusIngested).toBe(0);+ expect(inputs.length).toBe(1);+ expect(await s.requests()).toEqual(refused);++ // The file passes the check again, then another writer moves the page's revision and the+ // default visibility is narrowed. The retained Acme facts are admitted once more at the+ // current revision, never wider than private, without a new extraction; window 2 follows.+ writeFileSync(acmeFile, good);+ const refusedRevision = await s.revision(ACME.slug);+ await submitRememberMutation(s.ctx, { fact: 'Acme Example opened an office', entity: ACME.slug, provenance: 'test', visibility: 'private' }, 10_000);+ await s.settled();+ expect(await s.revision(ACME.slug)).not.toBe(refusedRevision);+ await engine.setConfig('facts.default_visibility', 'private');+ const r3 = await s.sweep();+ expect(r3.corpusIngested).toBe(1);+ expect(JSON.parse(readFileSync(file + CORPUS_INGESTED_SUFFIX, 'utf8')).facts_inserted).toBe(4);+ expect(inputs.length).toBe(2);+ expect(await s.facts()).toEqual([+ 'Acme Example works on workstream T00 (private)', 'Acme Example works on workstream T01 (private)',+ 'Alice Example works on workstream T00 (world)', 'Alice Example works on workstream T01 (private)',+ ]);+ const after = await s.requests();+ expect(after.slice(0, refused.length)).toEqual(refused);+ // The retry batch carries only the Acme request; window 2 is a batch of its own.+ expect(after.slice(refused.length).map((r) => [r.slug, r.state])).toEqual([+ [ACME.slug, 'committed'], [FACTS_COMPLETE, 'committed'],+ [ACME.slug, 'committed'], [ALICE.slug, 'committed'], [FACTS_COMPLETE, 'committed'],+ ]);+ // The committed Alice request of window 1 was kept, not admitted again.+ expect(after.filter((r) => r.slug === ALICE.slug).length).toBe(2);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 180_000);++test('managed: a page whose publication keeps refusing gets at most three new attempts', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-file-refusal-cap-'));+ inputs = [];+ entities = [ACME];+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ const s = await managedSource(engine, dir, [{ ...ACME, type: 'company' }]);+ const acmeFile = join(s.root, 'companies', 'acme-example.md');+ const good = readFileSync(acmeFile);+ appendFileSync(acmeFile, '\nAn uncoordinated local edit.\n');+ writeFileSync(join(s.corpusDir, 'flapping-session.txt'), corpus(1));+ expect((await s.sweep()).corpusIngested).toBe(0);+ expect((await s.requests()).length).toBe(2);++ // The file passes the check, then is edited again after each attempt is prepared, before it publishes.+ installFaultHook((point, detail) => {+ if (point === 'consumer:prepared' && detail.operation === 'extract_facts' && detail.sourceId === s.sourceId) {+ appendFileSync(acmeFile, '\nEdited before publication.\n');+ }+ });+ for (let attempt = 1; attempt <= 3; attempt++) {+ writeFileSync(acmeFile, good);+ expect((await s.sweep()).corpusIngested).toBe(0);+ const rows = await s.requests();+ expect(rows.length).toBe(2 + attempt * 2);+ expect(rows.slice(-2).map((r) => [r.slug, r.state, r.error_code])).toEqual([+ [ACME.slug, 'conflict', 'source_changed'], [FACTS_COMPLETE, 'conflict', 'revision_conflict']]);+ }+ installFaultHook(undefined);++ // Past the cap the stored outcome stands, even though the file passes the check now.+ writeFileSync(acmeFile, good);+ const capped = await s.requests();+ expect((await s.sweep()).corpusIngested).toBe(0);+ expect(await s.requests()).toEqual(capped);+ expect(inputs.length).toBe(1);+ });+ } finally {+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 180_000);++test('managed: a batch with any refusal other than the file check is not retried', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-file-refusal-mixed-'));+ inputs = [];+ entities = [ACME, ALICE];+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ const s = await managedSource(engine, dir, [{ ...ACME, type: 'company' }, { ...ALICE, type: 'person' }]);+ const files = [join(s.root, 'companies', 'acme-example.md'), join(s.root, 'people', 'alice-example.md')];+ const good = files.map((f) => readFileSync(f));+ for (const f of files) appendFileSync(f, '\nAn uncoordinated local edit.\n');+ writeFileSync(join(s.corpusDir, 'mixed-session.txt'), corpus(1));+ expect((await s.sweep()).corpusIngested).toBe(0);+ // The stored batch as a mixed one: the Alice request ended with another refusal+ // (the shape a page written between admission and publication leaves).+ await engine.executeRaw(`UPDATE persistence_requests SET error_code='revision_conflict',+ error_message='The fact entity changed after extraction admission.'+ WHERE source_id=$1 AND operation='extract_facts' AND slug=$2`, [s.sourceId, ALICE.slug]);+ const refused = await s.requests();+ expect(refused.map((r) => [r.slug, r.state, r.error_code])).toEqual([+ [ACME.slug, 'conflict', 'source_changed'],+ [ALICE.slug, 'conflict', 'revision_conflict'],+ [FACTS_COMPLETE, 'conflict', 'revision_conflict'],+ ]);++ // Both files pass the check again, but the other refusal keeps the stored outcome.+ files.forEach((f, i) => writeFileSync(f, good[i]));+ expect((await s.sweep()).corpusIngested).toBe(0);+ expect(await s.requests()).toEqual(refused);+ expect(inputs.length).toBe(1);+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 180_000);++test('managed: a retry honors a local writer grant narrowed since the refused attempt', async () => {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-file-refusal-narrowed-'));+ inputs = [];+ entities = [ACME, ALICE];+ let writerId: string | undefined;+ let ceiling: unknown;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {+ const s = await managedSource(engine, dir, [{ ...ACME, type: 'company' }, { ...ALICE, type: 'person' }]);+ const acmeFile = join(s.root, 'companies', 'acme-example.md');+ const good = readFileSync(acmeFile);+ appendFileSync(acmeFile, '\nAn uncoordinated local edit.\n');+ writeFileSync(join(s.corpusDir, 'narrowed-session.txt'), corpus(1));+ expect((await s.sweep()).corpusIngested).toBe(0);+ const refused = await s.requests();+ expect(refused.map((r) => [r.slug, r.state, r.error_code])).toEqual([+ [ACME.slug, 'conflict', 'source_changed'], [ALICE.slug, 'committed', null], [FACTS_COMPLETE, 'conflict', 'revision_conflict']]);+ const factsBefore = await s.facts();++ // The file passes the check again, but the writer that extracted the window may no longer write companies/.+ const [writer] = await engine.executeRaw<{ id: string; grant_ceiling: unknown }>(+ `SELECT w.id::text AS id, w.grant_ceiling FROM persistence_local_writers w+ JOIN persistence_requests r ON r.principal_id = w.id::text+ WHERE r.source_id=$1 AND r.slug=$2 LIMIT 1`, [s.sourceId, ACME.slug]);+ writerId = writer!.id;+ ceiling = writer!.grant_ceiling;+ await engine.executeRaw(`UPDATE persistence_local_writers SET grant_ceiling = jsonb_set(grant_ceiling, '{slugPrefixes}', '["people/"]'::jsonb) WHERE id=$1::uuid`, [writerId]);+ writeFileSync(acmeFile, good);+ expect((await s.sweep()).corpusIngested).toBe(0);+ expect(s.logs.at(-1)).toContain('The target is outside this writer grant.');+ expect(await s.requests()).toEqual(refused);+ expect(await s.facts()).toEqual(factsBefore);+ expect(inputs.length).toBe(1);+ });+ } finally {+ if (writerId) await engine.executeRaw('UPDATE persistence_local_writers SET grant_ceiling=$2::text::jsonb WHERE id=$1::uuid', [writerId, JSON.stringify(ceiling)]);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}, 180_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 918c668855..50b250aaee 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -42,6 +42,7 @@ test/managed-cycle-pull-upstream.test.tstest/managed-lint.test.tstest/managed-maintenance-links.test.tstest/managed-sweep-corpus-windows.test.ts+test/managed-sweep-file-refusal-retry.test.tstest/managed-sync-bulk.test.tstest/managed-sync-chunker-version.test.tstest/managed-sync-drain.test.ts