Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(persistence): our own implementation of the #6078 fix (#6078)

time-attack311bc8a7a4cc
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index 0606319f44..5ed19b80b1 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -20,7 +20,7 @@
- Read-time TTL validity (there is no sweeper): ACTIVE fact reads in BOTH engines (`listFactsByEntity/Since/BySession`, both `findCandidateDuplicates` branches, `countUnconsolidatedFacts`, `getFactsHealth` active buckets) carry `AND (valid_until IS NULL OR valid_until > now())` — `valid_until` is temporal validity, not retention; history paths (`listSupersessions`, `findTrajectory`, `--asof`) deliberately still see lapsed rows; a re-stated expired fact re-inserts fresh. Pinned by `test/facts/ttl-validity.test.ts` + engine-parity additions.
- Diagnostics: `src/commands/doctor/checks/memory-writeback.ts` (`memory_writeback`, BRAIN category) — quiet-ok when off, but the OFF branch still probes receipt + canonical instruction paths and WARNS on a lingering block (off-but-still-instructing) with the converge command; plane-compare warns when the file mirror disagrees with the DB row (the Stop hook acting on the wrong truth) naming the re-sync; a read_error reports the state as UNKNOWN, never "off (default)"; resolved bundle + BOTH visibility postures + audience/reasons; on both branches an explicit private `facts.default_visibility` on a non-shared brain with remote readers (a harness receipt, or HTTP MCP clients active in 30d; listed in `private_default_remote_readers`) warns with the shared `PRIVATE_DEFAULT_REMOTE_CONSEQUENCE` text (`writeback-config.ts`), the same text `bootstrap harness` prints before consent; instruction blocks receipt-vs-live-probe-vs-drift compare (drift fix names the `config set` + `bootstrap harness` combo — the config set re-stamps the posture mirror so the re-render converges even after an out-of-band visibility flip) + AGENTS.override.md detection — and a receipt target in state `failed` is a STANDING warn regardless of the live probe (the one physical-survival path — a smoke-rollback strip that itself threw — leaves a current-looking block directing sessions at a rolled-back endpoint, and only the receipt state knows) naming the `bootstrap harness --yes` / `--remove` converge; validity-lapsed count; 7d counters (verbs usage sidecar's additive `remember_status` [stamped in `src/mcp/dispatch.ts`, ALL-MCP-callers semantics labeled honestly] + `writeback`/`writeback-bank` heartbeat events; `turns_banked` counts flush_skip_* — banked, enqueue declined); when at least 10 serve-side harvests finished (ok + error; a `writer_busy_requeued` retry is not finished) in those 7d and more than 20% failed, a warn names the failure count, the top error reason and the `gbrain sweep --once` recovery; `details.corpus_backlog` counts corpus files with no `.ingested` sidecar (pending, oldest age, past retention, deletion day) and, with writeback on, warns once one is past plain retention (E-N1) with the local/lossy disclosure. Null-engine runs report the file mirror honestly. `cross_lane_duplicates_7d` / `near_duplicates_shadow_7d` sum the `writeback_dedup` heartbeat events in both the on and off branches.
- Tests: `test/writeback-config.test.ts`, `test/mcp-instructions-writeback.test.ts`, `test/facts/writeback-gate.test.ts`, `test/hook-writeback-stop.serial.test.ts`, writeback-lane cases in `test/checkpoint-harvest.serial.test.ts`, `test/bootstrap-instructions-block.test.ts` + harness serial additions, `test/writeback-nudge.serial.test.ts`, `test/doctor-memory-writeback.test.ts`, the hermetic 5-step `test/ambient-writeback-lifecycle.serial.test.ts`, and the NON-GATING real-codex door (`test/e2e/bootstrap-real-codex.serial.test.ts`, ambient-writeback describe).
-- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window whose managed facts batch the canonical file check refused is re-admitted from its retained facts once each refused page passes the check (`retryClearedFileRefusals`; at most three attempts, committed siblings kept, visibility only narrowed, current writer grant re-checked). Pinned by `test/managed-sweep-file-refusal-retry.test.ts`.
+- `src/core/sweep.ts` + `src/commands/sweep.ts` — the serve-resident maintenance sweep (the lock owner closes the persistence loop): facts-fence reconciliation (zero-LLM, reuses the cycle extractor with a slug subset), deterministic link/timeline extraction over recent workspace pages (the same cores as `gbrain extract` — remote put_page deliberately skips these, the sweep is where the graph compounds), and spend-gated corpus ingest (skipped keyless; turn-boundary windows through `src/core/context/corpus-windows.ts`, at most `CORPUS_WINDOWS_PER_SWEEP` (8) per file and `CORPUS_WINDOWS_PER_SWEEP_TOTAL` (32, env `GBRAIN_CORPUS_WINDOWS_PER_SWEEP`) per sweep, each windowed file reported in `corpus_files[]` as `{file, windows_done, windows_remaining}`; `.ingested` is written when the last window of the current snapshot finishes, and a finished file re-enters when its stat no longer matches its `.progress`; writeback `.wb-` turn files stay one call; dream outputs and claude-cli self-captures classified by `isClaudeCliSelfSessionId` get a terminal `.ingested` sidecar with `skipped: dream_output` / `self_capture` (the shared `selfCaptureSidecarJson` writer) and are never extracted; the extractor input is `corpusTextForExtraction`, so pasted blocks never reach it). Bounded, fail-soft, never throws; the wall-clock budget stops the corpus pass between files and windows, never mid-extraction (an in-flight extraction finishes and writes its sidecar, E-N2, pinned by `test/sweep-budget-between-items.test.ts`); armed at serve startup (3s, best-effort) and on 10-min idle ticks through the injectable timer seam, everything unref'd; `serve --http` arms `armCorpusDrain` instead (X8: every `CORPUS_DRAIN_INTERVAL_MS`, 10 min, one sweep on a `CORPUS_DRAIN_BUDGET_MS` 60 s budget while a corpus `.txt` has no `.ingested` sidecar; never overlaps itself; pinned by `test/serve-http-corpus-drain.test.ts`); `GBRAIN_SWEEP=0` kills both. `gbrain sweep --once` is the trusted CLI seam `bootstrap verify` uses (CLI-only, never over MCP). The link pass threads the same `link_resolution.cross_source` opt-in and configured `sources.default` the CLI extract lanes pass into `resolveCandidateSources`, so an edge into another source is created (flag on) or counted as `cross_source_link` in `skipped` (flag off) — never silently dropped, and the reconcile never deletes a cross-source edge `extract links --source db` created. A corpus window's facts batch is keyed by its text (the sweep passes `reAdmitFileRefusals`), so when the canonical file check refused some of its entity requests, `resumeManagedFacts` admits their retained facts as a follow-up batch once every refused page passes that check again: no new extraction, the page's current revision, never wider than the current default visibility, committed requests reported rather than re-admitted, the stored and current writer grants re-checked, at most three follow-ups. Pinned by `test/managed-sweep-refused-window-retry.test.ts`.
- `src/core/context/corpus-windows.ts` — windowed fact extraction of session-corpus files (#5887). `parseCorpusTurns` splits only at the exact `\n\n[user]\n` / `\n\n[assistant]\n` markers `toCorpusText` emits (text before the first marker is a header-less preamble); each user turn is paste-stripped whole before windowing; `planCorpusWindows` packs whole turns into windows of at most `MAX_TURN_TEXT_CHARS` (exported from `facts/extract.ts`) and splits a turn that cannot fit a fresh window at a newline or space, never inside a surrogate pair, repeating its `[role]` header on every piece. `<file>.progress` (suffix constants in `corpus-segments.ts`, GC'd by the session-end hook with the `.txt`, never deleted by its resume rewrite) holds `{version, generation, turns[{start,end,sha256}], continuation{turn_sha256, stripped_offset}|null, windows_done, finished(stat)|null, totals, entity_slugs, skipped_reason?, lease}`: `resumePoint` resumes at the first turn whose hash is unrecorded (appends, compaction remainders and same-size or shorter rewrites cost only their new turns). Every write is compare-and-set under the O_EXCL `<file>.progress.lock` (stale after 30 s): a window commits only when generation, last turn hash and lease owner still match and progress grows; the lease (stale after an hour, like the claim) stops a sweep whose `.in-progress` claim the hook deleted from extracting a window another extractor holds. `runCorpusWindows` returns `complete`/`partial`/`aborted`/`contended` with cumulative counts; an aborted window records nothing and transport errors release the lease and throw. `finishedCorpusFileState` decides `.ingested` files by stat compare (no rehash); `adoptFinishedCorpusFile` records a pre-window `.ingested` file at its current turns once (only when the sidecar is newer than the file). `checkpoint-harvest.ts` (`hook:compact`) extracts window 1 only: when more remains it publishes window 1's links, releases the receipt and leaves `.progress` for the sweep; an existing `.progress` means window 1 is done. Pinned by `test/corpus-windows.test.ts`, `test/sweep-corpus-windows.test.ts` and `test/managed-sweep-corpus-windows.test.ts` (managed coordinator, PGLite and Postgres).
- `src/core/context/sync-ipc.ts` + `src/core/serve-sync-runner.ts` + `src/commands/sync-delegate.ts` — serve-delegated sync. `sync-ipc.ts` is the LEAF wire module: the `DELEGATED_SYNC_OPTION_FIELDS` table is the single source of truth for the validator, the CLI wire-builder, and the serve-side SyncOpts builder; `validateDelegatedSyncOptions` rejects unknown keys fail-closed (repoPath/skipLock/lockId/concurrency are unreachable from the socket), requires `timeoutSeconds` (0 = the explicit `--no-hard-deadline` unbounded encoding; everything else clamps to 24h), and `toWireSyncResult` truncates `pagesAffected` to 50 + a true total under the 256KB message cap. `serve-sync-runner.ts` is the serve-side module singleton: one job at a time (correctness still rests on the `gbrain-sync:<source>` row lock inside performSync), clientToken attach (a lost-ack retry finds its own running OR retained-terminal job instead of duplicate-running), per-job deadline timer, `[serve-sync]` lifecycle stderr lines, an idempotent shared `shutdownDelegatedSync()` both serve shutdown paths await BEFORE `engine.disconnect()` (the disconnect-mode drain is allowAbort:false after `_db` is nulled, so settle writes need the live engine; a registered drainer remains as backstop), and `maybeDrainDeferredEmbeds` (delegated jobs always run noEmbed — the cost gate lives in runSync — and the serve drains stale embeds afterwards via `runEmbedCore`, keyless-safe, cleared only when a drain finds nothing left; wire `noEmbed` records that the USER declined embeds and suppresses the drain). `sync-delegate.ts` is the CLI half: read-only holder probe (`probeLivePgliteHolder`), DEFAULT-DENY argv gate (any unclassified token refuses by name — a silently dropped `--exclude` would perform the wrong sync), engine-free source tiers (`resolveSourceIdEngineFree`), 1s poll loop tolerant of event-loop-blocked serves with a PID-probe backstop, `unknown_job` → serve-restarted resume hint, Ctrl-C → `sync_abort` (second Ctrl-C exits 130), and runSync's `pull_failed` verdict mirroring. Mounts and non-PGLite configs never delegate; opt-outs `--no-delegate` / `GBRAIN_SYNC_NO_DELEGATE=1` (client) and `GBRAIN_SERVE_SYNC_IPC=0` (serve). Pinned by `test/context/sync-ipc-validation.test.ts`, `test/sync-delegate-ladder.test.ts`, `test/serve-sync-runner.serial.test.ts`, `test/context/resolve-ipc-sync-kinds.test.ts`, and `test/e2e/sync-delegation-under-serve.serial.test.ts` (gating tier1 step).
- `src/core/capability.ts` — config-plane keyless/keyed detection + the honest capability report (per-provider keyless banner: OpenAI = semantic search + auto-extraction, Voyage = semantic search, Anthropic = auto-extraction) rendered by verify and the runbook. The extraction probe resolves through the SAME shared `resolveEffectiveChatModel` the gateway's reconfigure fallback uses (`GBRAIN_MODEL` > servable file pin > key-aware tier default), so a stale unservable pin degrades identically in the report and at runtime. Key/env fold comes from `mergedProviderEnv` (`src/core/ai/provider-env.ts`). Accepted limitation (documented in the module): DB-plane overrides (`models.default`, `facts.extraction_model`) are invisible to this engine-less probe; the runtime gate in `facts/extract.ts` and the engine-aware pre-enqueue gate in `facts/backstop.ts` are the backstops.
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 6ccc5fdd4d..ac2cf701eb 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -137,11 +137,11 @@ export interface FactsBackstopCtx {
/** #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).
+ * #6048: with no request id (the batch is keyed by its input), re-admit the
+ * retained facts of entity requests the canonical file check refused once
+ * their pages pass it again (persistence/facts-maintenance.ts).
*/
- retryClearedFileRefusals?: boolean;
+ reAdmitFileRefusals?: boolean;
}
/** Discriminated return shape based on FactsBackstopCtx.mode. */
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 9688941d83..6cff7dc029 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -11,13 +11,13 @@ import type { Action } from '../agent-output.ts';
import { resolveEntitySlugWithSource } from '../entities/resolve.ts';
import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';
import { inferenceNote } from '../facts/subject-infer-write.ts';
+import { resolveDefaultVisibility } from '../facts/visibility.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.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';
@@ -55,12 +55,12 @@ 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: the batch is keyed by its input alone and the caller asked to re-admit facts the canonical file check refused. */
+ fileRefusalRetry?: boolean;
}
-/** #6048: new attempts a batch gets for entity requests the canonical file check refused. */
-const FILE_REFUSAL_ATTEMPTS = 3;
+/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */
+const MAX_FILE_REFUSAL_RETRIES = 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 } } });
@@ -71,22 +71,15 @@ const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sou
const 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_SLUG
+ if (prior.operation !== 'extract_facts' || prior.slug !== '__managed_facts_complete__'
|| 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.',
@@ -242,26 +235,21 @@ 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) : completionRequestIdFor(batchKey),
- ...(ctx.retryClearedFileRefusals && seed === inputDigest ? { retryFileRefusals: true as const } : {}) };
+ completionRequestId: ctx.requestId ? requireUuid(ctx.requestId) : managedFactRequestId(batchKey, '__managed_facts_complete__'),
+ fileRefusalRetry: ctx.reAdmitFileRefusals === true && seed === inputDigest };
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) {
- const finished = await settleManagedFact(engine, session, row);
+ 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());
writeResponse(finished);
result.write_requests.push(receiptFor(finished));
if ((row.intent?.kind ?? row.outcome?.kind) === 'managed_facts_entity') {
@@ -276,133 +264,90 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes
return result;
}
-/** 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> {
+export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFactsSession): Promise<ManagedFactsResult | null> {
+ const stored = await storedBatch(engine, session);
+ return stored && collectManagedFacts(engine, session, session.fileRefusalRetry ? await followFileRefusals(engine, session, stored) : stored);
+}
+
+/** Every request journaled under the session's batch key, once its completion receipt validates; null when nothing was accepted. */
+async function storedBatch(engine: BrainEngine, session: ManagedFactsSession): 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=$4
AND (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, batchKey, completionRequestId]);
+ session.authority.principal.kind, session.authority.principal.id, session.batchKey, session.completionRequestId]);
if (!rows.length) return null;
- const completion = rows.find(row => row.request_id === completionRequestId);
+ const completion = rows.find(row => row.request_id === session.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 ${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 ${session.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 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);
-}
+const isEntityRequest = (row: WriteRequest) => (row.intent?.kind ?? row.outcome?.kind) === 'managed_facts_entity';
/**
- * #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.
+ * #6048: an input-keyed batch (the sweep has no request id to give a window)
+ * would replay a terminal file-check refusal forever. Walk its follow-up
+ * batches instead: while every request of the latest one is terminal and each
+ * uncommitted entity request is a `source_changed` refusal that kept its facts,
+ * look for the next follow-up, or admit it when every refused page now passes
+ * the file check. Returns the committed entity requests of earlier batches and
+ * all requests of the latest one, for collectManagedFacts to report.
*/
-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;
+async function followFileRefusals(engine: BrainEngine, session: ManagedFactsSession, stored: WriteRequest[]): Promise<WriteRequest[]> {
+ const carried: WriteRequest[] = [];
+ let latest = stored;
+ for (let retry = 1; retry <= MAX_FILE_REFUSAL_RETRIES; retry++) {
+ if (latest.some(row => !isTerminal(row))) break;
+ const refused = latest.filter(row => isEntityRequest(row) && row.state !== 'committed');
+ const retained = refused.map(row => row.intent as ManagedFactIntent | null);
+ if (!refused.length || refused.some((row, i) => row.error_code !== 'source_changed' || !retained[i]?.facts?.length
+ || retained[i]!.inputDigest !== session.inputDigest || !sameSignature(retained[i]!.embedding, retained[0]!.embedding))) break;
+ const followUpKey = digest([session.batchKey, 'file-refusal-retry', retry]);
+ const followUp: ManagedFactsSession = { ...session, batchKey: followUpKey, embedding: retained[0]!.embedding ?? null,
+ completionRequestId: managedFactRequestId(followUpKey, '__managed_facts_complete__') };
+ const admitted = await storedBatch(engine, followUp) ?? await readmitRefusedFacts(engine, followUp, refused);
+ if (!admitted) break;
+ carried.push(...latest.filter(row => isEntityRequest(row) && row.state === 'committed'));
+ latest = admitted;
}
- return [...kept, ...batch];
+ return [...carried, ...latest];
}
-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;
+function sameSignature(a: FactEmbeddingSignature | null | undefined, b: FactEmbeddingSignature | null | undefined): boolean {
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
}
/**
- * #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.
+ * #6048: admit the refused requests' retained facts as `followUp`, or return
+ * null (nothing admitted) while any refused page still fails the canonical
+ * file check. Each refused request must still be authorized under its stored
+ * authority and its page under the current writer grant; facts target the
+ * page's current revision and are never wider than the current default
+ * visibility. No extraction runs again.
*/
-async function admitFileRefusalAttempt(engine: BrainEngine, session: ManagedFactsSession, batchKey: string, completionRequestId: string,
- refused: WriteRequest[]): Promise<WriteRequest[]> {
- const narrow = await resolveDefaultVisibility(engine) === 'private';
- const inputs: ManagedFactsBatchInput[] = [];
+async function readmitRefusedFacts(engine: BrainEngine, followUp: ManagedFactsSession, refused: WriteRequest[]): Promise<WriteRequest[] | null> {
+ const { sourceId, remote } = followUp.authority;
+ const activePack = (await loadActivePackForEngine(engine, { remote, sourceId }).catch(() => null))?.manifest;
+ const privateOnly = await resolveDefaultVisibility(engine) === 'private';
+ const entities: ManagedFactsEntityInput[] = [];
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);
+ await authorizeStoredRequest(engine, row);
+ await authorizeWrite(engine, followUp.authority, 'extract_facts', row.slug);
+ const page = await engine.readPageSnapshot(row.slug, { sourceId });
+ if (!page) return null;
+ try {
+ await prepareFileTarget(engine, { source_id: sourceId, worktree_id: followUp.binding?.worktree_id ?? null, slug: row.slug }, page, null, undefined, { activePack, remote });
+ } catch (refusal) {
+ if (refusal instanceof OperationError) return null;
+ throw refusal;
}
- return accepted;
- });
+ const { expected_revision: _refusedRevision, facts, ...kept } = row.intent as ManagedFactIntent;
+ entities.push({ slug: row.slug, pageId: page.page.id, intent: { ...kept, batchKey: followUp.batchKey, expected_revision: page.revision,
+ facts: privateOnly ? facts!.map(fact => ({ ...fact, visibility: 'private' as const })) : facts } });
+ }
+ return admitManagedFactsBatch(engine, followUp, entities, entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
}
export async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,
@@ -429,7 +374,7 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
valid_from: (fact.valid_from ?? ctx.validFrom ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });
groups.set(slug, group);
}
- const inputs: ManagedFactsBatchInput[] = [];
+ const inputs: ManagedFactsEntityInput[] = [];
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.',
@@ -441,7 +386,32 @@ 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 admitManagedFactsBatch(engine, session, { batchKey: session.batchKey, completionRequestId: session.completionRequestId,
- embedded, embedding: session.embedding }, inputs, ctx.abortSignal);
- return collectManagedFacts(engine, session, rows);
+ return collectManagedFacts(engine, session, await admitManagedFactsBatch(engine, session, inputs, embedded, ctx.abortSignal));
+}
+
+interface ManagedFactsEntityInput { slug: string; pageId: number | null; intent: ManagedFactIntent }
+
+/** One transaction: the session's per-entity fact requests, then the completion request that names them. */
+async function admitManagedFactsBatch(engine: BrainEngine, session: ManagedFactsSession, inputs: ManagedFactsEntityInput[],
+ embedded: boolean, signal?: AbortSignal): Promise<WriteRequest[]> {
+ const sourceId = session.authority.sourceId;
+ return 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 (signal?.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;
+ });
}
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 22d4929b67..2ff86c3455 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -744,7 +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
+ reAdmitFileRefusals: true,
...(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.ts
deleted file mode 100644
index cf4aa4ca0a..0000000000
--- a/test/managed-sweep-file-refusal-retry.test.ts
+++ /dev/null
@@ -1,347 +0,0 @@
-/**
- * #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/managed-sweep-refused-window-retry.test.ts b/test/managed-sweep-refused-window-retry.test.ts
new file mode 100644
index 0000000000..bb4055bad1
--- /dev/null
+++ b/test/managed-sweep-refused-window-retry.test.ts
@@ -0,0 +1,273 @@
+/**
+ * #6048: the sweep has no request id for a corpus window, so its managed facts
+ * batch is keyed by the window text. When the canonical file check refused an
+ * entity request, every later sweep used to replay that stored refusal, and the
+ * window (and every window after it) never ingested.
+ *
+ * 1. Protects: once every refused page passes the file check again, the
+ * retained facts are admitted as a follow-up batch, with no new extraction,
+ * at the page's current revision and never wider than the current default
+ * visibility; committed siblings are reported, not re-admitted; at most
+ * three follow-ups per window.
+ * 2. Fails when: the refusal replays forever, a follow-up is admitted while the
+ * page still drifts, beside a refusal of another kind, for a refused request
+ * that kept no facts or belongs to other input, or past the cap.
+ * 3. managed-sweep-corpus-windows.test.ts covers windows that commit.
+ * 4. Seams: gateway test transports and the persistence fault hook.
+ *
+ * Runs on PGLite; also on Postgres when DATABASE_URL is set (testBackends).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { appendFileSync, 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 { prepareManagedFactsSession } from '../src/core/persistence/facts-maintenance.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import type { FactsBackstopCtx } from '../src/core/facts/backstop.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 COMPLETE = '__managed_facts_complete__';
+const COMPANY = { slug: 'companies/widget-co', title: 'Widget Co', type: 'company' };
+const PERSON = { slug: 'people/charlie-example', title: 'Charlie Example', type: 'person' };
+
+const engines: BrainEngine[] = [];
+const dbDir = mkdtempSync(join(tmpdir(), 'gbrain-refused-window-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+let extractions = 0;
+let named: Array<typeof COMPANY> = [];
+
+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 (): Promise<ChatResult> => {
+ extractions++;
+ const facts = named.map(entity => ({ fact: `${entity.title} ships the example roadmap`, kind: 'fact', entity: entity.slug, confidence: 0.9, notability: 'high' }));
+ return { text: JSON.stringify({ facts }), blocks: [], stopReason: 'end', model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ usage: { input_tokens: 5, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map((value, i) => {
+ const vector = Array(1536).fill(0);
+ vector[(value.length * 7 + i) % 1536] = 1;
+ return vector;
+ }) })) as never);
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dbDir });
+ await engine.initSchema();
+ engines.push(engine);
+ } else {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(isolated.engine);
+ closePostgres = isolated.close;
+ }
+ }
+}, 120_000);
+
+afterAll(async () => {
+ installFaultHook(undefined);
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ resetGateway();
+ rmSync(dbDir, { recursive: true, force: true });
+});
+
+const transcript = () => toCorpusText([
+ { role: 'user', text: 'Planning notes for the example roadmap. '.repeat(40) },
+ { role: 'assistant', text: 'Summary of the example roadmap discussion. '.repeat(40) },
+]);
+
+/** A managed source holding committed entity pages, with one corpus transcript whose window refers to `named`. */
+async function refusedWindow(engine: BrainEngine, dir: string, pages: Array<typeof COMPANY>, drifted: Array<typeof COMPANY>) {
+ const root = join(dir, 'checkout'); mkdirSync(root);
+ const corpusDir = join(dir, 'sessions'); mkdirSync(corpusDir);
+ const sourceId = `refused-${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]);
+ for (const [key, value] of [['sync.write_through', 'true'], ['facts.extraction_enabled', 'true'], ['dream.synthesize.session_corpus_dir', corpusDir],
+ ['facts.default_visibility', 'world']]) await engine.setConfig(key, value);
+ 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() {} } } as unknown as OperationContext;
+ for (const page of pages) {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: page.slug, request_id: randomUUID(),
+ content: `---\ntitle: ${page.title}\ntype: ${page.type}\n---\n# ${page.title}\n` } });
+ }
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const fileOf = (page: typeof COMPANY) => join(root, `${page.slug}.md`);
+ const pristine = new Map(pages.map(page => [page.slug, readFileSync(fileOf(page))]));
+ const drift = (page: typeof COMPANY) => appendFileSync(fileOf(page), '\nA local edit nobody imported.\n');
+ const repair = (page: typeof COMPANY) => writeFileSync(fileOf(page), pristine.get(page.slug)!);
+ for (const page of drifted) drift(page);
+ const sessionFile = join(corpusDir, 'example-session.txt');
+ writeFileSync(sessionFile, transcript());
+ const logs: string[] = [];
+ const quiet = () => waitFor(async () => (await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')`, [sourceId]))[0].n === 0,
+ { timeoutMs: 30_000, label: 'fact requests settled' });
+ const sweep = async () => {
+ const report = await runMaintenanceSweep(engine, { sourceId, capabilities: KEYED, budgetMs: 120_000, log: line => logs.push(line) });
+ await quiet();
+ return report.corpusIngested;
+ };
+ const journal = () => engine.executeRaw<{ slug: string; state: string; error_code: string | null }>(
+ `SELECT slug, state, error_code FROM persistence_requests WHERE source_id=$1 AND operation='extract_facts' ORDER BY sequence`, [sourceId])
+ .then(rows => rows.map(row => `${row.slug}:${row.state}${row.error_code ? `:${row.error_code}` : ''}`));
+ const facts = () => engine.executeRaw<{ entity: string; visibility: string }>(
+ `SELECT entity_slug AS entity, visibility FROM facts WHERE source_id=$1 AND source='sweep:corpus' AND expired_at IS NULL ORDER BY entity_slug`, [sourceId])
+ .then(rows => rows.map(row => `${row.entity}:${row.visibility}`));
+ return { sourceId, ctx, logs, sessionFile, drift, repair, sweep, journal, facts, quiet };
+}
+
+async function onEachEngine(label: string, body: (engine: BrainEngine, dir: string) => Promise<void>) {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), `gbrain-refused-window-${label}-`));
+ extractions = 0;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, () => body(engine, dir));
+ } finally {
+ installFaultHook(undefined);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+const refusedFirstPass = [`${COMPANY.slug}:conflict:source_changed`, `${PERSON.slug}:committed`, `${COMPLETE}:conflict:revision_conflict`];
+
+describe('a sweep window refused by the canonical file check (#6048)', () => {
+ test('stays refused while the page drifts, then publishes its retained facts once the file is repaired', async () => {
+ named = [COMPANY, PERSON];
+ await onEachEngine('repair', async (engine, dir) => {
+ const w = await refusedWindow(engine, dir, [COMPANY, PERSON], [COMPANY]);
+ expect(await w.sweep()).toBe(0);
+ expect(await w.journal()).toEqual(refusedFirstPass);
+ expect(await w.sweep()).toBe(0);
+ expect(await w.journal()).toEqual(refusedFirstPass);
+
+ w.repair(COMPANY);
+ await submitRememberMutation(w.ctx, { fact: 'Widget Co moved offices', entity: COMPANY.slug, provenance: 'test', visibility: 'private' }, 10_000);
+ await w.quiet();
+ await engine.setConfig('facts.default_visibility', 'private');
+ expect(await w.sweep()).toBe(1);
+ expect(extractions).toBe(1);
+ expect(await w.journal()).toEqual([...refusedFirstPass, `${COMPANY.slug}:committed`, `${COMPLETE}:committed`]);
+ expect(await w.facts()).toEqual([`${COMPANY.slug}:private`, `${PERSON.slug}:world`]);
+ const ingested = JSON.parse(readFileSync(w.sessionFile + CORPUS_INGESTED_SUFFIX, 'utf8'));
+ expect(ingested.facts_inserted).toBe(2);
+
+ expect(await w.sweep()).toBe(0);
+ expect((await w.journal()).length).toBe(refusedFirstPass.length + 2);
+ });
+ }, 180_000);
+
+ test('a page whose publication keeps refusing gets three follow-ups, then the refusal stands', async () => {
+ named = [COMPANY];
+ await onEachEngine('cap', async (engine, dir) => {
+ const w = await refusedWindow(engine, dir, [COMPANY], [COMPANY]);
+ expect(await w.sweep()).toBe(0);
+ installFaultHook((point, detail) => {
+ if (point === 'consumer:prepared' && detail.operation === 'extract_facts' && detail.sourceId === w.sourceId) w.drift(COMPANY);
+ });
+ for (let followUps = 1; followUps <= 3; followUps++) {
+ w.repair(COMPANY);
+ expect(await w.sweep()).toBe(0);
+ expect((await w.journal()).length).toBe(2 * (followUps + 1));
+ expect((await w.journal()).slice(-2)).toEqual([`${COMPANY.slug}:conflict:source_changed`, `${COMPLETE}:conflict:revision_conflict`]);
+ }
+ installFaultHook(undefined);
+ w.repair(COMPANY);
+ expect(await w.sweep()).toBe(0);
+ expect((await w.journal()).length).toBe(8);
+ expect(extractions).toBe(1);
+ expect(await w.facts()).toEqual([]);
+ });
+ }, 180_000);
+
+ test('a refusal of another kind beside the file refusal admits no follow-up', async () => {
+ named = [COMPANY, PERSON];
+ await onEachEngine('mixed', async (engine, dir) => {
+ const w = await refusedWindow(engine, dir, [COMPANY, PERSON], [COMPANY, PERSON]);
+ expect(await w.sweep()).toBe(0);
+ await engine.executeRaw(`UPDATE persistence_requests SET error_code='revision_conflict' WHERE source_id=$1 AND slug=$2`, [w.sourceId, PERSON.slug]);
+ const before = await w.journal();
+ expect(before).toEqual([`${COMPANY.slug}:conflict:source_changed`, `${PERSON.slug}:conflict:revision_conflict`, `${COMPLETE}:conflict:revision_conflict`]);
+ w.repair(COMPANY); w.repair(PERSON);
+ expect(await w.sweep()).toBe(0);
+ expect(await w.journal()).toEqual(before);
+ expect(await w.facts()).toEqual([]);
+ });
+ }, 180_000);
+
+ test('a refused request without retained facts, or carrying other input, admits no follow-up', async () => {
+ named = [COMPANY];
+ for (const tamper of [`intent - 'facts'`, `jsonb_set(intent, '{inputDigest}', '"example-foreign-digest"')`]) {
+ await onEachEngine('retained', async (engine, dir) => {
+ const w = await refusedWindow(engine, dir, [COMPANY], [COMPANY]);
+ expect(await w.sweep()).toBe(0);
+ await engine.executeRaw(`UPDATE persistence_requests SET intent = ${tamper} WHERE source_id=$1 AND slug=$2`, [w.sourceId, COMPANY.slug]);
+ w.repair(COMPANY);
+ expect(await w.sweep()).toBe(0);
+ expect(await w.journal()).toEqual([`${COMPANY.slug}:conflict:source_changed`, `${COMPLETE}:conflict:revision_conflict`]);
+ expect(await w.facts()).toEqual([]);
+ });
+ }
+ }, 180_000);
+
+ test('a writer grant narrowed since the refusal admits no follow-up', async () => {
+ named = [COMPANY, PERSON];
+ for (const narrowed of [`'{slugPrefixes}', '["people/"]'`, `'{operations}', '["put_page"]'`]) {
+ await onEachEngine('narrowed', async (engine, dir) => {
+ const w = await refusedWindow(engine, dir, [COMPANY, PERSON], [COMPANY]);
+ expect(await w.sweep()).toBe(0);
+ const [writer] = await engine.executeRaw<{ id: string }>(`SELECT principal_id AS id FROM persistence_requests
+ WHERE source_id=$1 AND slug=$2 AND principal_kind='local_cli' LIMIT 1`, [w.sourceId, COMPANY.slug]);
+ const [{ ceiling }] = await engine.executeRaw<{ ceiling: string }>('SELECT grant_ceiling::text AS ceiling FROM persistence_local_writers WHERE id=$1::uuid', [writer.id]);
+ await engine.executeRaw(`UPDATE persistence_local_writers SET grant_ceiling = jsonb_set(grant_ceiling, ${narrowed}) WHERE id=$1::uuid`, [writer.id]);
+ try {
+ const factsBefore = await w.facts();
+ w.repair(COMPANY);
+ expect(await w.sweep()).toBe(0);
+ expect(await w.journal()).toEqual(refusedFirstPass);
+ expect(await w.facts()).toEqual(factsBefore);
+ expect(w.logs.join('\n')).toMatch(/grant|unconfined/);
+ } finally {
+ await engine.executeRaw('UPDATE persistence_local_writers SET grant_ceiling=$2::text::jsonb WHERE id=$1::uuid', [writer.id, ceiling]);
+ }
+ });
+ }
+ }, 180_000);
+
+ test('only an input-keyed extraction that asked for it is marked for follow-ups', async () => {
+ named = [COMPANY];
+ await onEachEngine('session', async (engine, dir) => {
+ const w = await refusedWindow(engine, dir, [COMPANY], []);
+ const base = { engine, sourceId: w.sourceId, source: 'sweep:corpus', sessionId: 'example-session', operationContext: w.ctx } as unknown as FactsBackstopCtx;
+ const marked = async (extra: Partial<FactsBackstopCtx>) =>
+ (await prepareManagedFactsSession({ ...base, ...extra }, { turnText: transcript() } as never))?.fileRefusalRetry;
+ expect(await marked({ reAdmitFileRefusals: true })).toBe(true);
+ expect(await marked({})).toBe(false);
+ expect(await marked({ reAdmitFileRefusals: true, requestId: randomUUID() })).toBe(false);
+ });
+ }, 180_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 50b250aaee..18528fa941 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -42,7 +42,7 @@ test/managed-cycle-pull-upstream.test.ts
test/managed-lint.test.ts
test/managed-maintenance-links.test.ts
test/managed-sweep-corpus-windows.test.ts
-test/managed-sweep-file-refusal-retry.test.ts
+test/managed-sweep-refused-window-retry.test.ts
test/managed-sync-bulk.test.ts
test/managed-sync-chunker-version.test.ts
test/managed-sync-drain.test.ts