Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(atoms): drain stops 'budget' with spend and cap instead of no_progress (#6425)

time-attack446fa8f99131
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 38686bf42d..8a720210a3 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -17,7 +17,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-cost-gate.ts` — cost-gate decision for the extract_atoms `BudgetTracker`, shared with the Life Chronicle `chronicle` phase through `settleExtractAtomsCostGate`'s `target` (phase name, refusal key prefix `chronicle.no_pricing.`, no rollup). `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` (pure) returns `{enforceCap, unpricedModel?, unpricedKind?, refusal?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable). A DEFAULT cap is dropped for an unpriced route (warn and run). When the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced chat model or embed route yields `refusal` (the shared `no_pricing` guidance). `settleExtractAtomsCostGate` acts before any work item: it warns on a dropped cap; on a refusal it returns the phase's `warn` result (`details.reason: 'no_pricing'`, `details.no_pricing`, no model call), records the guidance at `cycle.extract_atoms.no_pricing.<source>` and upserts the rollup as an expected limit, not a halt; any run past the gate clears the source's record (dry runs record nothing). `readExtractAtomsNoPricing` + `withExtractAtomsNoPricing` overlay doctor's `extract_health` (wired in `doctor/checks/local-audits.ts`) with a `warn` naming the model and `register_command`. Pinned by `test/extract-atoms-embed-cost-gate.test.ts` and `test/extract-atoms-explicit-cap-no-pricing.test.ts`.
-- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure`); a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline` or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.test.ts`.
+- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure|budget`); `budget` (#6425) stops after the first batch that reports `budgetSkipped > 0` (the attempt's one tracker is spent) and carries `spent_usd`/`budget_usd`, which `dream --drain` renders as the spend, the cap and an `atom_drain_budget` notice whose paid fix raises `cycle.extract_atoms.budget_usd`; the Minion handler completes it normally; a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline` or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.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.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. 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. 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. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce. 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.
diff --git a/src/commands/dream.ts b/src/commands/dream.ts
index f938da986b..12ff2929bb 100644
--- a/src/commands/dream.ts
+++ b/src/commands/dream.ts
@@ -653,17 +653,22 @@ async function runDrain(
`[drain] ${result.failure_count} item failure(s)${omitted}${result.last_error ? `; last error: ${result.last_error}` : ''}\n`,
);
}
+ const { drainBudgetNotice, usd } = await import('../core/cycle/extract-atoms-budget-notice.ts');
+ const budgetNotice = result.stopped === 'budget' ? drainBudgetNotice(result) : null;
if (opts.json) {
const done = result.stopped === 'drained' && result.remaining === 0;
- await writeJsonDocument(JSON.stringify(done ? result : { ...result, resume_command: drainCommand(opts) }, null, 2));
+ await writeJsonDocument(JSON.stringify(done ? result : { ...result, resume_command: drainCommand(opts),
+ ...(budgetNotice ? { notices: [budgetNotice] } : {}) }, null, 2));
} else {
console.log(`[drain] extracted ${result.extracted} atom(s) across ${result.batches} batch(es); ${result.remaining ?? '?'} remaining (stopped: ${result.stopped})`);
}
// null remaining = the final count query failed; do not report success.
if (result.stopped === 'drained' && result.remaining === 0) return;
- process.stderr.write(
- `[drain] stopped: ${result.stopped}; ${result.remaining ?? '?'} page(s) remaining. ` +
- `Rerun: ${drainCommand(opts)}\n`,
+ process.stderr.write(budgetNotice
+ ? `[drain] stopped: budget; spent ${usd(result.spent_usd)} of the ${usd(result.budget_usd)} per-run cap (cycle.extract_atoms.budget_usd); ` +
+ `${result.remaining ?? '?'} page(s) remaining. Rerun: ${drainCommand(opts)}, or raise the cap: gbrain config set cycle.extract_atoms.budget_usd <usd>\n`
+ : `[drain] stopped: ${result.stopped}; ${result.remaining ?? '?'} page(s) remaining. ` +
+ `Rerun: ${drainCommand(opts)}\n`,
);
process.exit(EXIT_DRAIN_INCOMPLETE);
}
diff --git a/src/core/cycle/extract-atoms-budget-notice.ts b/src/core/cycle/extract-atoms-budget-notice.ts
new file mode 100644
index 0000000000..b52c881120
--- /dev/null
+++ b/src/core/cycle/extract-atoms-budget-notice.ts
@@ -0,0 +1,18 @@
+/**
+ * #6425: the notice a `budget`-stopped atom drain carries (`gbrain dream --drain --json`):
+ * what the attempt spent, its per-run cap, the pages left, and the paid fix that raises the cap.
+ */
+import { cliRenderContext, renderNotice, type RenderedNotice } from '../agent-output.ts';
+
+export const usd = (n: number | undefined): string => n === undefined ? '$?' : `$${Number(n.toFixed(4))}`;
+
+export function drainBudgetNotice(result: { spent_usd?: number; budget_usd?: number; remaining: number | null }): RenderedNotice {
+ return renderNotice({
+ code: 'atom_drain_budget', kind: 'info',
+ why: `The atom drain stopped at its per-run spending cap: it spent ${usd(result.spent_usd)} of ${usd(result.budget_usd)} (cycle.extract_atoms.budget_usd) and ${result.remaining ?? 'an unknown number of'} page(s) still need atoms. Rerun the drain to continue under the same cap, or raise the cap.`,
+ fix: { argv: ['gbrain', 'config', 'set', 'cycle.extract_atoms.budget_usd', '<USD>'], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ inputs: [{ name: 'USD', how: `Ask the user the most one atom drain or cycle may spend on extraction (the cap is ${usd(result.budget_usd)} now).` }],
+ why: 'Raises the per-run atom extraction cap; every later drain and cycle may spend up to it on model calls.',
+ verify: { argv: ['gbrain', 'config', 'get', 'cycle.extract_atoms.budget_usd'] } },
+ }, cliRenderContext());
+}
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.ts
index 5dc2423f28..a6a0373ddf 100644
--- a/src/core/cycle/extract-atoms-drain.ts
+++ b/src/core/cycle/extract-atoms-drain.ts
@@ -100,6 +100,10 @@ export interface ExtractAtomsDrainDeps {
*
* `signal` is the hard stop and `stopSignal` the soft one (see the module
* header); the batch hands both to `runPhaseExtractAtoms`.
+ *
+ * #6425: `budgetSkipped` counts items the batch skipped because the
+ * attempt's per-run cap was spent, with `budget` the spend and the cap. The
+ * attempt shares one tracker across batches, so the drain stops `budget`.
*/
runBatch: (signals: { signal: AbortSignal; stopSignal: AbortSignal }) => Promise<{
extracted: number;
@@ -108,6 +112,8 @@ export interface ExtractAtomsDrainDeps {
failureCount?: number;
firstError?: string;
failures?: Array<{ source: string; reason: string }>;
+ budgetSkipped?: number;
+ budget?: { spentUsd: number; capUsd: number };
}>;
/**
* Count remaining eligible-but-unextracted pages, or null on query error.
@@ -138,14 +144,14 @@ export interface ExtractAtomsDrainOpts {
}
/**
- * Why a drain stopped. `window`/`no_progress`/`max_batches` are soft stops
- * after a final recount; `deadline` (job deadline), `lock_lost` (cycle lock
+ * Why a drain stopped. `window`/`no_progress`/`max_batches`/`budget` are soft
+ * stops after a final recount (`budget`: the attempt's per-run cap is spent); `deadline` (job deadline), `lock_lost` (cycle lock
* lease lost) and `aborted` (job cancelled or shutting down) are hard stops
* whose `remaining` is the last count taken before the stop.
*/
export type DrainStop =
| 'drained' | 'window' | 'deadline' | 'lock_lost' | 'aborted'
- | 'no_progress' | 'max_batches' | 'provider_failure';
+ | 'no_progress' | 'max_batches' | 'provider_failure' | 'budget';
export const DRAIN_COUNT_TIMEOUT_MS = 60_000;
@@ -204,6 +210,9 @@ export interface ExtractAtomsDrainResult {
* reported one (`source: reason`), or null for a clean run.
*/
last_error: string | null;
+ /** #6425: on a `budget` stop, the attempt's spend and its per-run cap (`cycle.extract_atoms.budget_usd`). */
+ spent_usd?: number;
+ budget_usd?: number;
}
/**
@@ -245,6 +254,7 @@ export async function runExtractAtomsDrain(
let lastError: string | null = null;
let lastCount: number | null = null;
let lockSignal: AbortSignal | null = null;
+ let budget: { spentUsd: number; capUsd: number } | undefined;
const result = (stopped: DrainStop, remaining: number | null): ExtractAtomsDrainResult => ({
phase: 'extract_atoms',
status: providerFailure ? 'provider_failure' : 'ok',
@@ -257,6 +267,7 @@ export async function runExtractAtomsDrain(
failures,
omitted_failure_count: failureCount - failures.length,
last_error: lastError,
+ ...(stopped === 'budget' && budget ? { spent_usd: budget.spentUsd, budget_usd: budget.capUsd } : {}),
});
try {
return await deps.withLock(async (signal) => {
@@ -366,6 +377,13 @@ export async function runExtractAtomsDrain(
break;
}
+ // #6425: the attempt's one BudgetTracker is spent, so no later batch can progress.
+ if ((r.budgetSkipped ?? 0) > 0) {
+ budget = r.budget;
+ stopped = 'budget';
+ break;
+ }
+
// Stop if a batch made zero forward progress — extraction is failing or
// everything left is ineligible (e.g. all skipped). Prevents a hot loop
// that spends budget without draining.
@@ -513,6 +531,8 @@ export async function runExtractAtomsDrainForSource(
providerFailure: failures.length > 0 && itemsSucceeded === 0,
failureCount: failures.length,
failures: typedFailures,
+ budgetSkipped: Number(d.pages_skipped_budget ?? 0) + Number(d.transcripts_skipped_budget ?? 0),
+ budget: { spentUsd: Number(d.estimated_spend_usd ?? 0), capUsd: Number(d.budget_usd ?? 0) },
};
},
countRemaining: (signal) => countExtractAtomsBacklog(engine, extractionSourceId, { signal }),
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index b1a5235edc..5302ca6a70 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -468,6 +468,7 @@ export interface NoticeEntry {
/** Notice codes. Mute (`gbrain notices mute`, `mute_notice`) accepts only coaching/info codes. */
export const NOTICE_CODES = {
+ atom_drain_budget: { kind: 'info', summary: 'An atom drain (`gbrain dream --drain`) stopped at its per-run spending cap (`cycle.extract_atoms.budget_usd`): the notice names the spend, the cap and the pages left; the fix raises the cap (paid, ask first).' },
backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },
empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },
first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },
diff --git a/test/dream-drain-failure-summary.serial.test.ts b/test/dream-drain-failure-summary.serial.test.ts
index 3ff5b9e0fb..ce30af4d6b 100644
--- a/test/dream-drain-failure-summary.serial.test.ts
+++ b/test/dream-drain-failure-summary.serial.test.ts
@@ -237,3 +237,20 @@ describe('dream --drain stop contract (#5809)', () => {
});
});
+
+describe('dream --drain budget stop (#6425)', () => {
+ test('names the spend, the cap and the raise-cap command; --json carries a structured notice', async () => {
+ nextResult = baseResult({ stopped: 'budget', remaining: 2, batches: 2, spent_usd: 0.0151, budget_usd: 0.03 });
+ const human = await runDrainCaptured([]);
+ expect(human.exitCode).toBe(11);
+ expect(human.stderr).toContain('[drain] stopped: budget; spent $0.0151 of the $0.03 per-run cap (cycle.extract_atoms.budget_usd); 2 page(s) remaining. '
+ + 'Rerun: gbrain dream --drain --window 300, or raise the cap: gbrain config set cycle.extract_atoms.budget_usd <usd>');
+ const json = await runDrainCaptured(['--json']);
+ const payload = JSON.parse(json.stdout.find(l => l.trim().startsWith('{'))!);
+ expect(payload).toMatchObject({ stopped: 'budget', spent_usd: 0.0151, budget_usd: 0.03, resume_command: 'gbrain dream --drain --window 300' });
+ expect(payload.notices).toEqual([expect.objectContaining({ code: 'atom_drain_budget', kind: 'info', contract_version: 1,
+ fix: expect.objectContaining({ argv: ['gbrain', 'config', 'set', 'cycle.extract_atoms.budget_usd', '<USD>'], consent: ['paid'], next: 'ask_user',
+ verify: { argv: ['gbrain', 'config', 'get', 'cycle.extract_atoms.budget_usd'] } }) })]);
+ expect(payload.notices[0].why).toContain('$0.0151 of $0.03');
+ });
+});
diff --git a/test/extract-atoms-drain-attempt.test.ts b/test/extract-atoms-drain-attempt.test.ts
index 25338d6968..2b4fce4524 100644
--- a/test/extract-atoms-drain-attempt.test.ts
+++ b/test/extract-atoms-drain-attempt.test.ts
@@ -45,7 +45,11 @@ test('a three-batch drain attempt stops at its per-run cap (one BudgetTracker pe
expect(calls).toBe(1);
expect(result.extracted).toBe(1);
expect(result.remaining).toBe(2);
- expect(result.stopped).toBe('no_progress');
+ // #6425: the per-run cap stopped the attempt, not an empty or failing backlog.
+ expect(result.stopped).toBe('budget');
+ expect(result.budget_usd).toBe(0.03);
+ expect(result.spent_usd).toBeGreaterThan(0);
+ expect(result.batches).toBe(2);
});
} finally { __setChatTransportForTests(null); }
expect(await engine.executeRaw("SELECT slug FROM pages WHERE type='atom' AND deleted_at IS NULL")).toHaveLength(1);
diff --git a/test/extract-atoms-drain-stops.test.ts b/test/extract-atoms-drain-stops.test.ts
index 128956c60a..bd24ebf7da 100644
--- a/test/extract-atoms-drain-stops.test.ts
+++ b/test/extract-atoms-drain-stops.test.ts
@@ -223,3 +223,34 @@ describe('the drain window on the real phase', () => {
expect(await engine.executeRaw(`SELECT id FROM gbrain_cycle_locks`)).toEqual([]);
}, 30_000);
});
+
+describe('#6425: budget stop', () => {
+ it('a batch that budget-skipped items stops with budget, spent and cap, after one batch', async () => {
+ let batches = 0;
+ let counts = 0;
+ const result = await runExtractAtomsDrain({
+ withLock: (work) => work(new AbortController().signal),
+ runBatch: async () => { batches++; return { extracted: 0, skipped: 0, budgetSkipped: 2, budget: { spentUsd: 0.31, capUsd: 0.3 } }; },
+ countRemaining: async () => { counts++; return 5; },
+ now: Date.now,
+ }, { windowMs: 60_000, maxBatches: 10 });
+ expect(batches).toBe(1);
+ expect(result.stopped).toBe('budget');
+ expect(result.status).toBe('ok');
+ expect(result.spent_usd).toBe(0.31);
+ expect(result.budget_usd).toBe(0.3);
+ expect(result.remaining).toBe(5);
+ expect(counts).toBe(2);
+ });
+
+ it('a drained final recount still reports drained over a budget stop', async () => {
+ let remaining = 1;
+ const result = await runExtractAtomsDrain({
+ withLock: (work) => work(new AbortController().signal),
+ runBatch: async () => { remaining = 0; return { extracted: 1, skipped: 0, budgetSkipped: 1, budget: { spentUsd: 0.3, capUsd: 0.3 } }; },
+ countRemaining: async () => remaining,
+ now: Date.now,
+ }, { windowMs: 60_000, maxBatches: 10 });
+ expect(result.stopped).toBe('drained');
+ });
+});