Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(autopilot): declaring extract_atoms no longer disables the daemon auto-drain; doctor judges the phase's own freshness (#5028)

time-attack2cb5586cfd0c
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 8089d0c0cc..61342ffcbb 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
-- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`.
+- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun`), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run.
- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.
diff --git a/src/commands/autopilot-dispatch.ts b/src/commands/autopilot-dispatch.ts
index 00fc68692e..8d81b775c4 100644
--- a/src/commands/autopilot-dispatch.ts
+++ b/src/commands/autopilot-dispatch.ts
@@ -408,17 +408,15 @@ export async function submitAutoDrains(
{ 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-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;
+ // The silent-backlog incident: the atom backlog grows invisibly when
+ // nothing runs extract_atoms. Auto-submit a bounded, PROTECTED drain per
+ // source when the backlog exceeds the threshold. Default-ON, daily-capped,
+ // time-sloted key so a new slot opens each UTC day (CODEX #1/#2/#3,
+ // DECISION 3C). #5028: this runs whether or not the active pack declares
+ // extract_atoms. The daemon's per-source cycles run only
+ // SOURCE_FRESHNESS_PHASES and the maintenance job runs no source phase, so
+ // a declaring pack does not make the routine cycle drain it; skipping here
+ // left this drain as the only runner switched off.
const parsePosInt = (v: string | null, d: number): number => {
if (v == null) return d;
const n = parseInt(v, 10);
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 1d935ee1c2..394daf92b6 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -646,6 +646,38 @@ async function latestFullCycleEvidence(
}
}
+/** #5028: a backlog source whose extract_atoms stamp is older than this is stale. */
+const EXTRACT_ATOMS_PHASE_WARN_HOURS = 48;
+
+/**
+ * #5028: backlog sources with no recent `last_extract_atoms_at` stamp (written
+ * by stampExtractAtomsRun after the phase actually runs, from a dream cycle
+ * or an auto-drain). The 48h window allows for the auto-drain's one slot per
+ * UTC day. Fail-open: an unreadable sources table returns null (no warn).
+ */
+async function sourcesWithStaleExtractAtomsRun(
+ engine: BrainEngine,
+ bySource: Array<{ source_id: string; backlog: number }>,
+ nowMs = Date.now(),
+): Promise<Array<{ source_id: string; backlog: number; last_extract_atoms_at: string | null }> | null> {
+ try {
+ const { LAST_EXTRACT_ATOMS_AT_KEY } = await import('../../../core/cycle/extract-atoms.ts');
+ const rows = await engine.executeRaw<{ id: string; stamp: string | null }>(
+ `SELECT id, config->>$2 AS stamp FROM sources WHERE id = ANY($1::text[])`,
+ [bySource.map((row) => row.source_id), LAST_EXTRACT_ATOMS_AT_KEY],
+ );
+ const stamps = new Map(rows.map((r) => [r.id, r.stamp]));
+ return bySource
+ .map((row) => ({ ...row, last_extract_atoms_at: stamps.get(row.source_id) ?? null }))
+ .filter((row) => {
+ const t = row.last_extract_atoms_at ? new Date(row.last_extract_atoms_at).getTime() : NaN;
+ return !Number.isFinite(t) || nowMs - t > EXTRACT_ATOMS_PHASE_WARN_HOURS * 3_600_000;
+ });
+ } catch {
+ return null;
+ }
+}
+
/**
* #4576 review fix: can this brain's shape produce per-source
* last_full_cycle_at stamps at all? Two lanes write them:
@@ -768,7 +800,37 @@ export async function computeExtractAtomsBacklogCheck(
},
};
}
- // Pack runs it AND a cycle completed recently (or the backlog is small,
+ // #5028: a recent cycle is not evidence that THIS phase ran: the
+ // autopilot daemon's per-source cycles run only the freshness phases
+ // yet stamp last_full_cycle_at. Require each backlog source's own
+ // last_extract_atoms_at stamp to be recent.
+ if (evidence && evidence.state === 'fresh') {
+ const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog, opts.sourceIds);
+ const phaseStale = backlogBySource ? await sourcesWithStaleExtractAtomsRun(engine, backlogBySource) : null;
+ if (phaseStale && phaseStale.length > 0) {
+ const drain = buildExtractAtomsDrainCommand(phaseStale);
+ const ids = phaseStale.map((row) => row.source_id).join(', ');
+ return {
+ name, status: 'warn',
+ message:
+ `${backlog} page(s) pending and cycles run, but extract_atoms has not run in the last ` +
+ `${EXTRACT_ATOMS_PHASE_WARN_HOURS}h for source(s) ${ids} (routine autopilot cycles run only the ` +
+ `freshness phases; the daily auto-drain needs autopilot on Postgres and a backlog above ` +
+ `autopilot.auto_drain.threshold). Drain now: ${drain}`,
+ details: {
+ backlog,
+ backlog_by_source: backlogBySource ?? undefined,
+ pack_declares_phase: true,
+ cycle_evidence: 'fresh',
+ phase_evidence: 'stale',
+ phase_stale_sources: phaseStale,
+ fix_hint: drain,
+ known_approximation: approx,
+ },
+ };
+ }
+ }
+ // Pack runs it AND the phase ran recently (or the backlog is small,
// or evidence is unreadable — fail-open). Informational.
return {
name, status: 'ok',
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 7123d3f476..e15399b06c 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -2423,6 +2423,10 @@ export async function runCycle(
signal: xaSignal?.signal,
}), 'extract_atoms').finally(() => xaSignal?.dispose());
result.duration_ms = duration_ms;
+ if (!dryRun) {
+ const { stampExtractAtomsRun } = await import('./cycle/extract-atoms.ts');
+ await stampExtractAtomsRun(engine, xaSourceId, result);
+ }
phaseResults.push(result);
progress.finish();
}
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.ts
index 26c3b585a6..896f2a6aa6 100644
--- a/src/core/cycle/extract-atoms-drain.ts
+++ b/src/core/cycle/extract-atoms-drain.ts
@@ -457,7 +457,7 @@ export async function runExtractAtomsDrainForSource(
opts: DrainForSourceOpts,
): Promise<ExtractAtomsDrainResult> {
const { withRefreshingLock } = await import('../db-lock.ts');
- const { runPhaseExtractAtoms, countExtractAtomsBacklog } = await import('./extract-atoms.ts');
+ const { runPhaseExtractAtoms, countExtractAtomsBacklog, stampExtractAtomsRun } = await import('./extract-atoms.ts');
const { cycleLockIdFor } = await import('../cycle.ts');
const { MaintenanceWriteWait } = await import('../persistence/maintenance-wait.ts');
@@ -480,6 +480,7 @@ export async function runExtractAtomsDrainForSource(
stopSignal,
attempt,
});
+ await stampExtractAtomsRun(engine, extractionSourceId, r);
const d = (r.details ?? {}) as Record<string, unknown>;
// issue #3218: `r.status` collapses to 'warn' whether ONE item failed
// (partial success — leave the drain's existing ok/no_progress path
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index a3ea434086..72b67356bd 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -684,6 +684,26 @@ export async function resolveExtractAtomsModel(engine: BrainEngine): Promise<str
* discoverTranscripts + discoverExtractablePages (both lazy-imported
* to avoid circular module loads and to keep PGLite-only tests fast).
*/
+/** #5028: sources.config key stamped after a pass of extract_atoms that ran. */
+export const LAST_EXTRACT_ATOMS_AT_KEY = 'last_extract_atoms_at';
+
+/**
+ * #5028: record that extract_atoms actually ran for a source, so doctor can
+ * judge the phase's own freshness instead of `last_full_cycle_at` (which
+ * freshness-only cycles stamp without running this phase). Counts a pass
+ * that finished ok, or warned with at least one item processed; a pass where
+ * every item failed, or a skip, does not stamp; callers skip dry runs.
+ * Best-effort.
+ */
+export async function stampExtractAtomsRun(engine: BrainEngine, sourceId: string, result: PhaseResult): Promise<void> {
+ const d = (result.details ?? {}) as Record<string, unknown>;
+ const processed = Number(d.transcripts_processed ?? 0) + Number(d.pages_processed ?? 0);
+ const ran = result.status === 'ok' || (result.status === 'warn' && processed > 0);
+ if (!ran) return;
+ try { await engine.updateSourceConfig(sourceId, { [LAST_EXTRACT_ATOMS_AT_KEY]: new Date().toISOString() }); }
+ catch { /* the stamp is evidence only; never fail the phase over it */ }
+}
+
export async function runPhaseExtractAtoms(
engine: BrainEngine,
opts: ExtractAtomsOpts = {},
diff --git a/test/autopilot-auto-drain-declared-pack-5028.test.ts b/test/autopilot-auto-drain-declared-pack-5028.test.ts
new file mode 100644
index 0000000000..1a9b79806e
--- /dev/null
+++ b/test/autopilot-auto-drain-declared-pack-5028.test.ts
@@ -0,0 +1,98 @@
+/**
+ * #5028 (fix wave 9) — a pack that declares extract_atoms must not switch off
+ * the autopilot atom auto-drain.
+ *
+ * Pre-fix submitAutoDrains returned early whenever the active pack declared
+ * extract_atoms, on the theory that the routine cycle drains it. On the
+ * Postgres daemon it does not: per-source cycles run only
+ * SOURCE_FRESHNESS_PHASES and the maintenance job runs no source phase, so
+ * declaring the phase stopped the only thing that ran it.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, writeFileSync } 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 } from '../src/commands/autopilot-dispatch.ts';
+import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, packDeclaresPhase } from '../src/core/cycle.ts';
+import { __setPackLocatorForTests, _resetPackLocatorForTests } from '../src/core/schema-pack/load-active.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { stampExtractAtomsRun } from '../src/core/cycle/extract-atoms.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+const HOME = mkdtempSync(join(tmpdir(), 'gbrain-5028-'));
+const PACK_NAME = 'declares-xa-5028';
+const ENV = { GBRAIN_HOME: HOME, GBRAIN_SCHEMA_PACK: PACK_NAME };
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+ const dir = join(HOME, 'schema-packs', PACK_NAME);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, 'pack.yaml');
+ writeFileSync(path, [
+ 'api_version: gbrain-schema-pack-v1', `name: ${PACK_NAME}`, 'version: 1.0.0', 'description: ""',
+ 'gbrain_min_version: 0.38.0', 'extends: null', 'borrow_from: []', 'page_types: []', 'link_types: []',
+ 'frontmatter_links: []', 'takes_kinds:', ' - fact', 'enrichable_types: []', 'filing_rules: []',
+ 'phases:', ' - extract_atoms', '',
+ ].join('\n'), 'utf-8');
+ __setPackLocatorForTests((name) => (name === PACK_NAME ? path : null));
+}, 120_000);
+
+afterAll(async () => {
+ _resetPackLocatorForTests();
+ _resetPackCacheForTests();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ _resetPackCacheForTests();
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
+ await engine.setConfig('autopilot.auto_drain.threshold', '1');
+});
+
+const prose = (n: string) => `A durable decision about ${n}, recorded in prose with context. `.repeat(12);
+
+test('the daemon cycle split never runs extract_atoms, so a declaring pack cannot rely on it', () => {
+ expect(SOURCE_FRESHNESS_PHASES).not.toContain('extract_atoms');
+ expect(MAINTENANCE_PHASES).not.toContain('extract_atoms');
+});
+
+test('a backlogged source still gets its daily drain when the active pack declares extract_atoms', async () => {
+ const root = join(HOME, 'vault');
+ mkdirSync(root, { recursive: true });
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['vault', root]);
+ for (let i = 0; i < 3; i++) {
+ await engine.putPage(`articles/vault-${i}`, { type: 'article', title: `vault ${i}`, compiled_truth: prose(`vault ${i}`) } as never, { sourceId: 'vault' });
+ }
+ await withEnv(ENV, async () => {
+ expect(await packDeclaresPhase(engine, 'extract_atoms')).toBe(true);
+ await submitAutoDrains(engine, queue, { timeoutMs: 60_000, jsonMode: true, now: () => Date.parse('2026-10-05T12:00:00Z') });
+ });
+ const jobs = await engine.executeRaw<{ source: string; key: string }>(
+ "SELECT data->>'sourceId' AS source, idempotency_key AS key FROM minion_jobs WHERE name = 'extract-atoms-drain'");
+ expect(jobs).toEqual([{ source: 'vault', key: 'autopilot-extract-atoms-drain:vault:2026-10-05' }]);
+});
+
+test('extract_atoms stamps last_extract_atoms_at only for a pass that ran', async () => {
+ const stamp = async () => (await engine.executeRaw<{ s: string | null }>(
+ "SELECT config->>'last_extract_atoms_at' AS s FROM sources WHERE id = 'default'"))[0]?.s ?? null;
+ await engine.executeRaw("UPDATE sources SET config = config - 'last_extract_atoms_at' WHERE id = 'default'");
+ const base = { phase: 'extract_atoms' as const, duration_ms: 0, summary: '' };
+ await stampExtractAtomsRun(engine, 'default', { ...base, status: 'fail', details: {} });
+ await stampExtractAtomsRun(engine, 'default', { ...base, status: 'skipped', details: {} });
+ await stampExtractAtomsRun(engine, 'default', { ...base, status: 'warn', details: { pages_processed: 0, transcripts_processed: 0 } });
+ expect(await stamp()).toBeNull();
+ await stampExtractAtomsRun(engine, 'default', { ...base, status: 'warn', details: { pages_processed: 2 } });
+ expect(await stamp()).not.toBeNull();
+ await engine.executeRaw("UPDATE sources SET config = config - 'last_extract_atoms_at' WHERE id = 'default'");
+ await stampExtractAtomsRun(engine, 'default', { ...base, status: 'ok', details: {} });
+ expect(Number.isFinite(new Date((await stamp())!).getTime())).toBe(true);
+});
diff --git a/test/autopilot-auto-drain-wiring.test.ts b/test/autopilot-auto-drain-wiring.test.ts
index d167853be6..122bd57a6c 100644
--- a/test/autopilot-auto-drain-wiring.test.ts
+++ b/test/autopilot-auto-drain-wiring.test.ts
@@ -30,8 +30,11 @@ describe('autopilot auto-drain wiring', () => {
expect(SRC).toContain('countExtractAtomsBacklog(engine, src.id)');
});
- test('gates on pack NOT declaring extract_atoms (the silent-backlog condition)', () => {
- expect(SRC).toContain("packDeclaresPhase(engine, 'extract_atoms')");
+ // #5028 (D6): the pack-declaration gate was removed on the daemon path; a
+ // declaring pack does not make the daemon's cycles run extract_atoms.
+ // Behavior pinned by test/autopilot-auto-drain-declared-pack-5028.test.ts.
+ test('does not gate on the pack declaring extract_atoms (#5028)', () => {
+ expect(SRC).not.toContain("packDeclaresPhase(engine, 'extract_atoms')");
});
test('gates on the enabled flag and a daily spend cap (DECISION 3C)', () => {
diff --git a/test/doctor-extract-atoms-backlog.test.ts b/test/doctor-extract-atoms-backlog.test.ts
index b320614578..bebf2bdba0 100644
--- a/test/doctor-extract-atoms-backlog.test.ts
+++ b/test/doctor-extract-atoms-backlog.test.ts
@@ -193,6 +193,11 @@ async function seedCycledSource(id: string, lastFullCycleAt?: string): Promise<v
);
}
+/** #5028: stamp a source's last_extract_atoms_at (what stampExtractAtomsRun writes). */
+async function stampExtractAtoms(id: string, iso: string): Promise<void> {
+ await engine.updateSourceConfig(id, { last_extract_atoms_at: iso });
+}
+
describe('computeExtractAtomsBacklogCheck — declared branch verifies a runner (#4576)', () => {
beforeEach(() => {
_resetPackCacheForTests();
@@ -230,12 +235,37 @@ describe('computeExtractAtomsBacklogCheck — declared branch verifies a runner
it('stays OK when a cycle completed recently (fresh evidence)', async () => {
for (let i = 0; i < 11; i++) await seedArticle(`declared-fresh-${i}`);
await seedCycledSource('vault', new Date(Date.now() - 3600_000).toISOString());
+ // #5028: the OK also needs the backlog source's own extract_atoms stamp;
+ // a fresh full-cycle stamp alone is the freshness-only false OK below.
+ await stampExtractAtoms('default', new Date(Date.now() - 3600_000).toISOString());
const check = await withEnv(PACK_ENV, () => computeExtractAtomsBacklogCheck(engine));
expect(check.status).toBe('ok');
expect(check.message).toContain('active pack runs extract_atoms each cycle');
expect((check.details as { pack_declares_phase: boolean }).pack_declares_phase).toBe(true);
});
+ it('WARNs when cycles run but extract_atoms itself has not run for the backlog source (#5028)', async () => {
+ for (let i = 0; i < 11; i++) await seedArticle(`declared-freshness-only-${i}`);
+ await seedCycledSource('vault', new Date(Date.now() - 3600_000).toISOString());
+ const check = await withEnv(PACK_ENV, () => computeExtractAtomsBacklogCheck(engine));
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('extract_atoms has not run in the last 48h for source(s) default');
+ expect(check.message).toContain('gbrain dream --phase extract_atoms --drain --source default');
+ const details = check.details as { cycle_evidence: string; phase_evidence: string; phase_stale_sources: Array<{ source_id: string; backlog: number; last_extract_atoms_at: string | null }> };
+ expect(details.cycle_evidence).toBe('fresh');
+ expect(details.phase_evidence).toBe('stale');
+ expect(details.phase_stale_sources).toEqual([{ source_id: 'default', backlog: 11, last_extract_atoms_at: null }]);
+ });
+
+ it('WARNs when the backlog source last ran extract_atoms outside the 48h window (#5028)', async () => {
+ for (let i = 0; i < 11; i++) await seedArticle(`declared-phase-stale-${i}`);
+ await seedCycledSource('vault', new Date(Date.now() - 3600_000).toISOString());
+ await stampExtractAtoms('default', new Date(Date.now() - 72 * 3600_000).toISOString());
+ const check = await withEnv(PACK_ENV, () => computeExtractAtomsBacklogCheck(engine));
+ expect(check.status).toBe('warn');
+ expect((check.details as { phase_evidence: string }).phase_evidence).toBe('stale');
+ });
+
it('stays OK below the warn threshold even with no cycle evidence', async () => {
for (let i = 0; i < 3; i++) await seedArticle(`declared-small-${i}`);
await seedCycledSource('vault');