Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor,cycle): links_extraction_lag reports held pages with a retry fix; the cycle extract phase warns on failed pages (GBRA-130 A-1)

garrytana19586105cef
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index ffbced31de..c01d24d8a6 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -14,7 +14,7 @@ import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeco
import { resolveHoursEnv } from '../../../core/env-number.ts';
import { chunkerStamp } from '../../../core/chunkers/code.ts';
import { smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';
-import { extractionLagVerdict, extractionRoutes, readExtractionLag } from '../../../core/extraction-lag.ts';
+import { extractionLagVerdict, extractionRoutes, heldExtractionReport, readExtractionLag } from '../../../core/extraction-lag.ts';
import { isMissingSchemaObject } from '../../../core/utils.ts';
import {
loadStorageConfig,
@@ -96,6 +96,7 @@ export { EXTRACTION_LAG_WARN_PCT_DEFAULT, EXTRACTION_LAG_MIN_PAGES } from '../..
*
* `opts.sourceId` scopes both the denominator and the stale count to one
* source (the explicit-only `--source` parse, like orphan_ratio).
+ * GBRA-130 A-1: held pages (`heldExtractionReport`) are counted apart and warn on any brain size.
*/
export async function checkLinksExtractionLag(
engine: BrainEngine,
@@ -107,11 +108,15 @@ export async function checkLinksExtractionLag(
// #6803 (D1): one statement and one verdict shared with the sync nudge; attendance-blocked pages (#5761: stale
// only by an unresolved attendee, `extract --stale` cannot clear them) are reported apart from lag.
const lag = await readExtractionLag(engine, { sourceId });
- const { total, actionable: stale, attendance_blocked: attendanceBlocked } = lag;
+ const { total, actionable: stale, attendance_blocked: attendanceBlocked, held = 0 } = lag;
if (total === 0) {
return { name, status: 'ok', message: 'Extraction lag not applicable (no pages)' };
}
const verdict = extractionLagVerdict(lag, sourceId);
+ const { note: heldNote, fix: heldFix } = await heldExtractionReport(engine, held, sourceId);
+ if (verdict.skipped && heldFix) {
+ return { name, status: 'warn', message: `Extraction lag not graded (${total} pages, too few to assess)${heldNote}`, details: { total, stale, held, source_id: sourceId ?? null }, fix: heldFix };
+ }
if (verdict.skipped) {
return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)${await smallBrainBacklogNote(engine)}` };
}
@@ -121,17 +126,19 @@ export async function checkLinksExtractionLag(
? `. ${attendanceBlocked} more page(s) wait on unresolved attendees; the next extraction clears each once its attendee's person page exists in the meeting's source (docs/guides/attendance-evidence.md)`
: '';
const mentionNote = lag.mention_due ? `; ${lag.mention_due} page(s) await the mention pass (last pass: ${lag.mention_last_pass_at ?? 'never'})` : '';
- const details: Record<string, unknown> = { total, stale, attendance_blocked: attendanceBlocked, pct: Number(pctStr), warn_pct: verdict.warn_pct, fail_pct: verdict.fail_pct,
+ const details: Record<string, unknown> = { total, stale, attendance_blocked: attendanceBlocked, held, pct: Number(pctStr), warn_pct: verdict.warn_pct, fail_pct: verdict.fail_pct,
source_id: sourceId ?? null, mention_due: lag.mention_due, mention_last_pass_at: lag.mention_last_pass_at };
if (verdict.status === 'ok') {
- return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}${mentionNote}${blockedNote}`, details };
+ return { name, status: held ? 'warn' : 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}${mentionNote}${blockedNote}${heldNote}`, details,
+ ...(heldFix ? { fix: heldFix } : {}) };
}
const { fix, decision, routes } = extractionRoutes(lag, { sourceId, remote: opts?.remote });
details.routes = routes;
details.decision = decision;
const fixText = `Run: ${routes.map(route => `${route.argv.join(' ')} (${route.label})`).join(', or ')}`;
const what = verdict.status === 'fail' ? `need link/timeline extraction (> ${verdict.fail_pct}% fail threshold)` : 'have un-extracted edges';
- return { name, status: verdict.status, message: `${stale}/${total} pages (${pctStr}%)${scope} ${what}${mentionNote}. ${fixText}${blockedNote}`, details, fix };
+ if (heldFix) details.held_fix = heldFix;
+ return { name, status: verdict.status, message: `${stale}/${total} pages (${pctStr}%)${scope} ${what}${mentionNote}. ${fixText}${blockedNote}${heldNote}`, details, fix };
} catch (e) {
// Pre-v112 brain: links_extracted_at column doesn't exist yet. Graceful OK
// (migration/bootstrap adds it; nothing to assess until then).
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index a4e34edb10..30a99ef137 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1424,6 +1424,8 @@ async function runPhaseExtract(
// hiccup must not fail the phase).
let staleRemaining: number | undefined;
let staleDetails: Record<string, unknown> = {};
+ // GBRA-130 A-1: pages the drain could not derive, or a drain its breaker stopped, make the phase warn with the page and code.
+ let staleWarning: string | null = null;
try {
const { extractStaleFromDB } = await import('../commands/extract.ts');
const drained = await extractStaleFromDB(engine, {
@@ -1442,19 +1444,23 @@ async function runPhaseExtract(
stale_timeline_created: drained.timelineCreated,
staleRemaining: drained.staleRemaining, ...(drained.mentions ? { mention_pages: drained.mentions.pages, mention_links_created: drained.mentions.created, mention_due: drained.mentions.remaining, mention_state: drained.mentions.state } : {}),
};
+ const failures = (await import('./cycle/connector-extract.ts')).staleDrainFailures(drained);
+ if (failures) { staleDetails = { ...staleDetails, ...failures.details }; staleWarning = failures.note; }
} catch (e) {
staleDetails = { stale_drain_error: e instanceof Error ? e.message : String(e) };
+ // The breaker stopped a source-scoped drain because most of its pages failed: warn, not a hiccup.
+ if ((e as { code?: unknown } | null)?.code === 'item_failures_systemic') staleWarning = `; the stale drain stopped: ${staleDetails.stale_drain_error}`;
}
const { sweepStaleRelationships } = await import('./link-relationships.ts');
staleDetails = { ...staleDetails, ...(await sweepStaleRelationships(engine)) };
staleDetails = { ...staleDetails, ...(await (await import('./belief/coverage-report.ts')).cycleBeliefReconcile(engine, sourceId)) };
return {
phase: 'extract',
- status: 'ok',
+ status: staleWarning ? 'warn' : 'ok',
duration_ms: 0,
- summary: incremental
+ summary: (incremental
? `${linksCreated} link(s), ${timelineCreated} timeline entries (incremental: ${changedSlugs.length} slugs)`
- : `${linksCreated} link(s), ${timelineCreated} timeline entries`,
+ : `${linksCreated} link(s), ${timelineCreated} timeline entries`) + (staleWarning ?? ''),
details: {
linksCreated, timelineCreated,
pages_processed: result?.pages_processed ?? 0,
diff --git a/src/core/cycle/connector-extract.ts b/src/core/cycle/connector-extract.ts
index 7d1fce2228..d57f385bd8 100644
--- a/src/core/cycle/connector-extract.ts
+++ b/src/core/cycle/connector-extract.ts
@@ -12,11 +12,34 @@
*
* Scope: a per-source cycle drains only its source; a brain-wide cycle (no
* source id) drains every source inside the same budget. Throws propagate to
- * the cycle's phase containment, which records a `fail` result.
+ * the cycle's phase containment, which records a `fail` result. Pages the
+ * drain could not derive (GBRA-130 A-1) make the phase `warn`, naming the
+ * first page, its code and the fix (`staleDrainFailures`, shared with the
+ * file-backed extract phase).
*/
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
import { extractStaleFromDB } from '../../commands/extract.ts';
+import type { LinkExtractionFailure } from '../persistence/links-extraction-holds.ts';
+import type { LinkExtractionSystemic } from '../persistence/links-maintenance.ts';
+
+/**
+ * GBRA-130 A-1: a stale drain that left pages underived (`linkFailed`) or stopped a source (`linkSystemic`) as
+ * phase details and the summary note that makes the extract phase warn; null when every attempted page derived.
+ */
+export function staleDrainFailures(drained: { linkFailed?: number; linkFailures?: LinkExtractionFailure[]; linkSystemic?: LinkExtractionSystemic[] }):
+ { details: Record<string, unknown>; note: string } | null {
+ const systemic = drained.linkSystemic ?? [];
+ if (!drained.linkFailed && !systemic.length) return null;
+ const failed = (drained.linkFailures ?? []).map(f => ({ slug: f.slug, source_id: f.source_id, code: f.code, held: f.held }));
+ const first = drained.linkFailures?.[0];
+ const notes = [
+ ...(first ? [`${drained.linkFailed} page(s) failed link extraction (first: ${first.source_id}:${first.slug}, ${first.code}${first.held ? ', held' : ''}; fix: ${first.fix.argv!.join(' ')})`] : []),
+ ...systemic.map(s => `source ${s.source_id} stopped (${s.code}, most often ${s.reason}; fix the shared cause, then run ${s.fix?.argv?.join(' ')})`),
+ ];
+ return { details: { stale_drain_failed: failed, ...(drained.linkFailed ? { stale_drain_failed_total: drained.linkFailed } : {}),
+ ...(systemic.length ? { stale_drain_systemic: systemic.map(s => ({ source_id: s.source_id, code: s.code, reason: s.reason })) } : {}) }, note: `; ${notes.join('; ')}` };
+}
export async function runPhaseExtractDatabaseOnly(
engine: BrainEngine,
@@ -39,12 +62,13 @@ export async function runPhaseExtractDatabaseOnly(
catchUp: false,
timeBudgetMs: opts.timeBudgetMs,
});
+ const failures = staleDrainFailures(drained);
return {
phase: 'extract',
- status: 'ok',
+ status: failures ? 'warn' : 'ok',
duration_ms: 0,
summary: `${drained.linksCreated} link(s), ${drained.timelineCreated} timeline entries `
- + `(database-only: ${drained.pagesProcessed} stale page(s) drained, ${drained.staleRemaining} remaining)`,
+ + `(database-only: ${drained.pagesProcessed} stale page(s) drained, ${drained.staleRemaining} remaining)${failures?.note ?? ''}`,
details: {
database_only: true,
linksCreated: drained.linksCreated,
@@ -55,6 +79,7 @@ export async function runPhaseExtractDatabaseOnly(
stale_timeline_created: drained.timelineCreated,
staleRemaining: drained.staleRemaining,
...(drained.staleRemaining > 0 ? { stale_backlog: true } : {}),
+ ...failures?.details,
},
};
}
diff --git a/src/core/extraction-lag.ts b/src/core/extraction-lag.ts
index 794976568b..b4732a972c 100644
--- a/src/core/extraction-lag.ts
+++ b/src/core/extraction-lag.ts
@@ -9,12 +9,13 @@
import type { BrainEngine } from './engine.ts';
import { AGENT_TOOL_LIMIT_MS, type Action, type Decision } from './agent-output.ts';
import { cliRouting, pinRouting, type FixRouting } from './fix-routing.ts';
-import { extractionLagStatement } from './engine-sql/pages.ts';
+import { extractionLagStatement, heldLinkExtractionStatement } from './engine-sql/pages.ts';
import { effectiveLinkExtractorWatermark } from './link-extraction-watermark.ts';
import { previewMentionPass } from './mentions/stale.ts';
import { readMentionPolicy } from './mentions/policy.ts';
import { resolveEnvNumber, warnOnceForEnv } from './env-number.ts';
import { isMissingSchemaObject } from './utils.ts';
+import { LINK_HOLD_THRESHOLD_RUNS, linkExtractionRetryFix } from './persistence/links-extraction-holds.ts';
/** Warn threshold (percent of live pages actionable-stale); `GBRAIN_EXTRACTION_LAG_WARN_PCT` overrides it. */
export const EXTRACTION_LAG_WARN_PCT_DEFAULT = 20;
@@ -34,6 +35,8 @@ export interface ExtractionLag {
/** Stale pages extraction can clear (attendance-blocked excluded). */
actionable: number;
attendance_blocked: number;
+ /** GBRA-130 A-1: pages whose link extraction is held after repeated failures (excluded from `actionable`). */
+ held?: number;
/** Pages due for the mention pass; null when the pass is off. */
mention_due: number | null;
mention_last_pass_at: string | null;
@@ -41,20 +44,39 @@ export interface ExtractionLag {
export async function readExtractionLag(engine: BrainEngine, opts: { sourceId?: string; timeoutMs?: number } = {}): Promise<ExtractionLag> {
const versionTs = await effectiveLinkExtractorWatermark(engine);
- const read = async (attendance: boolean) => {
- const { text, params } = extractionLagStatement({ sourceId: opts.sourceId, versionTs, attendance });
- return (await engine.executeRaw<{ total: number; stale: number; attendance_blocked: number }>(text, params, { timeoutMs: opts.timeoutMs ?? 10_000 }))[0];
+ const read = async (attendance: boolean, held: boolean) => {
+ const { text, params } = extractionLagStatement({ sourceId: opts.sourceId, versionTs, attendance, held });
+ return (await engine.executeRaw<{ total: number; stale: number; attendance_blocked: number; held: number }>(text, params, { timeoutMs: opts.timeoutMs ?? 10_000 }))[0];
};
let row;
- try { row = await read(true); } catch (e) {
- if (!isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) throw e;
- row = await read(false);
+ try { row = await read(true, true); } catch (e) {
+ if (isMissingSchemaObject(e, 'column', 'links_extract_failure')) row = await read(true, false).catch(async inner => {
+ if (!isMissingSchemaObject(inner, 'column', 'links_attendance_blocked_revision')) throw inner;
+ return read(false, false);
+ });
+ else if (isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) row = await read(false, false);
+ else throw e;
}
const mention = (await readMentionPolicy(engine)).enabled ? await previewMentionPass(engine, opts.sourceId) : null;
- return { total: Number(row?.total ?? 0), actionable: Number(row?.stale ?? 0), attendance_blocked: Number(row?.attendance_blocked ?? 0),
+ return { total: Number(row?.total ?? 0), actionable: Number(row?.stale ?? 0), attendance_blocked: Number(row?.attendance_blocked ?? 0), held: Number(row?.held ?? 0),
mention_due: mention ? mention.due : null, mention_last_pass_at: mention?.last_pass_at ?? null };
}
+/**
+ * GBRA-130 A-1: doctor's note for pages whose managed link extraction is held (failed
+ * `LINK_HOLD_THRESHOLD_RUNS` runs in a row), naming the first five with their codes, and the fix that retries them
+ * (`gbrain extract --stale [--source-id <id>] --retry-held`). Empty note and no fix when nothing is held.
+ */
+export async function heldExtractionReport(engine: BrainEngine, held: number, sourceId?: string): Promise<{ note: string; fix?: Action }> {
+ if (!held) return { note: '' };
+ const { text, params } = heldLinkExtractionStatement({ sourceId, versionTs: await effectiveLinkExtractorWatermark(engine), limit: 5 });
+ const sample = (await engine.executeRaw<{ slug: string; source_id: string; code: string }>(text, params, { timeoutMs: 10_000 }))
+ .map(row => `${row.source_id}:${row.slug} (${row.code})`);
+ const fix = linkExtractionRetryFix(sourceId, true);
+ return { fix, note: `. ${held} page(s) failed link extraction ${LINK_HOLD_THRESHOLD_RUNS} runs in a row and are held (${sample.join(', ')}${held > sample.length ? ', ...' : ''}); `
+ + `fix the cause the code names, then run ${fix.argv!.join(' ')}` };
+}
+
export interface ExtractionLagVerdict { status: 'ok' | 'warn' | 'fail'; skipped: boolean; pct: number; warn_pct: number; fail_pct: number | null }
/** Doctor warns, and the sync nudge prints, exactly when this says warn or fail. */
@@ -130,12 +152,12 @@ export function extractionNudgeLines(lag: ExtractionLag, opts: { sourceId?: stri
...routes.map(route => `[sync] ${route.argv.join(' ')} — ${route.label}`)];
}
-export interface StaleExtractionCounts { actionable: number; attendance_blocked: number; mention_due: number | null; complete: boolean }
+export interface StaleExtractionCounts { actionable: number; attendance_blocked: number; held: number; mention_due: number | null; complete: boolean }
/** The terminal counts `extract --stale` reports: done when `actionable` is 0 and, with mentions on, `mention_due` is 0. */
export async function staleExtractionCounts(engine: BrainEngine, sourceId?: string): Promise<StaleExtractionCounts> {
const lag = await readExtractionLag(engine, { sourceId });
- return { actionable: lag.actionable, attendance_blocked: lag.attendance_blocked, mention_due: lag.mention_due,
+ return { actionable: lag.actionable, attendance_blocked: lag.attendance_blocked, held: lag.held ?? 0, mention_due: lag.mention_due,
complete: lag.actionable === 0 && (lag.mention_due ?? 0) === 0 };
}
@@ -143,6 +165,7 @@ export async function staleExtractionCounts(engine: BrainEngine, sourceId?: stri
export function formatStaleCounts(c: StaleExtractionCounts): string {
return `Actionable: ${c.actionable} page(s) still need link/timeline extraction` +
(c.attendance_blocked ? `; ${c.attendance_blocked} attendance-blocked page(s) wait on unresolved attendees (extraction cannot clear them)` : '') +
+ (c.held ? `; ${c.held} held page(s) failed extraction ${LINK_HOLD_THRESHOLD_RUNS} runs in a row (gbrain extract --stale --retry-held retries them)` : '') +
(c.mention_due === null ? '' : `; ${c.mention_due} page(s) due for the mention pass`) +
(c.complete ? '. Extraction is complete (raw stale totals are not a completion signal).' : '. Raw stale totals include blocked pages; done when actionable is 0' + (c.mention_due === null ? '.' : ' and mention-due is 0.'));
}