Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(atoms): connector-safe auto-drain: structural refusal, fair attempt-counted dispatch, one budget per attempt, opt-in connector pages (#5856)
garrytan17cc5c51f333
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex db2a4c81b8..6f5e97a527 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -62,7 +62,9 @@ The USD-limit knobs accept `off`, `unlimited`, or `none` (case-insensitive) to m| `migrate embeddings` consent gate | — (plan + estimate before provider migration) | — | TTY y/N prompt / non-TTY refuse + exit 2 | `--yes` | estimate marked informational, but **still prompts** (guards a destructive schema rebuild, not just spend) || `enrich` / `onboard --auto` | `--max-usd` (per-call) | — | refuse without a cap (non-TTY) | `--max-usd off` | runs uncapped (still ledgered) || Image-OCR per-run ceiling | `embedding_image_ocr_max_images` / `embedding_image_ocr_max_usd` | `200` images / `$1.00` (estimated) | skips OCR over-cap (import continues; skips counted in `ocr_skipped_budget`, surfaced by doctor `ocr_health`) | `0` disables that cap | **not** bypassed (per-run cap, not a tracker gate) |-| Dream `extract_atoms` phase budget | `cycle.extract_atoms.budget_usd` | `0.30` | caps the phase's budget tracker | — | **not** consulted (phase budget enforces regardless) |+| Dream `extract_atoms` phase budget | `cycle.extract_atoms.budget_usd` | `0.30` | caps the phase's budget tracker (one tracker per drain attempt, across all its batches) | — | **not** consulted (phase budget enforces regardless) |+| Atom auto-drain daily cap | `autopilot.auto_drain.max_usd_per_day` | `2.00` | daily cap on drain **attempts** (`floor(max / 0.30)` = 6), not a dollar ledger | `gbrain config set autopilot.auto_drain.enabled false` | **not** consulted |+| Connector email/meeting atoms | `cycle.extract_atoms.connector_pages` | `false` (opt-in) | Gmail/Calendar `email`/`meeting` pages are skipped by atom extraction | leave unset / `false` | **not** consulted || Dream `synthesize` per-run budget | `dream.synthesize.budget_usd` | `5` | defers the transcript and the rest of the run before submission (estimate: prompt size + child output cap, x `max_turns` in agentic mode) | `unlimited` (`0` = submit nothing) | **not** consulted || Dream `synthesize` daily submission cap | `dream.synthesize.max_submissions_per_source_per_day` | `0` (off) | skips whole files; a failed count query submits nothing that run | `0` | **not** consulted || Dream `BudgetMeter` phases (auto_think, drift, propose/grade takes, calibration) | `dream.auto_think.budget`, `dream.drift.budget`, `cycle.<phase>.budget_usd` | per phase | refuses the next submit past the cap | `unlimited` (`0` = spend nothing) | **not** consulted |@@ -115,6 +117,42 @@ estimate is `delta + stale backlog`, labeled as such.version drift (forces a full re-chunk), or git being unavailable. Unchanged filesstill skip via `content_hash` at execution, so the ceiling over-states real spend.+### Atom extraction: auto-drain cap and connector pages++**Say to your agent:** *"Extract atoms from my Gmail and Calendar pages too"* or+*"Stop spending on automatic atom extraction."*++When the active schema pack does not run `extract_atoms` in the routine cycle,+autopilot (Postgres brains) submits a bounded `extract-atoms-drain` job per+source with a backlog. Each drain **attempt** runs under one BudgetTracker+capped at `cycle.extract_atoms.budget_usd` ($0.30 by default), shared by all of+its batches. The daily cap `autopilot.auto_drain.max_usd_per_day` ($2.00) is a+count of attempts at that per-attempt estimate (6 a day), so a retried job+uses one slot per attempt. A job refused before any model call (no active+canonical owner on this host, untrusted caller) dead-letters once with+`structural_refusal:` and uses no slot; autopilot also skips a source whose+writer would refuse, and logs why. Checkout-backed and connector sources take+turns for the daily slots. With a model the tracker cannot price, the dollar+limit is not enforced (see above); only the attempt count bounds the drain.++Connector pages are opt-in. Gmail threads (`email`) and Calendar events+(`meeting`) from a Google or GitHub connector source are skipped by atom+discovery, the backlog count, the routine cycle, `gbrain dream --drain` and+the auto-drain until you turn them on:++```bash+gbrain config set cycle.extract_atoms.connector_pages true # opt in+gbrain config set cycle.extract_atoms.connector_pages false # opt out again+gbrain config set autopilot.auto_drain.enabled false # stop all automatic atom drains+```++What leaves the machine when you opt in: the page text of each extracted email+thread or calendar event (message bodies, subjects, participants as rendered on+the page, up to `cycle.extract_atoms.max_input_chars`) is sent to the+configured `extract_atoms` chat model (`models.dream.extract_atoms`, a+utility-tier model by default), under the caps above. Atoms already extracted+stay; turning the setting off only stops new extraction.+## Notes & limits- **Pre-pull window:** the gate fetches before estimating, so it prices what the rundiff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.tsindex 2d73828856..08aa6fea46 100644--- a/src/commands/autopilot-dispatch.ts+++ b/src/commands/autopilot-dispatch.ts@@ -364,127 +364,174 @@ async function dispatchConnectorFreshnessSync(async function dispatchAutoDrain(engine: BrainEngine,queue: MinionQueue,- { timeoutMs, jsonMode }: { timeoutMs: number; jsonMode: boolean },+ opts: { timeoutMs: number; jsonMode: boolean },+): Promise<void> {+ // Postgres-only — PGLite has no multi-process worker to run the job.+ if (engine.kind === 'postgres') {+ try {+ if ((await engine.getConfig('autopilot.auto_drain.enabled')) !== 'false') await submitAutoDrains(engine, queue, opts);+ } catch (e) {+ logError('dispatch.auto-drain-gate', e);+ }+ }+}++/** #5856: the source kind the auto-drain offers the next free slot to; alternates across ticks and days. */+export const AUTO_DRAIN_NEXT_KIND_KEY = 'autopilot.auto_drain.next_kind';+type AutoDrainKind = 'checkout' | 'connector';++/**+ * #5856: units of today's drain jobs against the daily cap. Every started+ * attempt costs one (a waiting job one), so retried provider failures still+ * count; a job whose only attempt was a structural refusal spent nothing and+ * costs none.+ */+async function autoDrainUnitsToday(engine: BrainEngine, utcDay: string): Promise<number> {+ const { STRUCTURAL_REFUSAL_PREFIX } = await import('../core/cycle/extract-atoms-drain.ts');+ const rows = await engine.executeRaw<{ cnt: number }>(+ `SELECT COALESCE(sum(CASE WHEN status = 'dead' AND attempts_started <= 1+ AND left(COALESCE(error_text, ''), length($2)) = $2 THEN 0 ELSE GREATEST(attempts_started, 1) END), 0)::int AS cnt+ FROM minion_jobs WHERE name = 'extract-atoms-drain' AND created_at >= $1::timestamptz`,+ [`${utcDay}T00:00:00Z`, STRUCTURAL_REFUSAL_PREFIX],+ );+ return Number(rows[0]?.cnt ?? 0);+}++/**+ * The auto-drain submission pass behind dispatchAutoDrain's Postgres and+ * `autopilot.auto_drain.enabled` gates; exported so tests drive it on either engine. `now` is the clock seam for+ * the UTC-day slot.+ */+export async function submitAutoDrains(+ engine: BrainEngine,+ queue: MinionQueue,+ { timeoutMs, jsonMode, now = Date.now }: { timeoutMs: number; jsonMode: boolean; now?: () => number },): Promise<void> {// ── #1685 GAP D: per-source extract_atoms auto-drain ───────────────// The silent-backlog incident: a pack that doesn't declare extract_atoms// never runs the phase in the routine cycle, so the atom backlog grows// invisibly. Auto-submit a bounded, PROTECTED drain per source when the// backlog exceeds the threshold AND the active pack doesn't declare the- // phase. Default-ON, daily-spend-capped, time-sloted key so a new slot- // opens each UTC day (CODEX #1/#2/#3, DECISION 3C). Postgres-only —- // PGLite has no multi-process worker to run the job.- if (engine.kind === 'postgres') {- try {- const enabled = (await engine.getConfig('autopilot.auto_drain.enabled')) !== 'false';- if (enabled) {- const { packDeclaresPhase } = await import('../core/cycle.ts');- // packDeclaresPhase reads the active pack (brain-wide, not- // per-source). If the pack declares extract_atoms the routine- // cycle already drains it for every source — nothing to do.- const declares = await packDeclaresPhase(engine, 'extract_atoms');- if (!declares) {- const parsePosInt = (v: string | null, d: number): number => {- if (v == null) return d;- const n = parseInt(v, 10);- return Number.isFinite(n) && n > 0 ? n : d;- };- const parseNonNegFloat = (v: string | null, d: number): number => {- if (v == null) return d;- const n = parseFloat(v);- return Number.isFinite(n) && n >= 0 ? n : d;- };- const threshold = parsePosInt(await engine.getConfig('autopilot.auto_drain.threshold'), 25);- const windowSeconds = parsePosInt(await engine.getConfig('autopilot.auto_drain.window_seconds'), 120);- const maxUsdPerDay = parseNonNegFloat(await engine.getConfig('autopilot.auto_drain.max_usd_per_day'), 2.0);- // Each drain run is BudgetTracker-capped at ~$0.30; bound the- // brain-wide daily count instead of a real-time spend ledger.- const PER_RUN_USD = 0.3;- const maxJobsToday = Math.max(0, Math.floor(maxUsdPerDay / PER_RUN_USD));- const utcDay = new Date().toISOString().slice(0, 10);+ // phase. Default-ON, daily-capped, time-sloted key so a new slot+ // opens each UTC day (CODEX #1/#2/#3, DECISION 3C).+ const { packDeclaresPhase } = await import('../core/cycle.ts');+ // packDeclaresPhase reads the active pack (brain-wide, not+ // per-source). If the pack declares extract_atoms the routine+ // cycle already drains it for every source — nothing to do.+ if (await packDeclaresPhase(engine, 'extract_atoms')) return;+ const parsePosInt = (v: string | null, d: number): number => {+ if (v == null) return d;+ const n = parseInt(v, 10);+ return Number.isFinite(n) && n > 0 ? n : d;+ };+ const parseNonNegFloat = (v: string | null, d: number): number => {+ if (v == null) return d;+ const n = parseFloat(v);+ return Number.isFinite(n) && n >= 0 ? n : d;+ };+ const threshold = parsePosInt(await engine.getConfig('autopilot.auto_drain.threshold'), 25);+ const windowSeconds = parsePosInt(await engine.getConfig('autopilot.auto_drain.window_seconds'), 120);+ const maxUsdPerDay = parseNonNegFloat(await engine.getConfig('autopilot.auto_drain.max_usd_per_day'), 2.0);+ // Each drain attempt runs under one BudgetTracker capped at ~$0.30+ // (cycle.extract_atoms.budget_usd); bound the brain-wide daily attempt+ // count instead of a real-time spend ledger.+ const PER_RUN_USD = 0.3;+ const maxJobsToday = Math.max(0, Math.floor(maxUsdPerDay / PER_RUN_USD));+ const utcDay = new Date(now()).toISOString().slice(0, 10);- let submittedToday = 0;- try {- const rows = await engine.executeRaw<{ cnt: number }>(- `SELECT count(*)::int AS cnt FROM minion_jobs WHERE name = 'extract-atoms-drain' AND created_at >= $1::timestamptz`,- [`${utcDay}T00:00:00Z`],- );- submittedToday = rows[0]?.cnt ?? 0;- } catch {- // count is best-effort; treat as 0 (cap still bounds submits this tick).- }+ let submittedToday = 0;+ try {+ submittedToday = await autoDrainUnitsToday(engine, utcDay);+ } catch {+ // count is best-effort; treat as 0 (cap still bounds submits this tick).+ }+ if (submittedToday >= maxJobsToday) return;- if (submittedToday < maxJobsToday) {- const { countExtractAtomsBacklog } = await import('../core/cycle/extract-atoms.ts');- const sources = await loadAllSources(engine);- for (const src of sources) {- if (submittedToday >= maxJobsToday) break; // brain-wide daily cap (fairness)- if (!src.local_path) continue;- // Same unavailable-path skip (relative / missing on this- // machine) as the freshness loop above, same --json shape.- const skipWarn = sourceLocalPathSkipWarning(src.id, src.local_path, undefined, src.config);- if (skipWarn) {- process.stderr.write(- (jsonMode ? JSON.stringify({ event: 'freshness_source_path_skipped', source_id: src.id, reason: skipWarn }) : skipWarn) + '\n',- );- continue;- }- const backlog = await countExtractAtomsBacklog(engine, src.id);- if (backlog === null || backlog <= threshold) continue;- // Time-sloted key (CODEX #2): a static key would block the- // source FOREVER once the first job completes. A new UTC-day- // slot reopens it each day.- const idemKey = `autopilot-extract-atoms-drain:${src.id}:${utcDay}`;- try {- // CODEX (impl review #4): DO NOT use maxWaiting here — it- // coalesces by (name, queue), NOT by source, so source B's- // submit would return source A's waiting row, B would never- // queue, and the cap counter would over-count. The per-source- // idempotency key is the correct dedup. Pre-check it so we- // submit + count only genuinely-new sources (queue.add returns- // the existing row on an idempotency hit with no created flag,- // which would otherwise over-count the daily cap). The- // single-instance autopilot lock + the unique idempotency- // index make this pre-check race-free.- const dupe = await engine.executeRaw<{ one: number }>(- `SELECT 1 AS one FROM minion_jobs WHERE idempotency_key = $1 LIMIT 1`,- [idemKey],- );- if (dupe.length > 0) continue; // already queued/drained for this source today- const job = await queue.add(- 'extract-atoms-drain',- { sourceId: src.id, window: windowSeconds, repoPath: src.local_path },- {- queue: 'default',- idempotency_key: idemKey,- // issue #3218: the handler now throws on an- // all-provider-failed batch, so give the queue's- // backoff a chance (was 1 — dead-lettered instantly).- max_attempts: 3,- timeout_ms: timeoutMs,- },- { allowProtectedSubmit: true },- );- submittedToday++;- if (jsonMode) {- process.stderr.write(JSON.stringify({- event: 'dispatched', job_id: job.id, mode: 'auto-drain',- source_id: src.id, backlog,- }) + '\n');- } else {- console.log(`[dispatch] job #${job.id} extract-atoms-drain (auto-drain: ${src.id}; backlog=${backlog})`);- }- } catch (e) {- logError('dispatch.auto-drain', e);- }- }- }- }+ const { countExtractAtomsBacklog } = await import('../core/cycle/extract-atoms.ts');+ const { atomDrainOwnerRefusal } = await import('../core/persistence/atom-maintenance.ts');+ const skipped = (src: SourceRow, event: string, reason: string) => process.stderr.write(+ (jsonMode ? JSON.stringify({ event, source_id: src.id, reason }) : reason) + '\n');+ // #5856 fairness: checkout-backed and connector sources alternate for the+ // daily slots, starting with the kind the persisted pointer names, so a+ // large connector backlog cannot starve a git source's atoms (or the reverse).+ const byKind: Record<AutoDrainKind, SourceRow[]> = { checkout: [], connector: [] };+ for (const src of await loadAllSources(engine)) {+ byKind[isConnectorSourceKind(parseSourceConfig(src.config).kind) ? 'connector' : 'checkout'].push(src);+ }+ const pointer: AutoDrainKind = (await engine.getConfig(AUTO_DRAIN_NEXT_KIND_KEY)) === 'connector' ? 'connector' : 'checkout';+ let next = pointer;+ while (submittedToday < maxJobsToday) { // brain-wide daily cap (fairness)+ const kind: AutoDrainKind = byKind[next].length ? next : next === 'checkout' ? 'connector' : 'checkout';+ const src = byKind[kind].shift();+ if (!src) break;+ // A connector source syncs from its provider: its local_path is a state+ // directory, so it needs none and its job carries no repoPath.+ if (kind === 'checkout') {+ if (!src.local_path) continue;+ // Same unavailable-path skip (relative / missing on this+ // machine) as the freshness loop above, same --json shape.+ const skipWarn = sourceLocalPathSkipWarning(src.id, src.local_path, undefined, src.config);+ if (skipWarn) { skipped(src, 'freshness_source_path_skipped', skipWarn); continue; }+ }+ // Time-sloted key (CODEX #2): a static key would block the+ // source FOREVER once the first job completes. A new UTC-day+ // slot reopens it each day; it also bounds a structural refusal+ // to one dead job per source per day.+ const idemKey = `autopilot-extract-atoms-drain:${src.id}:${utcDay}`;+ try {+ // CODEX (impl review #4): DO NOT use maxWaiting here — it+ // coalesces by (name, queue), NOT by source, so source B's+ // submit would return source A's waiting row, B would never+ // queue, and the cap counter would over-count. The per-source+ // idempotency key is the correct dedup. Pre-check it so we+ // submit + count only genuinely-new sources (queue.add returns+ // the existing row on an idempotency hit with no created flag,+ // which would otherwise over-count the daily cap). The+ // single-instance autopilot lock + the unique idempotency+ // index make this pre-check race-free.+ const dupe = await engine.executeRaw<{ one: number }>(+ `SELECT 1 AS one FROM minion_jobs WHERE idempotency_key = $1 LIMIT 1`,+ [idemKey],+ );+ if (dupe.length > 0) continue; // already queued/drained for this source today+ const backlog = await countExtractAtomsBacklog(engine, src.id);+ if (backlog === null || backlog <= threshold) continue;+ // #5856: the drain's writer preflight would refuse this source (no+ // active local owner); submitting it would only dead-letter.+ const refusal = await atomDrainOwnerRefusal(engine, src.id);+ if (refusal) {+ skipped(src, 'auto_drain_source_skipped', `[autopilot] skipping atom auto-drain for '${src.id}': ${refusal}`);+ continue;+ }+ const job = await queue.add(+ 'extract-atoms-drain',+ { sourceId: src.id, window: windowSeconds, ...(kind === 'checkout' ? { repoPath: src.local_path } : {}) },+ {+ queue: 'default',+ idempotency_key: idemKey,+ // issue #3218: the handler now throws on an+ // all-provider-failed batch, so give the queue's+ // backoff a chance (was 1 — dead-lettered instantly).+ max_attempts: 3,+ timeout_ms: timeoutMs,+ },+ { allowProtectedSubmit: true },+ );+ submittedToday++;+ next = kind === 'checkout' ? 'connector' : 'checkout';+ if (jsonMode) {+ process.stderr.write(JSON.stringify({+ event: 'dispatched', job_id: job.id, mode: 'auto-drain',+ source_id: src.id, backlog,+ }) + '\n');+ } else {+ console.log(`[dispatch] job #${job.id} extract-atoms-drain (auto-drain: ${src.id}; backlog=${backlog})`);}} catch (e) {- logError('dispatch.auto-drain-gate', e);+ logError('dispatch.auto-drain', e);}}+ if (next !== pointer) await engine.setConfig(AUTO_DRAIN_NEXT_KIND_KEY, next);}/** The remediation plan autopilot routes on (brain score + doctor/onboard recommendations). */diff --git a/src/core/cycle/connector-atoms.ts b/src/core/cycle/connector-atoms.tsnew file mode 100644index 0000000000..0511e79382--- /dev/null+++ b/src/core/cycle/connector-atoms.ts@@ -0,0 +1,25 @@+/**+ * #5856: atom extraction of connector `email` and `meeting` pages is opt-in.+ * While `cycle.extract_atoms.connector_pages` is off (the default), atom+ * discovery and the backlog count skip those pages of Google and GitHub+ * connector sources, so no routine cycle, drain or autopilot auto-drain sends+ * their bodies to the chat model. Other page types of a connector source, and+ * every page of a checkout-backed source, are unaffected.+ */+import type { BrainEngine } from '../engine.ts';+import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';++export const CONNECTOR_ATOM_PAGES_KEY = 'cycle.extract_atoms.connector_pages';+export const CONNECTOR_ATOM_PAGE_TYPES = ['email', 'meeting'] as const;++export async function connectorAtomPagesEnabled(engine: BrainEngine): Promise<boolean> {+ return /^(true|1|on|yes)$/i.test((await engine.getConfig(CONNECTOR_ATOM_PAGES_KEY).catch(() => null)) ?? '');+}++/** The discovery/backlog predicate over `pages p`: empty when opted in, else the connector email/meeting exclusion. */+export async function connectorAtomExclusionSql(engine: BrainEngine): Promise<string> {+ if (await connectorAtomPagesEnabled(engine)) return '';+ const list = (values: readonly string[]) => values.map(v => `'${v}'`).join(',');+ return `AND NOT (p.type IN (${list(CONNECTOR_ATOM_PAGE_TYPES)}) AND EXISTS (SELECT 1 FROM sources cs+ WHERE cs.id = p.source_id AND cs.config->>'kind' IN (${list(CONNECTOR_SOURCE_KINDS)})))`;+}diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.tsindex 1147bbeb0d..26c3b585a6 100644--- a/src/core/cycle/extract-atoms-drain.ts+++ b/src/core/cycle/extract-atoms-drain.ts@@ -30,6 +30,7 @@*/import type { BrainEngine } from '../engine.ts';+import type { ExtractAtomsOpts } from './extract-atoms.ts';import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import { redactFindings } from '../secret-scan.ts';import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';@@ -147,6 +148,19 @@ export type DrainStop =| 'no_progress' | 'max_batches' | 'provider_failure';export const DRAIN_COUNT_TIMEOUT_MS = 60_000;++/**+ * #5856: dead-letter text of a drain the atom session preflight refused before any spend+ * (`owner_unavailable` / `permission_denied`). The auto-drain cap does not count such a job.+ */+export const STRUCTURAL_REFUSAL_PREFIX = 'structural_refusal:';++/** The non-retryable dead-letter text for a structural preflight refusal, or null for any other error. */+export function structuralAtomRefusal(error: unknown): string | null {+ if (!(error instanceof Error) || error.name !== 'OperationError') return null;+ const code = (error as Error & { code?: unknown }).code;+ return code === 'owner_unavailable' || code === 'permission_denied' ? `${STRUCTURAL_REFUSAL_PREFIX} ${code}: ${error.message}` : null;+}/** setTimeout fires at once past 2^31-1 ms; a longer window or deadline waits the maximum. */const MAX_TIMER_MS = 2 ** 31 - 1;@@ -446,8 +460,13 @@ export async function runExtractAtomsDrainForSource(const { runPhaseExtractAtoms, countExtractAtomsBacklog } = await import('./extract-atoms.ts');const { cycleLockIdFor } = await import('../cycle.ts');+ const { MaintenanceWriteWait } = await import('../persistence/maintenance-wait.ts');+const extractionSourceId = opts.sourceId ?? 'default';const lockId = cycleLockIdFor(opts.sourceId);+ // #5856/#5854: one call is one attempt; its batches share one BudgetTracker+ // (the per-run cap holds for the whole attempt) and one publish wait.+ const attempt: NonNullable<ExtractAtomsOpts['attempt']> = { writeWait: new MaintenanceWriteWait(opts.deadlineAtMs ?? null) };return runExtractAtomsDrain({@@ -459,6 +478,7 @@ export async function runExtractAtomsDrainForSource(brainDir: opts.brainDir,signal,stopSignal,+ attempt,});const d = (r.details ?? {}) as Record<string, unknown>;// issue #3218: `r.status` collapses to 'warn' whether ONE item faileddiff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex c00f59c491..81e6f592d1 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -71,6 +71,8 @@ import { truncateUtf8 } from '../text-safe.ts';import { corpusTextForExtraction } from '../context/corpus-segments.ts';import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';+import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';+import { connectorAtomExclusionSql } from './connector-atoms.ts';import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate } from './extract-atoms-cost-gate.ts';import { writeReceipt } from '../extract/receipt-writer.ts';import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';@@ -232,6 +234,8 @@ export interface ExtractAtomsOpts {* limit in the rollup, like a budget stop.*/stopSignal?: AbortSignal;+ /** #5856/#5854: one drain attempt's state shared by its batches: the first batch's BudgetTracker (one cap per attempt) and one publish wait. */+ attempt?: { budgetTracker?: BudgetTracker; writeWait?: MaintenanceWriteWait };}interface ExtractedAtom {@@ -391,6 +395,7 @@ export async function discoverExtractablePages(limit: number = PAGE_DISCOVERY_BUDGET,): Promise<AtomPageInput[]> {const hasFilter = Array.isArray(affectedSlugs) && affectedSlugs.length > 0;+ const connectorExclusion = await connectorAtomExclusionSql(engine);const sql = `SELECT p.id, p.knowledge_revision,(SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,@@ -408,6 +413,7 @@ export async function discoverExtractablePages(AND length(COALESCE(p.compiled_truth, '')) >= $3${MANAGED_ATOM_DISCOVERY_SQL}${PAGE_SCAN_STATE_EXCLUSION_SQL}+ ${connectorExclusion}${hasFilter ? "AND p.slug = ANY($5::text[])" : ''}AND NOT EXISTS (SELECT 1@@ -478,6 +484,7 @@ export async function countExtractAtomsBacklog(// The atom must live in the SAME source as the page either way, so the// brain-wide form keys the NOT EXISTS on `atom.source_id = p.source_id`.const scoped = sourceId !== undefined;+ const connectorExclusion = await connectorAtomExclusionSql(engine);const sql = scoped? `SELECT COUNT(*) AS cnt FROM pages pWHERE p.source_id = $1@@ -490,6 +497,7 @@ export async function countExtractAtomsBacklog(AND length(COALESCE(p.compiled_truth, '')) >= $3${MANAGED_ATOM_DISCOVERY_SQL}${PAGE_SCAN_STATE_EXCLUSION_SQL}+ ${connectorExclusion}AND NOT EXISTS (SELECT 1 FROM pages atomWHERE atom.type = 'atom' AND atom.source_id = $1@@ -507,6 +515,7 @@ export async function countExtractAtomsBacklog(AND length(COALESCE(p.compiled_truth, '')) >= $2${MANAGED_ATOM_DISCOVERY_SQL}${PAGE_SCAN_STATE_EXCLUSION_SQL}+ ${connectorExclusion}AND NOT EXISTS (SELECT 1 FROM pages atomWHERE atom.type = 'atom' AND atom.source_id = p.source_id@@ -680,7 +689,7 @@ export async function runPhaseExtractAtoms(): Promise<PhaseResult> {const sourceId = opts.sourceId ?? 'default';const chat = opts._chat ?? gatewayChat;- const managed = await managedAtomSession(engine, sourceId, opts._managedRetry);+ const managed = await managedAtomSession(engine, sourceId, opts._managedRetry, opts.attempt?.writeWait);const writeRequests: WriteReceipt[] = [];// 1a. Get transcripts (test seam OR production discovery).@@ -969,11 +978,12 @@ export async function runPhaseExtractAtoms(`gbrain config set pricing.overrides '{"${costGate.zeroPricedEmbedModel}": <usd-per-1M-tokens>}'.`,);}- const budgetTracker = new BudgetTracker({+ const budgetTracker = opts.attempt?.budgetTracker ?? new BudgetTracker({maxCostUsd: costGate.enforceCap ? budgetCap : undefined,label: 'cycle.extract_atoms',pricingOverrides: costGate.pricingOverrides ?? pricingOverrides,});+ if (opts.attempt) opts.attempt.budgetTracker = budgetTracker;// v0.41.19.0 (T3): throttled yield helper. Fires `opts.yieldDuringPhase`// every 30s. Cycle.ts threads `buildYieldDuringPhase(lock, outer)` sodiff --git a/src/core/minions/handlers/extract-atoms-drain.ts b/src/core/minions/handlers/extract-atoms-drain.tsindex bb0b05bee8..04a6bc2a38 100644--- a/src/core/minions/handlers/extract-atoms-drain.ts+++ b/src/core/minions/handlers/extract-atoms-drain.ts@@ -19,7 +19,7 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandlerconst { retryManagedAtomBatch } = await import('../../persistence/atom-retry.ts');return retryManagedAtomBatch(engine, job.data.sourceId, job.data.retryRequestId, `job:${job.id}`);}- const { formatDrainProviderFailure, runExtractAtomsDrainForSource } =+ const { formatDrainProviderFailure, runExtractAtomsDrainForSource, structuralAtomRefusal } =await import('../../cycle/extract-atoms-drain.ts');const { LockUnavailableError } = await import('../../db-lock.ts');const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined;@@ -73,6 +73,9 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandlerif (e instanceof LockUnavailableError) {return { phase: 'extract_atoms', status: 'skipped', deferred: true, reason: 'cycle_already_running' };}+ // #5856: the session preflight refused the writer itself (no owner, untrusted caller); a retry cannot change that.+ const structural = structuralAtomRefusal(e);+ if (structural) throw new UnrecoverableError(structural);if (e instanceof UnrecoverableError || !pastDeadline()) throw e;throw new UnrecoverableError(e instanceof Error ? e.message : String(e));}diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.tsindex c4e16d7d21..acf4e250ff 100644--- a/src/core/persistence/atom-maintenance.ts+++ b/src/core/persistence/atom-maintenance.ts@@ -13,6 +13,7 @@ import { acquireWorktree, getWorktreeBinding, managedPersistenceEnabled, type Woimport { isConnectorSourceKind } from './connector-identity.ts';import { preparePageMutation } from './page-prepare.ts';import { assertPersistenceAccepting, waitForWrite, writeResponse } from './service.ts';+import { MaintenanceWriteWait } from './maintenance-wait.ts';import type { PreparedMutation } from './coordinator.ts';import type { WriteAuthority, WriteRequest } from './model.ts';import type { WriteReceipt } from './types.ts';@@ -35,6 +36,8 @@ export interface ManagedAtomSession {authority: WriteAuthority;binding: WorktreeBinding | null;config: GBrainConfig;+ /** #5854: the publish wait of the job this session runs in (a drain attempt shares one across its batches). */+ wait: MaintenanceWriteWait;retry?: { runKey: string; checkpointKey: string; expectedCheckpoint: unknown; rows: WriteRequest[]; origin: AtomOrigin };}export interface AtomIntent extends Record<string, unknown> {@@ -50,7 +53,32 @@ export interface AtomIntent extends Record<string, unknown> {expectedCheckpoint?: unknown;}-export async function managedAtomSession(engine: BrainEngine, sourceId: string, retry?: { requestId: string; retryId: string }): Promise<ManagedAtomSession | null> {+/**+ * The managed atom write target of a source and the owner refusal its session raises (null when it can run).+ * An unbound connector source is database-only by design (connector_database), like its connector sync:+ * its local_path is the connector's state directory, not a canonical checkout.+ */+async function atomOwnerTarget(engine: BrainEngine, sourceId: string, source: { local_path: string | null; kind: string | null }) {+ const binding = await getWorktreeBinding(engine, sourceId);+ const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);+ const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');+ const connectorDatabase = writeThrough && !binding && isConnectorSourceKind(source.kind);+ const refusal = writeThrough && root && !binding && !connectorDatabase ? 'Atom maintenance requires the configured canonical owner.'+ : writeThrough && binding && (binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path)+ ? 'The canonical atom owner is unavailable; no extraction was started.' : null;+ return { binding, writeThrough, connectorDatabase, refusal };+}++/** #5856: the owner refusal a managed atom drain of this source would hit in its session preflight, or null (always null when unmanaged). */+export async function atomDrainOwnerRefusal(engine: BrainEngine, sourceId: string): Promise<string | null> {+ if (!(await managedPersistenceEnabled(engine))) return null;+ const [source] = await engine.executeRaw<{ local_path: string | null; kind: string | null }>(+ "SELECT local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ return source ? (await atomOwnerTarget(engine, sourceId, source)).refusal : null;+}++export async function managedAtomSession(engine: BrainEngine, sourceId: string, retry?: { requestId: string; retryId: string },+ wait: MaintenanceWriteWait = new MaintenanceWriteWait()): Promise<ManagedAtomSession | null> {if (!(await managedPersistenceEnabled(engine))) return null;assertPersistenceAccepting(engine);const caller = currentSubmissionAuthority();@@ -68,16 +96,8 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,}await authorizeWrite(engine, authority, 'put_page', 'atoms/preflight');await authorizeWrite(engine, authority, 'delete_page', 'atoms/preflight');- const binding = await getWorktreeBinding(engine, sourceId);- const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);- const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');- // An unbound connector source is database-only by design (connector_database), like its connector sync:- // its local_path is the connector's state directory, not a canonical checkout.- const connectorDatabase = writeThrough && !binding && isConnectorSourceKind(source.kind);- if (writeThrough && root && !binding && !connectorDatabase) throw new OperationError('owner_unavailable', 'Atom maintenance requires the configured canonical owner.');- if (writeThrough && binding && (binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path)) {- throw new OperationError('owner_unavailable', 'The canonical atom owner is unavailable; no extraction was started.');- }+ const { binding, writeThrough, connectorDatabase, refusal } = await atomOwnerTarget(engine, sourceId, source);+ if (refusal) throw new OperationError('owner_unavailable', refusal);if (writeThrough && binding) {const lock = await acquireWorktree(binding, 0, undefined, engine);if (!lock) throw new OperationError('writer_lock_unavailable', 'The canonical atom writer is busy; no extraction was started.');@@ -86,7 +106,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';else if (connectorDatabase) authority.databaseOnlyReason = 'connector_database';else if (!binding) authority.databaseOnlyReason = 'no_repo_configured';- const session: ManagedAtomSession = { sourceId, incarnation: source.incarnation, authority, binding: writeThrough ? binding : null, config: { engine: engine.kind } as GBrainConfig };+ const session: ManagedAtomSession = { sourceId, incarnation: source.incarnation, authority, binding: writeThrough ? binding : null, config: { engine: engine.kind } as GBrainConfig, wait };if (retry) {if (!retry.retryId || retry.retryId.length > 128) throw new OperationError('invalid_params', 'A bounded explicit atom retry identity is required.');const prior = await getWriteRequest(engine, authority.principal, requireUuid(retry.requestId));@@ -100,7 +120,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,const rows = await atomBatchRows(engine, session, p.runKey);for (let i = 0; i < rows.length; i++) {await authorizeStoredRequest(engine, rows[i]);- if (['queued', 'running', 'recovering'].includes(rows[i].state)) rows[i] = await waitForWrite(engine, rows[i], session.config);+ if (['queued', 'running', 'recovering'].includes(rows[i].state)) rows[i] = session.wait.observe(await waitForWrite(engine, rows[i], session.config, session.wait.ms()));if (['queued', 'running', 'recovering'].includes(rows[i].state)) writeResponse(rows[i]);}const expired = rows.find(row => row.compacted && !row.intent);@@ -248,7 +268,7 @@ export async function resumeManagedAtoms(engine: BrainEngine, session: ManagedAtif (!rows.length) return false;for (const row of rows) {await authorizeStoredRequest(engine, row);- const completed = await waitForWrite(engine, row, session.config);+ const completed = session.wait.observe(await waitForWrite(engine, row, session.config, session.wait.ms()));writeResponse(completed);if (completed.outcome?.failure) malformedAtomReceipt(completed);}@@ -318,7 +338,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA});const receipts: WriteReceipt[] = [];for (const row of rows) {- const finished = await waitForWrite(engine, row, session.config);+ const finished = session.wait.observe(await waitForWrite(engine, row, session.config, session.wait.ms()));try { writeResponse(finished); }catch (error) {// #5601: an accepted batch still publishing is progress; its deterministic request ids resume it next run.diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.tsindex 5479e223eb..112b9bd46f 100644--- a/src/core/persistence/connector-identity.ts+++ b/src/core/persistence/connector-identity.ts@@ -20,8 +20,9 @@ import type { GoogleSourceConfig } from '../google/types.ts';export type ConnectorKind = 'google' | 'github';+export const CONNECTOR_SOURCE_KINDS: readonly ConnectorKind[] = ['google', 'github'];/** A managed Google or GitHub connector source (`sources.config.kind`). */-export function isConnectorSourceKind(kind: unknown): kind is ConnectorKind { return kind === 'google' || kind === 'github'; }+export function isConnectorSourceKind(kind: unknown): kind is ConnectorKind { return CONNECTOR_SOURCE_KINDS.includes(kind as ConnectorKind); }export type ConnectorConfig = GoogleSourceConfig | GitHubSourceConfig;type LeafClass = 'identity' | 'excluded';type Rule = LeafClass | ((config: GitHubSourceConfig) => LeafClass);diff --git a/test/autopilot-auto-drain-dispatch.test.ts b/test/autopilot-auto-drain-dispatch.test.tsnew file mode 100644index 0000000000..c7b61aa2fa--- /dev/null+++ b/test/autopilot-auto-drain-dispatch.test.ts@@ -0,0 +1,164 @@+/**+ * #5856: the autopilot atom auto-drain submission pass, driven through the+ * real queue on PGLite (the tick itself is Postgres-gated; see the e2e+ * wrapper). Fairness between checkout-backed and connector sources, the+ * attempt-counted daily cap, the structural-refusal exclusion, the writer+ * pre-check and the opt-in for connector email/meeting pages.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { submitAutoDrains, AUTO_DRAIN_NEXT_KIND_KEY } from '../src/commands/autopilot-dispatch.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;+let home: string;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+});+afterAll(async () => { await engine.disconnect(); });+async function reset(): Promise<void> {+ await engine.executeRaw('DELETE FROM minion_jobs');+ await engine.executeRaw("DELETE FROM pages");+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'autopilot.auto_drain.%' OR key LIKE 'cycle.extract_atoms.%'");+}+beforeEach(async () => {+ await reset();+ home = mkdtempSync(join(tmpdir(), 'gbrain-auto-drain-'));+ await engine.setConfig('autopilot.auto_drain.threshold', '1');+ await engine.setConfig('cycle.extract_atoms.connector_pages', 'true');+});++const DAY1 = Date.parse('2026-09-20T12:00:00Z');+const DAY2 = Date.parse('2026-09-21T12:00:00Z');+const prose = (n: string) => `A durable decision about ${n}, recorded in prose with context. `.repeat(12);++async function gitSource(id: string, pages = 2): Promise<void> {+ const root = join(home, id);+ mkdirSync(root, { recursive: true });+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, root]);+ for (let i = 0; i < pages; i++) {+ await engine.putPage(`notes/${id}-${i}`, { type: 'note', title: `${id} ${i}`, compiled_truth: prose(`${id} ${i}`) } as never, { sourceId: id });+ }+}++async function connectorSource(id: string, type: 'email' | 'meeting' = 'email', pages = 2): Promise<void> {+ const state = join(home, `${id}-state`);+ mkdirSync(state, { recursive: true });+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,jsonb_build_object('kind','google'))", [id, state]);+ for (let i = 0; i < pages; i++) {+ await engine.putPage(`${type === 'email' ? 'emails' : 'calendar'}/${id}-${i}`, { type, title: `${id} ${i}`, compiled_truth: prose(`${id} ${i}`) } as never, { sourceId: id });+ }+}++async function tick(now = DAY1): Promise<string> {+ let stderr = '';+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;+ try {+ await withEnv({ GBRAIN_HOME: home }, () => submitAutoDrains(engine, queue, { timeoutMs: 60_000, jsonMode: true, now: () => now }));+ } finally { process.stderr.write = write; }+ await engine.executeRaw("UPDATE minion_jobs SET created_at=$1::timestamptz WHERE idempotency_key LIKE '%:' || $2",+ [new Date(now).toISOString(), new Date(now).toISOString().slice(0, 10)]);+ return stderr;+}++async function submitted(): Promise<Array<{ source: string; repo: string | null }>> {+ return engine.executeRaw<{ source: string; repo: string | null }>(+ "SELECT data->>'sourceId' AS source, data->>'repoPath' AS repo FROM minion_jobs WHERE name='extract-atoms-drain' ORDER BY id");+}++async function priorJob(sourceId: string, day: number, row: { status: string; attempts: number; error?: string }): Promise<void> {+ const job = await queue.add('extract-atoms-drain', { sourceId, window: 120 },+ { queue: 'default', idempotency_key: `autopilot-extract-atoms-drain:${sourceId}:${new Date(day).toISOString().slice(0, 10)}`, max_attempts: 3 },+ { allowProtectedSubmit: true });+ await engine.executeRaw(`UPDATE minion_jobs SET status=$2, attempts_started=$3, attempts_made=$3, error_text=$4, created_at=$5::timestamptz WHERE id=$1`,+ [job.id, row.status, row.attempts, row.error ?? null, new Date(day).toISOString()]);+}++test('six backlogged git sources and one connector source under the default cap: the connector gets a slot', async () => {+ for (const n of [1, 2, 3, 4, 5, 6]) await gitSource(`git-${n}`);+ await connectorSource('gmail');+ await tick();+ const jobs = await submitted();+ expect(jobs).toHaveLength(6);+ expect(jobs.map(j => j.source)).toEqual(['git-1', 'gmail', 'git-2', 'git-3', 'git-4', 'git-5']);+ expect(jobs.find(j => j.source === 'gmail')!.repo).toBeNull();+ expect(jobs.find(j => j.source === 'git-1')!.repo).toBe(join(home, 'git-1'));+});++test('one slot left with a git and a connector source: the git source is submitted, the connector goes first next day', async () => {+ await engine.setConfig('autopilot.auto_drain.max_usd_per_day', '0.3');+ await gitSource('git-a');+ await connectorSource('gmail');+ await tick(DAY1);+ expect((await submitted()).map(j => j.source)).toEqual(['git-a']);+ expect(await engine.getConfig(AUTO_DRAIN_NEXT_KIND_KEY)).toBe('connector');+ await tick(DAY2);+ expect((await submitted()).map(j => j.source)).toEqual(['git-a', 'gmail']);+ expect(await engine.getConfig(AUTO_DRAIN_NEXT_KIND_KEY)).toBe('checkout');+});++test('a structural refusal frees its slot and is not resubmitted the same day; a provider-failure dead letter keeps its units', async () => {+ await engine.setConfig('autopilot.auto_drain.max_usd_per_day', '0.3');+ await gitSource('git-a');+ await gitSource('git-b');+ await priorJob('git-a', DAY1, { status: 'dead', attempts: 1, error: 'structural_refusal: owner_unavailable: Atom maintenance requires the configured canonical owner.' });+ await tick(DAY1);+ expect((await submitted()).map(j => j.source)).toEqual(['git-a', 'git-b']);+ await tick(DAY1);+ expect((await submitted()).map(j => j.source)).toEqual(['git-a', 'git-b']);++ await reset();+ await engine.setConfig('autopilot.auto_drain.threshold', '1');+ await engine.setConfig('autopilot.auto_drain.max_usd_per_day', '0.3');+ await gitSource('git-c');+ await gitSource('git-d');+ await priorJob('git-c', DAY1, { status: 'dead', attempts: 1, error: 'extract-atoms-drain: all provider calls failed this batch (batches=1, remaining=2)' });+ await tick(DAY1);+ expect((await submitted()).map(j => j.source)).toEqual(['git-c']);+});++test('the cap counts attempts: a job retried three times consumes three units', async () => {+ await engine.setConfig('autopilot.auto_drain.max_usd_per_day', '0.9');+ await gitSource('git-a');+ await gitSource('git-b');+ await priorJob('git-a', DAY1, { status: 'dead', attempts: 3, error: 'extract-atoms-drain: all provider calls failed this batch (batches=1, remaining=2)' });+ await tick(DAY1);+ expect((await submitted()).map(j => j.source)).toEqual(['git-a']);+ await engine.executeRaw("UPDATE minion_jobs SET attempts_started=2, attempts_made=2 WHERE data->>'sourceId'='git-a'");+ await tick(DAY1);+ expect((await submitted()).map(j => j.source)).toEqual(['git-a', 'git-b']);+});++test('connector email and meeting pages are opt-in: off, a connector backlog submits nothing', async () => {+ await engine.setConfig('cycle.extract_atoms.connector_pages', 'false');+ await connectorSource('gmail', 'email');+ await connectorSource('gcal', 'meeting');+ await tick(DAY1);+ expect(await submitted()).toEqual([]);+ await engine.setConfig('cycle.extract_atoms.connector_pages', 'true');+ await tick(DAY1);+ expect((await submitted()).map(j => j.source).sort()).toEqual(['gcal', 'gmail']);+});++test('managed brain: a source whose writer preflight would refuse is skipped with its reason; an unbound connector is submitted database-only', async () => {+ await gitSource('git-unowned');+ await connectorSource('gmail');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ let stderr: string;+ try { stderr = await tick(DAY1); }+ finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); }+ expect(await submitted()).toEqual([{ source: 'gmail', repo: null }]);+ const skip = stderr.split('\n').filter(Boolean).map(line => JSON.parse(line)).find(e => e.event === 'auto_drain_source_skipped');+ expect(skip).toMatchObject({ source_id: 'git-unowned' });+ expect(skip.reason).toContain('requires the configured canonical owner');+});diff --git a/test/connector-atom-pages.test.ts b/test/connector-atom-pages.test.tsnew file mode 100644index 0000000000..a947d95553--- /dev/null+++ b/test/connector-atom-pages.test.ts@@ -0,0 +1,49 @@+/**+ * #5856: atom extraction of connector email/meeting pages is opt-in+ * (`cycle.extract_atoms.connector_pages`, default off). Discovery and the+ * backlog count agree, scoped and brain-wide; checkout-backed sources and+ * other connector page types are unaffected.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { countExtractAtomsBacklog, discoverExtractablePages } from '../src/core/cycle/extract-atoms.ts';+const CONNECTOR_ATOM_PAGES_KEY = 'cycle.extract_atoms.connector_pages';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ await engine.executeRaw('DELETE FROM config WHERE key=$1', [CONNECTOR_ATOM_PAGES_KEY]);+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES('gmail','gmail',jsonb_build_object('kind','google'))");+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('notes','notes','/tmp/gbrain-connector-atom-notes')");+ const prose = (n: string) => `A durable decision about ${n}, recorded in prose with context. `.repeat(12);+ await engine.putPage('emails/thread-1', { type: 'email', title: 'Thread 1', compiled_truth: prose('thread 1') } as never, { sourceId: 'gmail' });+ await engine.putPage('calendar/standup', { type: 'meeting', title: 'Standup', compiled_truth: prose('standup') } as never, { sourceId: 'gmail' });+ await engine.putPage('notes/connector-note', { type: 'note', title: 'Note', compiled_truth: prose('connector note') } as never, { sourceId: 'gmail' });+ await engine.putPage('emails/forwarded', { type: 'email', title: 'Forwarded', compiled_truth: prose('forwarded') } as never, { sourceId: 'notes' });+});++const slugs = async (sourceId: string) => (await discoverExtractablePages(engine, sourceId)).map(p => p.slug).sort();++test('off by default: connector email and meeting pages are neither discovered nor counted', async () => {+ expect(await slugs('gmail')).toEqual(['notes/connector-note']);+ expect(await countExtractAtomsBacklog(engine, 'gmail')).toBe(1);+ expect(await slugs('notes')).toEqual(['emails/forwarded']);+ expect(await countExtractAtomsBacklog(engine, 'notes')).toBe(1);+ expect(await countExtractAtomsBacklog(engine)).toBe(2);+});++test('opted in: connector email and meeting pages are discovered and counted', async () => {+ await engine.setConfig(CONNECTOR_ATOM_PAGES_KEY, 'true');+ expect(await slugs('gmail')).toEqual(['calendar/standup', 'emails/thread-1', 'notes/connector-note']);+ expect(await countExtractAtomsBacklog(engine, 'gmail')).toBe(3);+ expect(await countExtractAtomsBacklog(engine)).toBe(4);+ await engine.setConfig(CONNECTOR_ATOM_PAGES_KEY, 'false');+ expect(await countExtractAtomsBacklog(engine, 'gmail')).toBe(1);+});diff --git a/test/extract-atoms-drain-attempt.test.ts b/test/extract-atoms-drain-attempt.test.tsnew file mode 100644index 0000000000..25338d6968--- /dev/null+++ b/test/extract-atoms-drain-attempt.test.ts@@ -0,0 +1,77 @@+/**+ * #5856: one extract-atoms-drain attempt is one budget. Its batches share one+ * BudgetTracker, so the per-run dollar cap holds for the whole attempt+ * instead of once per batch.+ */+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import { runExtractAtomsDrainForSource } from '../src/core/cycle/extract-atoms-drain.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+beforeEach(async () => { await resetPgliteState(engine); });+afterAll(async () => { __setChatTransportForTests(null); await engine.disconnect(); resetGateway(); });++test('a three-batch drain attempt stops at its per-run cap (one BudgetTracker per attempt)', async () => {+ for (const n of [1, 2, 3]) {+ await engine.putPage(`notes/decision-${n}`, { type: 'note', title: `Decision ${n}`,+ compiled_truth: `Decision ${n}: a durable choice recorded in prose. `.repeat(20) } as never, { sourceId: 'default' });+ }+ await engine.setConfig('cycle.extract_atoms.page_discovery_budget', '1');+ await engine.setConfig('models.dream.extract_atoms', 'anthropic:claude-haiku-4-5');+ // Haiku: $1/M input, $5/M output. Each call reserves ~$0.021 (4,096 output+ // tokens) and records $0.015 (15,000 input tokens): one call fits the+ // $0.03 cap, a second reservation on the same tracker does not.+ await engine.setConfig('cycle.extract_atoms.budget_usd', '0.03');+ let calls = 0;+ __setChatTransportForTests(async (opts) => {+ calls++;+ const text = JSON.stringify([{ title: `Measured progress ${calls}`, atom_type: 'insight', body: `Measure progress against clear exit criteria ${calls}.` }]);+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 15_000, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: opts.model!, providerId: 'anthropic' };+ });+ try {+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-atom-budget' }, async () => {+ const result = await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120, maxBatches: 3 });+ expect(calls).toBe(1);+ expect(result.extracted).toBe(1);+ expect(result.remaining).toBe(2);+ expect(result.stopped).toBe('no_progress');+ });+ } finally { __setChatTransportForTests(null); }+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE type='atom' AND deleted_at IS NULL")).toHaveLength(1);+});++test('each drain attempt starts a fresh budget: the next attempt extracts the next page', async () => {+ for (const n of [1, 2]) {+ await engine.putPage(`notes/attempt-${n}`, { type: 'note', title: `Attempt ${n}`,+ compiled_truth: `Attempt ${n}: a durable choice recorded in prose. `.repeat(20) } as never, { sourceId: 'default' });+ }+ await engine.setConfig('cycle.extract_atoms.page_discovery_budget', '1');+ await engine.setConfig('models.dream.extract_atoms', 'anthropic:claude-haiku-4-5');+ await engine.setConfig('cycle.extract_atoms.budget_usd', '0.03');+ let calls = 0;+ __setChatTransportForTests(async (opts) => {+ calls++;+ const text = JSON.stringify([{ title: `Next step ${calls}`, atom_type: 'insight', body: `Ship the smallest next step ${calls}.` }]);+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 15_000, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: opts.model!, providerId: 'anthropic' };+ });+ try {+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-atom-budget' }, async () => {+ expect((await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120, maxBatches: 3 })).extracted).toBe(1);+ expect((await runExtractAtomsDrainForSource(engine, { sourceId: 'default', windowSeconds: 120, maxBatches: 3 })).extracted).toBe(1);+ });+ } finally { __setChatTransportForTests(null); }+ expect(calls).toBe(2);+});diff --git a/test/extract-atoms-drain-structural.test.ts b/test/extract-atoms-drain-structural.test.tsnew file mode 100644index 0000000000..57216ac3f3--- /dev/null+++ b/test/extract-atoms-drain-structural.test.ts@@ -0,0 +1,67 @@+/**+ * #5856: a drain the atom session preflight refuses structurally (no active+ * owner for a configured checkout, untrusted caller) dead-letters after ONE+ * attempt with `structural_refusal:` text and no model call, instead of+ * burning `max_attempts` retries.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { MinionWorker } from '../src/core/minions/worker.ts';+import { registerBuiltinHandlers } from '../src/commands/jobs.ts';+import { __setChatTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); });++test('a structural refusal dead-letters after one attempt with structural_refusal text and no model call', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-drain-structural-'));+ const root = join(home, 'checkout');+ mkdirSync(root);+ let calls = 0;+ __setChatTransportForTests(async () => { calls++; throw new Error('the model must not be called'); });+ const worker = new MinionWorker(engine, { pollInterval: 30 });+ try {+ await withEnv({ GBRAIN_HOME: join(home, 'home'), ANTHROPIC_API_KEY: 'sk-test-structural' }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['git-unowned', root]);+ for (const n of [1, 2]) {+ await engine.putPage(`notes/unowned-${n}`, { type: 'note', title: `Unowned ${n}`,+ compiled_truth: `A durable decision ${n} recorded in prose. `.repeat(20) } as never, { sourceId: 'git-unowned' });+ }+ await engine.setConfig('sync.write_through', 'true');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const job = await new MinionQueue(engine).add('extract-atoms-drain', { sourceId: 'git-unowned', window: 60, repoPath: root },+ { queue: 'default', max_attempts: 3, backoff_delay: 10 }, { allowProtectedSubmit: true });+ await registerBuiltinHandlers(worker, engine, { quiet: true });+ const running = worker.start();+ let row: { status: string; attempts_started: number; error_text: string | null } | undefined;+ for (let i = 0; i < 300; i++) {+ [row] = await engine.executeRaw<NonNullable<typeof row>>('SELECT status,attempts_started,error_text FROM minion_jobs WHERE id=$1', [job.id]);+ if (row && ['dead', 'completed', 'failed'].includes(row.status) || (row?.attempts_started ?? 0) >= 2) break;+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ worker.stop();+ await running;+ expect(row!.status).toBe('dead');+ expect(row!.attempts_started).toBe(1);+ expect(row!.error_text).toStartWith('structural_refusal: owner_unavailable: ');+ expect(calls).toBe(0);+ });+ } finally {+ worker.stop();+ __setChatTransportForTests(null);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(home, { recursive: true, force: true });+ }+}, 60_000);diff --git a/test/extract-atoms-drain-wait.test.ts b/test/extract-atoms-drain-wait.test.tsnew file mode 100644index 0000000000..fb444ab10e--- /dev/null+++ b/test/extract-atoms-drain-wait.test.ts@@ -0,0 +1,100 @@+/**+ * #5854: a drain attempt shares one maintenance publish wait across its+ * batches. When the canonical writer is busy, the first pending atom publish+ * costs one wait; every later publish in the attempt (the rest of the batch,+ * and the next batch resuming it) is deferred without waiting, and the+ * accepted batch commits once the writer frees up.+ */+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import { runExtractAtomsDrainForSource } from '../src/core/cycle/extract-atoms-drain.ts';+import { MaintenanceWriteWait, __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';+import { acquireWorktree, claimWorktree } from '../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { serializePageToMarkdown } from '../src/core/markdown.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); resetGateway(); });++test('a busy writer during a two-batch drain costs one wait; the deferred batch commits after it frees up', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-drain-wait-'));+ const root = join(home, 'repo');+ const sourceId = 'atoms-wait';+ const waits: number[] = [];+ const ms = MaintenanceWriteWait.prototype.ms;+ const spy = spyOn(MaintenanceWriteWait.prototype, 'ms').mockImplementation(function (this: MaintenanceWriteWait) {+ const value = ms.call(this);+ waits.push(value);+ return value;+ });+ __setMaintenanceWriteWaitForTests(400);+ try {+ await withEnv({ GBRAIN_HOME: join(home, 'home'), ANTHROPIC_API_KEY: 'sk-test-drain-wait' }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ mkdirSync(join(root, 'notes'), { recursive: true });+ for (const n of [1, 2]) {+ await engine.putPage(`notes/wait-${n}`, { type: 'note', title: `Wait ${n}`,+ compiled_truth: `Decision ${n}: a durable choice recorded in prose. `.repeat(20) } as never, { sourceId });+ writeFileSync(join(root, `notes/wait-${n}.md`), serializePageToMarkdown((await engine.getPage(`notes/wait-${n}`, { sourceId }))!, []));+ }+ await engine.setConfig('cycle.extract_atoms.page_discovery_budget', '1');+ await engine.setConfig('sync.write_through', 'true');+ await registerLocalWriter(engine, 'cli');+ const binding = await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;+ let calls = 0;+ __setChatTransportForTests(async (opts) => {+ calls++;+ lock = await acquireWorktree(binding, 1000);+ const text = JSON.stringify([{ title: `Exit criteria ${calls}`, atom_type: 'insight', body: `Measure progress against clear exit criteria ${calls}.` }]);+ 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' };+ });+ const started = performance.now();+ const result = await runExtractAtomsDrainForSource(engine, { sourceId, windowSeconds: 120, maxBatches: 2,+ onBatch: () => { void lock?.release(); lock = null; } });+ const elapsed = performance.now() - started;+ await (lock as Awaited<ReturnType<typeof acquireWorktree>>)?.release();+ expect(calls).toBe(1);+ expect(result.batches).toBe(2);+ expect(result.extracted).toBe(1);+ expect(waits.filter(w => w > 0)).toEqual([400]);+ expect(waits.length).toBeGreaterThanOrEqual(3);+ expect(elapsed).toBeLessThan(5_000);+ await disposePersistenceConsumer(engine);+ for (let i = 0; i < 100; i++) {+ const open = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state<>'committed'", [sourceId]);+ if (!open.length) break;+ await waitForCommit();+ }+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state<>'committed'", [sourceId])).toEqual([]);+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL", [sourceId])).toHaveLength(1);+ });+ } finally {+ spy.mockRestore();+ __setMaintenanceWriteWaitForTests(null);+ __setChatTransportForTests(null);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(home, { recursive: true, force: true });+ }+}, 60_000);++async function waitForCommit(): Promise<void> {+ const { startPersistenceConsumer } = await import('../src/core/persistence/service.ts');+ startPersistenceConsumer(engine, { engine: engine.kind } as never).wake();+ await new Promise(resolve => setTimeout(resolve, 100));+}diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.tsindex 58c94471e4..33e0705c81 100644--- a/test/helpers/managed-atoms-contract.ts+++ b/test/helpers/managed-atoms-contract.ts@@ -9,6 +9,7 @@ import { disposePersistenceConsumer, waitForWrite } from '../../src/core/persistimport { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';import { claimWorktree } from '../../src/core/persistence/ownership.ts';import { isPhysicalRootMetadata } from '../../src/core/persistence/physical-root.ts';+import { __setMaintenanceWriteWaitForTests } from '../../src/core/persistence/maintenance-wait.ts';import { registerLocalWriter, withVerifiedLocalRegistration, type LocalGrant } from '../../src/core/persistence/identity.ts';import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts';@@ -29,6 +30,8 @@ type Case = typeof atomContractCases[number];export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case): Promise<void> {const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atoms-'));const sourceId = `atoms-${scenario.replaceAll('_', '-')}`;+ // The deferred case only needs a pending publish; keep its wait at the pre-#5854 5 s.+ if (scenario === 'deferred') __setMaintenanceWriteWaitForTests(5_000);try {await withEnv({ GBRAIN_HOME: home }, async () => {await disposePersistenceConsumer(engine);@@ -264,7 +267,7 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):expect(state).toEqual([{ content_hash: page.content_hash!, fail_count: scenario === 'malformed' ? 1 : 0, tombstoned: scenario === 'zero_yield' }]);}});- } finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); rmSync(home, { recursive: true, force: true }); }+ } finally { __setMaintenanceWriteWaitForTests(null); await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); rmSync(home, { recursive: true, force: true }); }}export async function exerciseManagedAtomReconciliation(engine: BrainEngine): Promise<void> {