Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract-atoms): drain stops no_progress when a batch only re-skips items
garrytan7ab712a3f9c6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c51f34fc79..c67d52ff7e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,10 +16,13 @@ identifiers and attribution are available in the pre-removal Git revision**A source with automatic sync off now walks forward through its pages on a database whose DateStyle is not ISO.** The per-source maintenance window saved its cursor in the session's date style. Under a day-first style such as `German, DMY` or `SQL, DMY`, a cursor dated after the 12th of a month was not a date the cycle handler could read, so it dropped the cursor and the next cycle started again from the source's oldest pages; a source over 2,000 pages never got past its first window. The cursor is now always written as a UTC ISO timestamp with microseconds. A source holding a cursor in the old form may start from its oldest pages one last time; from then on it advances. Reported by @javieraldape (#8771).+**`gbrain dream --drain` stops as no progress when its batches only skip items the backlog keeps counting.** The drain checked for no progress only after a batch that extracted nothing and skipped nothing. A page the phase skips on every batch while the backlog still counts it kept that check from ever running, so the drain ran all 1,000 batches, held the cycle lock for minutes and ended `max_batches` with exit 11, which tells the caller to rerun a stop a rerun cannot clear. A batch that extracts nothing now always rechecks the backlog: when it did not shrink, the drain stops `no_progress` (`atom_drain_no_progress`, exit 1), and skips that do shrink it keep draining. Reported by @h6y3 (#8445).+### Itemized changes- `src/core/cycle/unindexed-files.ts`: `details.complete` also requires `errors.length === 0`. Test: `test/unindexed-files.test.ts` (a source whose `.git/HEAD` is unreadable: phase `warn`, one error, `complete: false`).- `src/core/cycle/source-window.ts`: the listing instant and the last page's `updated_at` are formatted with `to_char(... AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`. Test: `test/sync-disabled-cycle-window.test.ts` (the real queued handler under `German, DMY` advances window by window; `German`, `SQL` and `Postgres` styles under a +05:45 time zone give ISO UTC cursors with microseconds and the same windows), now also run on Postgres by `test/e2e/sync-disabled-cycle-window-postgres.test.ts`.+- `src/core/cycle/extract-atoms-drain.ts`: the no-progress recount runs after every batch with `extracted === 0`, not only when `skipped` is also 0. Test: `test/extract-atoms-drain.test.ts` (a skip-only batch over a flat backlog stops `no_progress` after one batch; skip-only batches that shrink the backlog drain).## [0.60.620.0] - 2026-11-09diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex 7b8a44873a..82bbb5d6af 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -17,7 +17,7 @@ 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|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). #7514: a record whose write did not commit also carries `request_id` and `code`; the adapter leaves such items out of `providerFailure` and its class (they never reached a provider), and a batch whose only progress is write-failure strikes (`writeStrikes`) is not `no_progress`, so the drain moves on and the strikes reach their hold in the same window. A `provider_failure` result carries `provider_failure_class` (`batchProviderFailureClass`: the phase's `aborted_global_error` halt class `auth`/`billing`/`model_not_found`/`rate_limit`, `content_block` when every failure is a provider content block, else `transient`). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline`, on a provider failure `drainOutcome` marks not retryable, 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). #7514: a record whose write did not commit also carries `request_id` and `code`; the adapter leaves such items out of `providerFailure` and its class (they never reached a provider), a batch that extracted nothing (whatever it skipped, #8445) is recounted and stops `no_progress` when the backlog did not shrink, and a batch whose only progress is write-failure strikes (`writeStrikes`) is not `no_progress`, so the drain moves on and the strikes reach their hold in the same window. A `provider_failure` result carries `provider_failure_class` (`batchProviderFailureClass`: the phase's `aborted_global_error` halt class `auth`/`billing`/`model_not_found`/`rate_limit`, `content_block` when every failure is a provider content block, else `transient`). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline`, on a provider failure `drainOutcome` marks not retryable, 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-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`.diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.tsindex 9387cb2403..d0374007a5 100644--- a/src/core/cycle/extract-atoms-drain.ts+++ b/src/core/cycle/extract-atoms-drain.ts@@ -420,7 +420,11 @@ export async function runExtractAtomsDrain(// #2144: a zero-ATOM batch can still be progress — tombstoned// zero-yield pages shrink the backlog without producing atoms. Only// stop when the backlog count genuinely didn't move.- if (r.extracted === 0 && r.skipped === 0) {+ //+ // #8445: a skip-only batch gets the same recount. An item the phase+ // skips but the backlog still counts re-skipped every batch, so the+ // drain ran to max_batches holding the cycle lock.+ if (r.extracted === 0) {const after = await count();if (hard.signal.aborted) break;if (after !== null) lastCount = after;diff --git a/test/extract-atoms-drain.test.ts b/test/extract-atoms-drain.test.tsindex 1ca442dad5..2cc3e5e330 100644--- a/test/extract-atoms-drain.test.ts+++ b/test/extract-atoms-drain.test.ts@@ -285,4 +285,33 @@ describe('#2144: zero-yield tombstone progress semantics', () => {expect(result.remaining).toBe(5);expect(batches).toBe(1);});+ it('#8445: stops no_progress when a batch only skips items the backlog keeps counting', async () => {+ let batches = 0;+ const result = await runExtractAtomsDrain(+ {+ withLock: passThroughLock,+ countRemaining: async () => 1,+ runBatch: async () => { batches++; return { extracted: 0, skipped: 1 }; },+ now: () => 0,+ },+ { windowMs: 1_000_000, maxBatches: 20 },+ );+ expect(result).toMatchObject({ stopped: 'no_progress', batches: 1, skipped: 1, remaining: 1 });+ expect(batches).toBe(1);+ });++ it('#8445: a skip-only batch that shrinks the backlog keeps draining', async () => {+ let batches = 0;+ const result = await runExtractAtomsDrain(+ {+ withLock: passThroughLock,+ countRemaining: async () => Math.max(0, 3 - batches),+ runBatch: async () => { batches++; return { extracted: 0, skipped: 2 }; },+ now: () => 0,+ },+ { windowMs: 1_000_000, maxBatches: 20 },+ );+ expect(result).toMatchObject({ stopped: 'drained', batches: 3, skipped: 6, remaining: 0 });+ expect(batches).toBe(3);+ });});