Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): continue explicit-slug batches after page failures (#6037)
time-attackdb91b22ea483
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bc9c597219..e68d9f23cd 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -7,7 +7,7 @@ src/cli.ts 3212 ratchet +3 agent operator gate fixes: repair-failed connect wrapsrc/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)-src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)+src/commands/extract-conversation-facts.ts 2184 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled pathsrc/commands/extract.ts 2541 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured)src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 322a5e959a..e80fb7f6bd 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -69,6 +69,7 @@ import type { Page } from '../core/types.ts';import {extractFactsFromTurnWithOutcome,isFactsExtractionEnabled,+ type ExtractFailureReason,type ExtractInput,type ExtractedFact,} from '../core/facts/extract.ts';@@ -1145,9 +1146,9 @@ async function processPage(const detail = extraction.error instanceof Error? `: ${extraction.error.message}`: '';- throw new Error(+ throw Object.assign(new Error(`segment ${seg.startIso}..${seg.endIso} extraction failed (${extraction.reason})${detail}`,- );+ ), { extractionReason: extraction.reason });}extracted = extraction.facts;}@@ -1507,7 +1508,12 @@ export async function runExtractConversationFactsCore(result.pages_skipped_type_mismatch++;continue;}- await processPageWithLock(page);+ try {+ await processPageWithLock(page);+ } catch (error) {+ if (isAbortError(error) || error instanceof BudgetExhausted) throw error;+ recordPageFailure(result, sourceId, slug, error);+ }}} else if (opts.slug) {const page = await engine.getPage(opts.slug, { sourceId });@@ -1590,15 +1596,7 @@ export async function runExtractConversationFactsCore(name: 'AbortError',});}- result.pages_failed += poolResult.errored;- for (const failure of poolResult.failures) {- const message = failure.error instanceof Error- ? failure.error.message- : String(failure.error);- process.stderr.write(- `[extract-conversation-facts] ${failure.label} failed: ${message}\n`,- );- }+ for (const failure of poolResult.failures) recordPageFailure(result, sourceId, failure.label, failure.error);processedPagesCount += claimable.length;offset += batch.length;@@ -2173,6 +2171,13 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+// The log names only the closed extraction reason, never provider or error text.+function recordPageFailure(result: ExtractConversationFactsResult, sourceId: string, slug: string, error: unknown): void {+ result.pages_failed++;+ const reason = (error as { extractionReason?: ExtractFailureReason } | null)?.extractionReason ?? 'page_error';+ process.stderr.write(`[extract-conversation-facts] ${slug} failed (${reason}) and stays unfinished; retry: gbrain extract-conversation-facts --source-id ${sourceId} --slug ${slug}\n`);+}+export function isAbortError(err: unknown): boolean {if (!(err instanceof Error)) return false;return err.name === 'AbortError' || /aborted|cancell?ed/i.test(err.message);diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex 1292b825ce..e8ebf021ac 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -529,7 +529,7 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {// --facts: ONE extractor invocation over every touched slug (including// hash-skipped pages — the extractor's version-token gate dedupes work).- let factsSummary: { pages: number; spentUsd?: number } | undefined;+ let factsSummary: { pages: number; pagesFailed: number; spentUsd?: number } | undefined;if (parsed.facts && !parsed.dryRun && result.slugsTouched.length > 0) {const { runIngestFacts } = await import('../core/transcripts/ingest-facts.ts');factsSummary = await runIngestFacts(engine, {@@ -546,8 +546,9 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {console.log(fmtSummary(result));if (factsSummary) {console.log(- `facts: extracted over ${factsSummary.pages} page(s)` +- (factsSummary.spentUsd !== undefined ? `, ~$${factsSummary.spentUsd.toFixed(2)} spent` : ''),+ `facts: attempted ${factsSummary.pages} page(s), ${factsSummary.pagesFailed} failed` ++ (factsSummary.spentUsd !== undefined ? `, ~$${factsSummary.spentUsd.toFixed(2)} spent` : '') ++ (factsSummary.pagesFailed > 0 ? ' (failed pages stay unfinished; stderr names each retry command)' : ''),);}const firstImported = result.files.flatMap((f) => f.sessions).find((s) => !s.error && s.baseSlug);@@ -559,7 +560,7 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {const allFailed =result.files.length > 0 &&result.files.every((f) => f.error !== undefined || (f.drift && f.sessions.length === 0));- if (allFailed) setCliExitVerdict(1);+ if (allFailed || (factsSummary?.pagesFailed ?? 0) > 0) setCliExitVerdict(1);}async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {diff --git a/src/core/transcripts/ingest-facts.ts b/src/core/transcripts/ingest-facts.tsindex 2c29bbd0a9..7b2e6b7a88 100644--- a/src/core/transcripts/ingest-facts.ts+++ b/src/core/transcripts/ingest-facts.ts@@ -27,6 +27,7 @@ import {export interface IngestFactsResult {pages: number;+ pagesFailed: number;spentUsd?: number;skippedDisabled?: boolean;}@@ -42,7 +43,7 @@ export async function runIngestFacts('(facts.extraction_enabled=false) — pages imported, facts skipped',);}- return { pages: 0, skippedDisabled: true };+ return { pages: 0, pagesFailed: 0, skippedDisabled: true };}const pricingOverrides = await loadPricingOverrides(engine);@@ -51,12 +52,12 @@ export async function runIngestFacts(label: 'transcripts-ingest-facts',pricingOverrides,});- await withBudgetTracker(tracker, () =>+ const result = await withBudgetTracker(tracker, () =>runExtractConversationFactsCore(engine, {sourceId: opts.sourceId,slugs: opts.slugs,budgetTracker: tracker,}),);- return { pages: opts.slugs.length, spentUsd: tracker.totalSpent };+ return { pages: opts.slugs.length, pagesFailed: result.pages_failed, spentUsd: tracker.totalSpent };}diff --git a/test/extract-conversation-facts.test.ts b/test/extract-conversation-facts.test.tsindex 3d2ab036bd..41e9f7a11d 100644--- a/test/extract-conversation-facts.test.ts+++ b/test/extract-conversation-facts.test.ts@@ -47,6 +47,9 @@ import {import { _resetLlmCacheForTests } from '../src/core/conversation-parser/llm-base.ts';import { BudgetExhausted } from '../src/core/budget/budget-tracker.ts';import { loadOpCheckpoint } from '../src/core/op-checkpoint.ts';+import { runIngestFacts } from '../src/core/transcripts/ingest-facts.ts';+import { runTranscripts } from '../src/commands/transcripts.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';// ---------------------------------------------------------------------------// pageTypesForAllowed — logical→concrete page-type expansion.@@ -329,6 +332,7 @@ describe('runExtractConversationFactsCore', () => {let mainChatCalls = 0;let chatStopReason: ChatResult['stopReason'] = 'end';let chatTextOverride: string | null = null;+ let chatMalformedOnCall: number | null = null;let embeddedTexts: string[] = [];let fallbackCalls = 0;let fallbackContents: string[] = [];@@ -389,8 +393,10 @@ describe('runExtractConversationFactsCore', () => {chatHook = null;if (hook) await hook();callIndex++;+ const malformedCall = chatMalformedOnCall !== null &&+ (mainChatCalls === chatMalformedOnCall || mainChatCalls === chatMalformedOnCall + 1);return {- text: chatTextOverride ?? JSON.stringify({+ text: malformedCall ? JSON.stringify({ facts: [{ fact: 123, kind: 'fact' }] }) : chatTextOverride ?? JSON.stringify({facts: [{fact: `synthetic fact #${callIndex}`,kind: 'event',@@ -435,6 +441,7 @@ describe('runExtractConversationFactsCore', () => {mainChatCalls = 0;chatStopReason = 'end';chatTextOverride = null;+ chatMalformedOnCall = null;embeddedTexts = [];fallbackCalls = 0;fallbackContents = [];@@ -1511,6 +1518,129 @@ describe('runExtractConversationFactsCore', () => {expect(Number(terminals[0]?.count ?? 0)).toBe(0);});+ // #6033: one failed page in an explicit slug batch is contained, counted+ // and left unfinished; the rest of the batch still runs.+ async function seedBatch(slugs: string[]): Promise<void> {+ for (const slug of slugs) {+ await engine.putPage(slug, {+ type: 'conversation',+ title: slug,+ compiled_truth: [+ fmt('Alice Example', '2024-03-15', '9:00 AM', 'We signed the contract.'),+ fmt('Bob Demo', '2024-03-15', '9:01 AM', 'The contract is signed.'),+ ].join('\n'),+ timeline: '',+ frontmatter: {},+ });+ }+ }++ async function captureStderr<T>(fn: () => Promise<T>): Promise<{ value: T; err: string }> {+ const writes: string[] = [];+ const originalWrite = process.stderr.write;+ process.stderr.write = ((chunk: string | Uint8Array) => {+ writes.push(String(chunk));+ return true;+ }) as typeof process.stderr.write;+ try {+ return { value: await fn(), err: writes.join('') };+ } finally {+ process.stderr.write = originalWrite;+ }+ }++ test('explicit slugs continue after a malformed page and leave it unfinished (#6033)', async () => {+ const slugs = ['conversations/batch-first', 'conversations/batch-malformed', 'conversations/batch-last'];+ await seedBatch(slugs);+ chatMalformedOnCall = 2;++ const { value: result, err } = await captureStderr(() =>+ runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, sleepMs: 0 }));+ expect(result.pages_failed).toBe(1);+ expect(result.pages_processed).toBe(2);+ expect(err).toContain('conversations/batch-malformed failed (malformed_output) and stays unfinished; ' ++ 'retry: gbrain extract-conversation-facts --source-id default --slug conversations/batch-malformed');+ const terminal = await engine.executeRaw<{ slug: string }>(+ `SELECT source_markdown_slug AS slug FROM facts WHERE source = $1 ORDER BY source_markdown_slug`,+ [TERMINAL_AUDIT_SOURCE],+ );+ expect(terminal.map(r => r.slug)).toEqual(['conversations/batch-first', 'conversations/batch-last']);++ chatMalformedOnCall = null;+ const retry = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, sleepMs: 0 });+ expect(retry.pages_processed).toBe(1);+ expect(retry.pages_skipped_completed).toBe(2);+ expect(retry.pages_failed).toBe(0);+ });++ test('explicit-slug failure log omits provider error details (#6033)', async () => {+ chatFailure = new Error('provider response included api_key=private-value');+ const { value: result, err } = await captureStderr(() => runExtractConversationFactsCore(engine, {+ sourceId: 'default',+ slugs: ['conversations/imessage/alice-example'],+ sleepMs: 0,+ }));+ expect(result.pages_failed).toBe(1);+ expect(err).toContain('conversations/imessage/alice-example failed (provider_error)');+ expect(err).not.toContain('private-value');+ });++ test('a budget stop in an explicit slug batch halts the batch instead of counting failures (#6033)', async () => {+ const slugs = ['conversations/batch-first', 'conversations/batch-last'];+ await seedBatch(slugs);+ chatFailure = new BudgetExhausted('reserve denied', { reason: 'cost', spent: 5, cap: 5 });+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test' }, async () => {+ const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, sleepMs: 0 });+ expect(result.budget_exhausted).toBe(true);+ expect(result.pages_failed).toBe(0);+ expect(mainChatCalls).toBe(1);+ });+ });++ test('caller cancellation in an explicit slug batch stops the batch (#6033)', async () => {+ const slugs = ['conversations/batch-first', 'conversations/batch-last'];+ await seedBatch(slugs);+ const controller = new AbortController();+ const cancellation = Object.assign(new Error('caller cancelled'), { name: 'AbortError' });+ chatHook = async () => { controller.abort(cancellation); };+ await expect(+ runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, sleepMs: 0 }, controller.signal),+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(mainChatCalls).toBe(1);+ });++ test('transcript ingest reports failed explicit-slug extraction (#6033)', async () => {+ chatTextOverride = JSON.stringify({ facts: [{ fact: 123, kind: 'fact' }] });+ const result = await runIngestFacts(engine, {+ sourceId: 'default',+ slugs: ['conversations/imessage/alice-example'],+ quiet: true,+ });+ expect(result).toMatchObject({ pages: 1, pagesFailed: 1 });+ });++ test.each([+ { name: 'a failed page exits 1', malformed: true, exit: 1, failed: 1 },+ { name: 'no failed page exits 0', malformed: false, exit: 0, failed: 0 },+ ])('transcripts ingest --facts: $name (#6033)', async (c) => {+ if (c.malformed) chatTextOverride = JSON.stringify({ facts: [{ fact: 123, kind: 'fact' }] });+ const fixture = join(import.meta.dir, 'fixtures', 'transcripts', 'codex-rollout.jsonl');+ const out: string[] = [];+ const originalLog = console.log;+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };+ _resetCliExitVerdictForTests();+ try {+ await captureStderr(() => runTranscripts(engine, ['ingest', fixture, '--facts', '--source-id', 'default', '--json']));+ const doc = JSON.parse(out.join('\n')) as { facts: { pages: number; pagesFailed: number } };+ expect(doc.facts).toMatchObject({ pages: 1, pagesFailed: c.failed });+ expect(currentExitCode()).toBe(c.exit);+ } finally {+ console.log = originalLog;+ _resetCliExitVerdictForTests();+ process.exitCode = 0;+ }+ });+test('insert failure leaves no terminal and retries from a clean replay', async () => {const engineAny = engine as any;const originalInsertFacts = engineAny.insertFacts;