Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract-atoms): the backlog count includes partial pages a raised input cap releases, so a drain no longer stops at zero (#7391)

garrytan6adc25b2d4a9
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 2b67404143..119c0ae69d 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-drain-outcome.ts` — #6817: `drainOutcome(result)`, the one mapping from a drain stop to exit code, JSON `status` (never `ok` for an incomplete stop), `retryable`, `code` and `reason`, read from the error registry (`atom_drain_incomplete` exit 11, `atom_drain_provider_failure` exit 1 with `rate_limit`/`transient` overridden to retryable exit 11, `atom_drain_no_progress` exit 1; a null count is always `atom_drain_incomplete`/`count_unavailable`). Used by `dream --drain` and the `extract-atoms-drain` Minion handler; type-only import of the drain module. Tests: `test/extract-atoms-drain-outcome.test.ts`, `test/dream-drain-failure-summary.serial.test.ts`, `test/extract-atoms-drain-handler.test.ts`.
- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.
-- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).
+- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; `countExtractAtomsBacklog` reads the same cap and counts a page whose partial row or checkpoint sits below it (`pageScanStateExclusionSql` / `managedAtomDiscoverySql` with the cap; #7391), so a drain, doctor and autopilot see it before any phase has released it, while counting itself writes nothing (`test/extract-atoms-raised-cap-drain-7391.test.ts`); a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).
- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. The input cap, the cut and the partial disposition of a cut item are in `extract-atoms-input.ts` (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. A page-derived atom's frontmatter `date` is the source page's content date (`atom-source-date.ts`: the stored `effective_date`, else `computeEffectiveDate`), read with the input before the model call, so classic import and managed publication store that `effective_date` (source `date`) and `extracted_at` stays the processing stamp; transcript-derived atoms carry no `date`. After an unmanaged item completes (`completeUnmanagedItem`), `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce; a cut item neither completes nor retires. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index da3c4b76bb..2de17b9640 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -88,7 +88,7 @@ import { atomSourceDate } from './atom-source-date.ts';
import { normalizeForGrounding } from './synthesize-verify.ts';
import type { TranscriptPageIndex } from '../transcripts/discover.ts';
import { atomOriginPin, managedAtomSession, readAtomOrigin, resumeManagedAtoms, publishManagedAtoms, publishManagedAtomGeneration, resumeManagedGenerationMembers,
- MANAGED_ATOM_DISCOVERY_SQL, type AtomOrigin } from '../persistence/atom-maintenance.ts';
+ MANAGED_ATOM_DISCOVERY_SQL, managedAtomDiscoverySql, type AtomOrigin } from '../persistence/atom-maintenance.ts';
import { effectiveVisibility } from '../search/private-visibility.ts';
import { OperationError } from '../ops/contract.ts';
import { isOpPageSlug } from '../ops/context.ts';
@@ -152,11 +152,15 @@ const RAW_SOURCE_HOLDER_EXCLUSION_SQL =
// #6503: a partial row (the page was cut at the input cap) is skipped like a
// tombstone until releasePartialDispositions clears it under a raised cap.
-const PAGE_SCAN_STATE_EXCLUSION_SQL = `AND NOT EXISTS (
+// #7391: the backlog count passes the current cap, so a row recorded below it
+// (one the phase's release clears) counts before any phase has run.
+const pageScanStateExclusionSql = (maxInputChars?: string) => `AND NOT EXISTS (
SELECT 1 FROM extract_atoms_page_state scan
WHERE scan.source_incarnation=(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id)
- AND scan.page_id=p.id AND scan.content_hash=p.content_hash AND (scan.tombstoned OR scan.partial_input_chars IS NOT NULL)
+ AND scan.page_id=p.id AND scan.content_hash=p.content_hash
+ AND (scan.tombstoned OR ${maxInputChars ? `scan.partial_input_chars >= ${maxInputChars}` : 'scan.partial_input_chars IS NOT NULL'})
)`;
+const PAGE_SCAN_STATE_EXCLUSION_SQL = pageScanStateExclusionSql();
/**
* Pure allowlist policy: the legacy floor (minus floor types the pack declares not extractable, #5756: the floor
@@ -473,6 +477,10 @@ export async function discoverExtractablePages(
* rides migration v104's `pages_atom_source_hash_idx` partial index and stays
* O(log n) on 100K+ brains.
*
+ * #7391: a partial disposition recorded below the current input cap counts,
+ * because the phase releases it before discovery; without it a drain under a
+ * raised cap stopped at a zero count before any phase could release it.
+ *
* PAGE-BACKLOG-ONLY (Codex #11): extract_atoms also discovers transcript files
* at runtime; this count covers DB pages only. Callers label that caveat.
*
@@ -502,8 +510,8 @@ export async function countExtractAtomsBacklog(
AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'
${RAW_SOURCE_HOLDER_EXCLUSION_SQL}
AND ${minCompiledTruthChars('$3')}
- ${MANAGED_ATOM_DISCOVERY_SQL}
- ${PAGE_SCAN_STATE_EXCLUSION_SQL}
+ ${managedAtomDiscoverySql('$4::integer')}
+ ${pageScanStateExclusionSql('$4::integer')}
${connectorExclusion}
AND NOT EXISTS (
SELECT 1 FROM pages atom
@@ -520,8 +528,8 @@ export async function countExtractAtomsBacklog(
AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'
${RAW_SOURCE_HOLDER_EXCLUSION_SQL}
AND ${minCompiledTruthChars('$2')}
- ${MANAGED_ATOM_DISCOVERY_SQL}
- ${PAGE_SCAN_STATE_EXCLUSION_SQL}
+ ${managedAtomDiscoverySql('$3::integer')}
+ ${pageScanStateExclusionSql('$3::integer')}
${connectorExclusion}
AND NOT EXISTS (
SELECT 1 FROM pages atom
@@ -531,9 +539,10 @@ export async function countExtractAtomsBacklog(
AND atom.deleted_at IS NULL
)`;
const extractableTypes = await resolveExtractableTypes();
+ const maxInputChars = await resolveExtractAtomsInputCap(engine);
const params = scoped
- ? [sourceId, extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION]
- : [extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION];
+ ? [sourceId, extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION, maxInputChars]
+ : [extractableTypes, MIN_PAGE_CHARS_FOR_EXTRACTION, maxInputChars];
const rows = await engine.executeRaw<{ cnt: string | number }>(sql, params, { signal: opts.signal });
return Number(rows[0]?.cnt ?? 0);
} catch (err) {
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 07e0c5b9a8..2fcface1ce 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -799,10 +799,18 @@ export function managedAtomCompletedSql(page: { sourceId: string; slug: string;
AND ac.completed_keys->0->>'failure' IS NULL`;
}
-/** #6325: discovery and the backlog skip a page whose current content completed or is held after repeated failures. */
-export const MANAGED_ATOM_DISCOVERY_SQL = `AND NOT EXISTS (SELECT 1 FROM op_checkpoints ac
+/**
+ * #6325: discovery and the backlog skip a page whose current content completed or is held after repeated failures.
+ * #7391: given the current input cap, a partial checkpoint recorded below it (one `releasePartialDispositions` clears) is not skipped.
+ */
+export function managedAtomDiscoverySql(maxInputChars?: string): string {
+ return `AND NOT EXISTS (SELECT 1 FROM op_checkpoints ac
WHERE ${managedAtomIdentitySql({ sourceId: 'p.source_id', slug: 'p.slug', pageId: 'p.id', contentHash: 'p.content_hash' })}
- AND (ac.completed_keys->0->>'failure' IS NULL OR ac.completed_keys->0->>'held'='true'))`;
+ AND (ac.completed_keys->0->>'failure' IS NULL OR ac.completed_keys->0->>'held'='true')${maxInputChars ? `
+ AND (ac.completed_keys->0->>'partial' IS NULL OR (ac.completed_keys->0->>'partial')::integer >= ${maxInputChars})` : ''})`;
+}
+
+export const MANAGED_ATOM_DISCOVERY_SQL = managedAtomDiscoverySql();
export interface HeldManagedAtom {
source_id: string;
diff --git a/test/extract-atoms-raised-cap-drain-7391.test.ts b/test/extract-atoms-raised-cap-drain-7391.test.ts
new file mode 100644
index 0000000000..2242b8552d
--- /dev/null
+++ b/test/extract-atoms-raised-cap-drain-7391.test.ts
@@ -0,0 +1,155 @@
+/**
+ * #7391: a drain under a raised `cycle.extract_atoms.max_input_chars` reported
+ * drained with zero batches while pages cut at a lower cap waited. The drain
+ * counts its backlog before each batch, `countExtractAtomsBacklog` skipped every
+ * partial disposition, and the raised-cap release runs only inside
+ * `runPhaseExtractAtoms`, which a zero count never reaches.
+ *
+ * Protects: the backlog count offers a partial disposition recorded below the
+ * current cap (the release condition the phase applies), so the drain runs a
+ * batch that reads the whole page and records completion; at an unchanged cap
+ * the page stays skipped and the drain does no model work; another source's
+ * partial page is neither released nor processed; counting writes nothing.
+ * Seams: the gateway chat transport (no provider call); PGLite always,
+ * Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';
+import { countExtractAtomsBacklog, runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { runExtractAtomsDrainForSource } from '../src/core/cycle/extract-atoms-drain.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const KNOB = 'cycle.extract_atoms.max_input_chars';
+const CAP = 2_000;
+const SLUG = 'notes/launch-decision';
+const BODY = 'The team decided to measure every launch against clear exit criteria. '.repeat(40)
+ + 'TAIL: the launch also needs an independent review.';
+
+let prompts: string[] = [];
+
+async function seed(engine: BrainEngine, sourceId: string): Promise<void> {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);
+ await engine.putPage(SLUG, { type: 'note', title: 'Launch decision', compiled_truth: BODY, timeline: '' }, { sourceId });
+}
+
+/** One phase run at the current cap: the page is cut and gets a partial disposition. */
+async function cutOnce(engine: BrainEngine, sourceId: string): Promise<void> {
+ const result = await runPhaseExtractAtoms(engine, { sourceId, _transcripts: [] });
+ expect(result.details.input_truncated).toBe(1);
+}
+
+const pageState = (engine: BrainEngine, sourceId: string) =>
+ engine.executeRaw<{ tombstoned: boolean; partial_input_chars: number | null }>(
+ `SELECT scan.tombstoned, scan.partial_input_chars FROM extract_atoms_page_state scan
+ JOIN pages p ON p.id=scan.page_id AND scan.content_hash=p.content_hash WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, SLUG]);
+
+const drain = (engine: BrainEngine, sourceId: string) =>
+ runExtractAtomsDrainForSource(engine, { sourceId, windowSeconds: 60, maxBatches: 3 });
+
+describe('extract_atoms drain under a raised input cap (#7391)', () => {
+ const engines: Array<{ backend: string; engine: BrainEngine; close: () => Promise<void> }> = [];
+
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ __setChatTransportForTests(async opts => {
+ prompts.push(JSON.stringify(opts.messages));
+ const text = JSON.stringify([{ title: 'Measure every launch', atom_type: 'insight', body: 'Measure every launch against clear exit criteria.' }]);
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: opts.model!, providerId: 'anthropic' };
+ });
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push({ backend, engine, close: () => engine.disconnect() });
+ } else {
+ const isolated = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engines.push({ backend, engine: isolated.engine, close: isolated.close });
+ }
+ }
+ }, 120_000);
+ afterAll(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ for (const { engine, close } of engines) { await disposePersistenceConsumer(engine); await close(); }
+ });
+
+ test('a raised cap turns a zero ordinary backlog into one batch that completes the page; other sources stay put', async () => {
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-raised-cap' }, async () => {
+ for (const { backend, engine } of engines) {
+ await engine.setConfig('models.dream.extract_atoms', 'anthropic:claude-haiku-4-5');
+ await engine.setConfig('generations.shrink_floor', '0.05');
+ await engine.setConfig(KNOB, String(CAP));
+ const sourceId = `raised-${backend}`;
+ const sibling = `sibling-${backend}`;
+ await seed(engine, sourceId);
+ await seed(engine, sibling);
+ await cutOnce(engine, sourceId);
+ await cutOnce(engine, sibling);
+ expect(await countExtractAtomsBacklog(engine, sourceId), backend).toBe(0);
+
+ prompts = [];
+ const unchanged = await drain(engine, sourceId);
+ expect(unchanged.stopped, backend).toBe('drained');
+ expect(unchanged.batches, backend).toBe(0);
+ expect(prompts, backend).toHaveLength(0);
+
+ await engine.setConfig(KNOB, String(CAP * 2));
+ const raised = await drain(engine, sourceId);
+ expect(raised.stopped, backend).toBe('drained');
+ expect(raised.batches, backend).toBe(1);
+ expect(raised.input_truncated, backend).toBe(0);
+ expect(raised.remaining, backend).toBe(0);
+ expect(prompts, backend).toHaveLength(1);
+ expect(prompts[0], backend).toContain('TAIL:');
+ expect(await pageState(engine, sourceId), backend).toEqual([{ tombstoned: true, partial_input_chars: null }]);
+ expect((await drain(engine, sourceId)).batches, backend).toBe(0);
+
+ expect(await countExtractAtomsBacklog(engine, sibling), backend).toBe(1);
+ expect(await pageState(engine, sibling), backend).toEqual([{ tombstoned: false, partial_input_chars: CAP }]);
+ expect(prompts, backend).toHaveLength(1);
+ }
+ });
+ }, 120_000);
+
+ test('managed: a raised cap offers the partial checkpoint and the drain completes it through the coordinator', async () => {
+ for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ await managedBrain(async ({ engine }) => {
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-raised-cap' }, async () => {
+ await cutOnce(engine, 'default');
+ await disposePersistenceConsumer(engine);
+ expect(await countExtractAtomsBacklog(engine, 'default'), backend).toBe(0);
+ prompts = [];
+ expect((await drain(engine, 'default')).batches, backend).toBe(0);
+ expect(prompts, backend).toHaveLength(0);
+
+ await engine.setConfig(KNOB, String(CAP * 2));
+ const raised = await drain(engine, 'default');
+ await disposePersistenceConsumer(engine);
+ expect(raised.batches, backend).toBe(1);
+ expect(raised.remaining, backend).toBe(0);
+ expect(prompts, backend).toHaveLength(1);
+ expect(prompts[0], backend).toContain('TAIL:');
+ expect((await engine.executeRaw<{ status: string }>(
+ "SELECT outcome->>'status' AS status FROM persistence_requests WHERE slug='__managed_atom_complete__' ORDER BY sequence"))
+ .map(row => row.status), backend).toEqual(['partial', 'completed']);
+ expect(await countExtractAtomsBacklog(engine, 'default'), backend).toBe(0);
+ });
+ }, { databaseUrl, setup: async ({ engine }) => {
+ await engine.setConfig('models.dream.extract_atoms', 'anthropic:claude-haiku-4-5');
+ await engine.setConfig('generations.shrink_floor', '0.05');
+ await engine.setConfig(KNOB, String(CAP));
+ await seed(engine, 'default');
+ } });
+ }
+ }, 180_000);
+});