Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): facts_extraction_health separates historical incidents from jobs still dead (#6761)

garrytan6e5424c44518
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index b4b30bf00a..0ebfe6450a 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/embedding-identity.ts` — `embedding_identity_unqualified` (#6113, BRAIN, right after `embedding_env_override`): warns when the DB `config` row `embedding_model` has no provider prefix (managed fact extraction reads only that row and `config set` refuses it). The fix is the read-only `gbrain migrate embeddings --to <provider:model> --dry-run`, filled from `loadConfig()`'s provider-qualified `embedding_model`, or `<PROVIDER_MODEL>` plus an `inputs` entry when none is configured; `details.target_differs` flags a configured model with another name (applying it switches models). Applying re-embeds active facts (paid, user's call). The free relabel is parked (TODOS). Test: `test/doctor-embedding-identity-unqualified.test.ts`.
- `src/commands/doctor/checks/embedding-state.ts` — `embedding_state` (#6696 B3, BRAIN, `tier: 'ops'`, `opsPglite: 'not_applicable'`, after `embeddings`): `readEmbeddingState` in `ops` mode on the ops tier, `full` otherwise. Warns only on chunks of pages soft-deleted past the 72 h purge window (`deleted_page_chunks_overdue`, fix `pages purge-deleted`) and, on a keyed brain, live pages with body text but no chunks (`chunkless_pages_healable`, fix `embed --stale`); the pending backlog stays `embeddings`' warning and quarantined pages `quarantined_pages`'. keyword_only, deleted chunks inside the window and a keyless brain are `infoCheck`; ops without a covering index warns with `details.health: 'unknown'` (`embedding_state_unknown`). Test: `test/doctor-embedding-state.test.ts`.
-- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`.
+- `src/commands/doctor/checks/knowledge-health.ts` — `facts_extraction_health` reads the last 24 h of `facts:absorb` rows in `ingest_log` (written by `src/core/facts/absorb-log.ts`) per source and reason (`split_part(summary, ':', 1)`) and warns when a failure reason reaches `facts.absorb_warn_threshold` (default 10) in a source. Two reasons are not failures and never count: `write_pending_accepted` (the absorb log read the facts write's receipt back from the journal and it is still queued, running or recovering after the job's publish wait) and `write_deferred_unadmitted` (`writer_lock_unavailable` before admission, no receipt; the job retries). Deferrals warn on their own when, in a source, more than 10 or one over an hour old have no later completed `facts-absorb` job for the same page; that warning's fix is the read-only `gbrain sources writer status --source <id> --json`. The failure count is history: the message gives the incidents in the rolling 24 h window and when the newest ages out, and `details.facts_absorb` (`incidents_24h`, `ages_out_at`, `jobs_still_dead`, `dead_jobs`) adds the current state, the `facts-absorb` jobs dead or failed in the last 24 h with no later completed job for the same page (source and slug); they never change the status, and when no other fix applies the newest one gets the paid `gbrain jobs retry <id>` fix (`retry_job` over MCP, asks first). Tests: `test/doctor-facts-absorb-contention-6778.test.ts`, `test/facts-absorb-publish-wait-6778.test.ts`, `test/doctor-facts-absorb-history-6761.test.ts`.
- `src/commands/doctor/checks/persistence-consumers.ts` — #6317 (B3, T1c): doctor `two_consumers_on_host` (warn only when two live rows of resident kinds on this host have both been alive longer than 30 s; every other row, a `put` or a row younger than 30 s, is listed in `details`) and `consumers_without_heartbeat` (a `claim_phase.owner` pid on a running claim of this host with no heartbeat row: an older process that never defers; named with its kind and version from the stamp). Both carry a structured `agentFix` (`gbrain sources writer status --json`) and `doctorVerify`; with `persistence.single_consumer` off the overlap is reported as the configured behavior. `serve_build_drift` (#6696 C6, its own `serveBuildDriftEntry`, one `listHostConsumers` read, ok on PGLite with no read) compares the live resident rows (not this process) with this binary's `VERSION` through `compareWriterVersions` (an unparsable version counts as older): an older row warns "serve is running an older build than this checkout; restart serve and workers" with `details { count, this_version, owner, older, newer }` and a `fix` (actor `user`, `doctorVerify`) whose argv is the installed serve service's restart (`systemctl --user restart gbrain-serve.service` when `systemdUnitPath` exists on Linux, `launchctl kickstart -k gui/<uid>/com.gbrain.serve` when `launchdPlistPath` exists on macOS; `serveBuildDriftCheck`'s `ServiceHost` argument injects platform, home and uid) or else `kill <pid>`; a newer row is reported in an ok message; no rows names `consumers_without_heartbeat` for a pre-heartbeat serve. Registered in `DOCTOR_CHECK_REGISTRY` (the consumer entry, then `serveBuildDriftEntry`) before `searchModeEntry` and categorised `ops` in `src/core/doctor-categories.ts`. Tests: `test/doctor-serve-build-drift.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index b8870328a0..bebed54053 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -90,7 +90,7 @@ of making a duplicate.
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried with `gbrain sync --source <source> --no-pull --retry-failed`; an ignored file syncs once it is committed and not ignored. `gbrain sync status --source <source> --json` shows the source's failures and holds. |
-| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
+| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). Doctor's incident count is a historical metric: it counts the `facts:absorb` rows of a rolling 24 h window, says when they age out, and keeps counting them after the cause is fixed and the job retried, so a warning there does not by itself mean anything is still broken; the threshold (`facts.absorb_warn_threshold`) is unchanged. The current state is the check's `jobs still dead` count: facts-absorb jobs that went dead or failed in the last 24 h and that no later job for the same page completed after, each named with `gbrain jobs retry <id>`. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
diff --git a/src/commands/doctor/checks/knowledge-health.ts b/src/commands/doctor/checks/knowledge-health.ts
index 1a2e79defd..c162b25e3e 100644
--- a/src/commands/doctor/checks/knowledge-health.ts
+++ b/src/commands/doctor/checks/knowledge-health.ts
@@ -197,17 +197,30 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
source_id: string;
reason: string;
n: string | number;
+ newest: string | Date;
}>(
`SELECT
source_id,
split_part(summary, ':', 1) AS reason,
- COUNT(*)::text AS n
+ COUNT(*)::text AS n,
+ MAX(created_at) AS newest
FROM ingest_log
WHERE source_type = 'facts:absorb'
AND created_at >= now() - INTERVAL '24 hours'
GROUP BY source_id, split_part(summary, ':', 1)
ORDER BY source_id, COUNT(*) DESC`,
);
+ // #6778: an accepted write still committing and a retry after writer contention before admission are not
+ // failures, so they never count toward the threshold; contention that persists warns on its own.
+ const { WRITE_PENDING_ACCEPTED, WRITE_DEFERRED_UNADMITTED } = await import('../../../core/facts/absorb-log.ts');
+ const notFailures = [WRITE_PENDING_ACCEPTED, WRITE_DEFERRED_UNADMITTED];
+ // #6761: the incident count is history (a rolling window); the facts-absorb jobs still dead are the current state.
+ const failures = rows.filter(r => !notFailures.includes(r.reason));
+ const incidents = failures.reduce((sum, r) => sum + (Number(r.n) || 0), 0);
+ const agesOutAt = incidents ? new Date(Math.max(...failures.map(r => new Date(r.newest).getTime())) + 24 * 3600_000).toISOString() : null;
+ const dead = await factsAbsorbJobsStillDead(engine);
+ const deadSentence = dead.total === 0 ? '' : `${dead.total} job${dead.total === 1 ? '' : 's'} still dead (${dead.jobs.map(j => `job ${j.id} for ${j.slug ?? 'an unknown page'}`).join(', ')}): ` +
+ `fix the cause in its error (\`gbrain jobs get <id>\`), then ${dead.jobs.map(j => `\`gbrain jobs retry ${j.id}\``).join(', ')}.`;
if (rows.length === 0) {
// Zero failure rows is only "healthy" when extraction is actually
@@ -251,10 +264,6 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
});
}
} else {
- // #6778: an accepted write still committing and a retry after writer contention before admission are not
- // failures, so they never count toward the threshold; contention that persists warns on its own.
- const { WRITE_PENDING_ACCEPTED, WRITE_DEFERRED_UNADMITTED } = await import('../../../core/facts/absorb-log.ts');
- const notFailures = [WRITE_PENDING_ACCEPTED, WRITE_DEFERRED_UNADMITTED];
// Group per source so the breakdown is operator-friendly.
const bySource = new Map<string, Array<{ reason: string; n: number }>>();
let anyOverThreshold = false;
@@ -284,8 +293,8 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
message: [
anyOverThreshold
? `Facts:absorb failures over the threshold (${threshold}) in the last 24h: ${summary}. ` +
- `Run \`gbrain recall --since 24h --json\` to inspect what landed; ` +
- `tune the gate via \`gbrain config set facts.absorb_warn_threshold N\`.`
+ `${incidents} incident${incidents === 1 ? '' : 's'} in 24 h (rolling, ages out at ${agesOutAt})` +
+ (dead.total ? '.' : '; 0 jobs still dead. No facts-absorb job is unresolved, so these are past attempts: nothing needs retrying, and the warning clears as they age out.')
: `Facts:absorb activity in last 24h (under threshold ${threshold}): ${summary}.`,
notes,
contended ? `Writer contention persists (${contended}). Check the canonical writer with \`gbrain sources writer status --source ${contention[0].source_id} --json\`.` : '',
@@ -298,8 +307,20 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
} : {}),
});
}
- const note = await conversationPipelineNote(engine);
const check = checks[checks.length - 1];
+ if (check && (rows.length > 0 || dead.total > 0)) {
+ if (deadSentence) check.message = `${check.message} ${deadSentence}`;
+ check.details = { ...(check.details ?? {}),
+ facts_absorb: { incidents_24h: incidents, ages_out_at: agesOutAt, jobs_still_dead: dead.total, dead_jobs: dead.jobs } };
+ const newestDead = dead.jobs[0];
+ if (newestDead && !check.fix) {
+ check.fix = agentFix(['gbrain', 'jobs', 'retry', String(newestDead.id)],
+ `Re-queues dead facts-absorb job ${newestDead.id}, which extracts ${newestDead.slug ?? 'its page'} again with a paid model call. Fix the cause in the job's error first (gbrain jobs get ${newestDead.id}).`,
+ 'facts_extraction_health', { consent: ['paid'], mcp: { tool: 'retry_job', arguments: { id: newestDead.id } },
+ user_message: `Facts extraction for ${newestDead.slug ?? 'a page'} failed and its job is dead. Retrying job ${newestDead.id} makes one paid model call. Should I retry it?` });
+ }
+ }
+ const note = await conversationPipelineNote(engine);
if (note && check) {
check.message = `${check.message} ${note.message}`;
check.details = { ...(check.details ?? {}), conversation_pipeline: note.details };
@@ -328,6 +349,32 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
return checks;
}
+/**
+ * #6761: facts-absorb jobs that went dead or failed in the last 24 h and are still in that state, newest first (at
+ * most 5 listed): a job a later facts-absorb job for the same page (source and slug: the backstop queue path sets no
+ * `page_id`) completed after is not counted.
+ */
+async function factsAbsorbJobsStillDead(engine: ReturnType<typeof connectedEngine>) {
+ try {
+ const rows = await engine.executeRaw<{ id: number; slug: string | null; source_id: string; status: string; total: string | number }>(
+ `SELECT j.id, j.data->>'slug' AS slug, COALESCE(j.data->>'sourceId', 'default') AS source_id, j.status, COUNT(*) OVER () AS total
+ FROM minion_jobs j
+ WHERE j.name = 'facts-absorb' AND j.status IN ('dead', 'failed')
+ AND COALESCE(j.finished_at, j.updated_at) >= now() - INTERVAL '24 hours'
+ AND NOT EXISTS (
+ SELECT 1 FROM minion_jobs k
+ WHERE k.name = 'facts-absorb' AND k.status = 'completed' AND k.id > j.id
+ AND k.data->>'slug' = j.data->>'slug' AND COALESCE(k.data->>'sourceId', 'default') = COALESCE(j.data->>'sourceId', 'default'))
+ ORDER BY j.id DESC
+ LIMIT 5`,
+ );
+ return { total: Number(rows[0]?.total ?? 0), jobs: rows.map(({ total: _total, ...job }) => ({ ...job, id: Number(job.id) })) };
+ } catch (err) {
+ if (isMissingSchemaObject(err, 'table', 'minion_jobs')) return { total: 0, jobs: [] };
+ throw err;
+ }
+}
+
/**
* #6778: per source, the facts writes deferred before admission (writer_lock_unavailable) in the last 24 h that no
* facts-absorb job for the same page completed after, when they persist: more than 10, or the oldest over an hour old.
diff --git a/test/doctor-facts-absorb-history-6761.test.ts b/test/doctor-facts-absorb-history-6761.test.ts
new file mode 100644
index 0000000000..bb82cf6a27
--- /dev/null
+++ b/test/doctor-facts-absorb-history-6761.test.ts
@@ -0,0 +1,162 @@
+/**
+ * #6761: doctor facts_extraction_health reports its 24 h `facts:absorb`
+ * incident count as history (a rolling window, with the time it ages out)
+ * apart from current state: the facts-absorb jobs still dead, each with the
+ * `gbrain jobs retry <id>` fix. Status thresholds are unchanged.
+ *
+ * 1. Protects: ten incidents with no dead job say there is nothing to retry and
+ * when the count ages out, without "tune the gate" advice; a dead job is
+ * named with its retry fix (asks first: it is a paid re-extraction) on the
+ * CLI and over MCP, and the verify clears once it is retried; a dead job a
+ * later completed job for the same page superseded is not counted.
+ * 2. Fails if the message goes back to the bare count with threshold tuning,
+ * if dead jobs are not read, or if a superseded job is still reported.
+ * 3. test/doctor-facts-absorb-contention-6778.test.ts covers the non-failure
+ * reasons; nothing read minion_jobs for this check before.
+ * 4. No production seam: rows are seeded in ingest_log and minion_jobs, and the
+ * journey runs the real CLI against an on-disk PGLite brain (no worker runs,
+ * so the retried job makes no model call).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { factsExtractionEntry } from '../src/commands/doctor/checks/knowledge-health.ts';
+import { finalizeCheckFixes } from '../src/commands/doctor/check-fix.ts';
+import { cliRenderContext } from '../src/core/agent-output.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { gb, oneDocument } from './helpers/agent-journey.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig('version', String(LATEST_VERSION)); });
+
+const REFUSED = 'write_refused: revision_conflict (OperationError): The source page changed before fact extraction.';
+
+async function incidents(db: BrainEngine, count: number): Promise<void> {
+ for (let i = 0; i < count; i++) {
+ await db.logIngest({ source_id: 'default', source_type: 'facts:absorb', source_ref: `notes/page-${i}`, pages_updated: [], summary: REFUSED });
+ }
+}
+
+async function factsJob(db: BrainEngine, status: 'dead' | 'completed', pageId: number, hoursAgo = 0, withPageId = true): Promise<number> {
+ const job = await new MinionQueue(db).add('facts-absorb', { slug: `notes/page-${pageId}`, sourceId: 'default', ...(withPageId ? { page_id: pageId } : {}) }, { queue: 'default' });
+ await db.executeRaw(`UPDATE minion_jobs SET status=$2, finished_at=now() - ($3::double precision * interval '1 hour'),
+ updated_at=now() - ($3::double precision * interval '1 hour'), error_text=CASE WHEN $2='dead' THEN 'revision_conflict' END WHERE id=$1`,
+ [job.id, status, hoursAgo]);
+ return job.id;
+}
+
+async function check(): Promise<Check> {
+ const checks = await factsExtractionEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[];
+ expect(checks).toHaveLength(1);
+ return checks[0]!;
+}
+
+describe('facts_extraction_health separates history from jobs still dead (#6761)', () => {
+ test('ten incidents and no dead job: a historical warning that names no retry and says when it ages out', async () => {
+ await incidents(engine, 10);
+ const result = await check();
+ expect(result.status).toBe('warn');
+ expect(result.message).toContain('10 incidents in 24 h (rolling, ages out at ');
+ expect(result.message).toContain('0 jobs still dead');
+ expect(result.message).toContain('No facts-absorb job is unresolved');
+ expect(result.message).not.toContain('tune the gate');
+ expect(result.message).not.toContain('gbrain jobs retry');
+ expect(result.fix).toBeUndefined();
+ const facts = (result.details as Record<string, any>).facts_absorb;
+ expect(facts).toMatchObject({ incidents_24h: 10, jobs_still_dead: 0, dead_jobs: [] });
+ const agesOut = new Date(facts.ages_out_at).getTime();
+ expect(Math.abs(agesOut - (Date.now() + 24 * 3600_000))).toBeLessThan(5 * 60_000);
+ });
+
+ test('one dead job: says so, names its retry, and the retry fix asks first on the CLI and over MCP', async () => {
+ await incidents(engine, 10);
+ const id = await factsJob(engine, 'dead', 7);
+ const result = await check();
+ expect(result.status).toBe('warn');
+ expect(result.message).toContain('10 incidents in 24 h (rolling, ages out at ');
+ expect(result.message).toContain('1 job still dead');
+ expect(result.message).toContain(`gbrain jobs retry ${id}`);
+ expect((result.details as Record<string, any>).facts_absorb).toMatchObject({ jobs_still_dead: 1,
+ dead_jobs: [{ id, slug: 'notes/page-7', source_id: 'default', status: 'dead' }] });
+ expect(result.fix).toMatchObject({ argv: ['gbrain', 'jobs', 'retry', String(id)], consent: ['paid'], actor: 'agent',
+ mcp: { tool: 'retry_job', arguments: { id } }, verify: { argv: ['gbrain', 'doctor', '--only', 'facts_extraction_health', '--json'] } });
+ expect(finalizeCheckFixes([result], cliRenderContext())[0].fix).toMatchObject({ next: 'ask_user', command: `gbrain jobs retry ${id}` });
+ const callable = finalizeCheckFixes([result], { transport: 'stdio', isCallable: op => op === 'retry_job', preapproved: () => false })[0];
+ expect(callable.fix).toMatchObject({ next: 'ask_user', mcp: { tool: 'retry_job', arguments: { id } } });
+ const notCallable = finalizeCheckFixes([result], { transport: 'stdio', isCallable: () => false, preapproved: () => false })[0];
+ expect(notCallable.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'user' });
+ });
+
+ test('a dead job a later completed job for the same page superseded, or one that died over 24 h ago, is not still dead', async () => {
+ await incidents(engine, 10);
+ await factsJob(engine, 'dead', 3);
+ await factsJob(engine, 'completed', 3);
+ await factsJob(engine, 'dead', 4, 30);
+ const result = await check();
+ expect(result.message).toContain('0 jobs still dead');
+ expect(result.fix).toBeUndefined();
+ });
+
+ test('a backstop-queued job (slug and source, no page_id) is superseded by a later completed job for the same page', async () => {
+ await incidents(engine, 10);
+ await factsJob(engine, 'dead', 6, 0, false);
+ await factsJob(engine, 'completed', 6, 0, false);
+ const result = await check();
+ expect(result.message).toContain('0 jobs still dead');
+ expect(result.fix).toBeUndefined();
+ });
+
+ test('thresholds are unchanged: one incident and one dead job stay ok and still name the job', async () => {
+ await incidents(engine, 1);
+ const id = await factsJob(engine, 'dead', 9);
+ const result = await check();
+ expect(result.status).toBe('ok');
+ expect(result.message).toContain('1 job still dead');
+ expect(result.fix).toMatchObject({ argv: ['gbrain', 'jobs', 'retry', String(id)] });
+ });
+});
+
+describe('fix envelope: a dead job to a verified clear through the real CLI', () => {
+ let home: string;
+ let jobId: number;
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-6761-journey-'));
+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
+ await withEnv({ HOME: home, GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const db = new PGLiteEngine();
+ await db.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });
+ try { await incidents(db, 1); jobId = await factsJob(db, 'dead', 5); } finally { await db.disconnect(); }
+ });
+ }, 180_000);
+ afterAll(() => { if (home) rmSync(home, { recursive: true, force: true }); });
+
+ test('render the envelope, run its argv once the user agrees, run its verify', async () => {
+ const doc = oneDocument(await gb(home, ['doctor', '--only', 'facts_extraction_health', '--json']), 'doctor');
+ const found = (doc.checks as Array<Record<string, any>>).find(c => c.name === 'facts_extraction_health')!;
+ expect(found.message).toContain('1 job still dead');
+ expect(found.fix.next).toBe('ask_user');
+ expect(found.fix.user_message).toContain(`job ${jobId}`);
+ expect(found.fix.argv.slice(0, 4)).toEqual(['gbrain', 'jobs', 'retry', String(jobId)]);
+ const retried = await gb(home, found.fix.argv.slice(1));
+ expect(retried.exitCode).toBe(0);
+ expect(found.fix.verify.argv.slice(0, 5)).toEqual(['gbrain', 'doctor', '--only', 'facts_extraction_health', '--json']);
+ const verified = oneDocument(await gb(home, found.fix.verify.argv.slice(1)), 'doctor verify');
+ const cleared = (verified.checks as Array<Record<string, any>>).find(c => c.name === 'facts_extraction_health')!;
+ expect(cleared.fix).toBeUndefined();
+ expect(cleared.details.facts_absorb).toMatchObject({ jobs_still_dead: 0, dead_jobs: [] });
+ }, 300_000);
+});