Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): implement --json for extract-conversation-facts (#5704, #5448)
garrytanff3605c2c54a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 45c5cb3d83..620499e86b 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -7,7 +7,7 @@ src/cli.ts 3202 ratchet +2 fix wave 5 (#5401): projections drain help line and tsrc/commands/autopilot.ts 1637 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 + auditsrc/commands/doctor.ts 653 ratchet 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 2190 ratchet 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-src/commands/extract-conversation-facts.ts 2164 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+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.ts 2623 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)src/commands/jobs.ts 658 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)src/commands/serve-http.ts 915 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.tsdiff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 0e4f6b1ce6..6c40847e5a 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -1797,6 +1797,7 @@ interface ParsedArgs {/** v0.41.15.0 (D9): in-process parallel workers per source. */workers?: number;yes?: boolean;+ json?: boolean;help?: boolean;error?: string;}@@ -1807,6 +1808,7 @@ function parseArgs(args: string[]): ParsedArgs {const a = args[i];if (a === '--help' || a === '-h') { out.help = true; continue; }if (a === '--dry-run') { out.dryRun = true; continue; }+ if (a === '--json') { out.json = true; continue; }if (a === '--force') { out.force = true; continue; }if (a === '--yes' || a === '-y') { out.yes = true; continue; }if (a === '--override-disabled') { out.overrideDisabled = true; continue; }@@ -1904,6 +1906,7 @@ Options:safety (delete-orphans-first on each page claim).--override-disabled Bypass facts.extraction_enabled=false brain-wide kill-switch.--background Submit as a Minion job; print job_id; exit (use 'gbrain jobs follow').+ --json Emit the run counters as one JSON object on stdout (diagnostics stay on stderr).--yes Auto-confirm cost preview in non-TTY contexts.--help, -h Show this help.@@ -2072,56 +2075,71 @@ export async function runExtractConversationFacts(const outcome = parsed.dryRun? '(dry run) segmentation only; no facts extracted': `extracted ${aggregate.facts_extracted} facts (${aggregate.facts_inserted} inserted)`;- console.log(- `\nDone: ${outcome} across ${aggregate.segments_processed} segments ` +- `from ${aggregate.pages_processed}/${aggregate.pages_considered} pages ` +- `in ${sourceIds.length} source(s). ` +- `Spent ~$${totalSpent.toFixed(4)}.`,- );- if (aggregate.pages_skipped > 0) {- console.log(` Skipped ${aggregate.pages_skipped} page(s) without eligible segments or outside the selected types:`);- console.log(` ${aggregate.pages_skipped_unparsed} with no parseable speaker turns (retryable); ${aggregate.pages_skipped_type_mismatch} with a type mismatch; ${aggregate.pages_skipped_insufficient_turns} with insufficient turns; ${aggregate.pages_skipped_since} with no eligible segments after --since; ${aggregate.pages_skipped_unrecognized_speaker} declined for speaker attribution.`);- }- if (aggregate.pages_skipped_too_large > 0) {- console.log(` Skipped ${aggregate.pages_skipped_too_large} page(s) exceeding ${MAX_PAGE_BODY_BYTES / 1024 / 1024}MB body cap.`);- }- if (aggregate.pages_skipped_disappeared > 0) {- console.log(` Skipped ${aggregate.pages_skipped_disappeared} page(s) that disappeared between enumeration and fetch.`);- }- if (aggregate.pages_skipped_completed > 0) {- console.log(` Skipped ${aggregate.pages_skipped_completed} page(s) with fresh durable completion outcomes.`);- }- if (aggregate.pages_skipped_non_extractable > 0) {- console.log(` Skipped ${aggregate.pages_skipped_non_extractable} page(s) previously scanned as not extractable.`);- }- if (aggregate.pages_skipped_unrecognized_speaker > 0) {- console.log(` Declined ${aggregate.pages_skipped_unrecognized_speaker} page(s) with unrecognized speaker headings (attribution would be wrong; retried next run).`);- }- if (aggregate.pages_marked_non_extractable > 0) {- console.log(` Marked ${aggregate.pages_marked_non_extractable} page(s) as scanned, not extractable.`);- }- if (aggregate.pages_failed > 0) {- console.error(` Failed ${aggregate.pages_failed} page(s); they remain unfinished and will retry.`);- }- if (aggregate.pages_llm_fallback > 0) {- console.log(` Parsed ${aggregate.pages_llm_fallback} page(s) with the opt-in LLM fallback.`);- }- if (aggregate.pages_lock_skipped > 0) {- console.log(` Skipped ${aggregate.pages_lock_skipped} page(s) held by another worker / process (will retry next run).`);- }- if (aggregate.orphan_facts_cleaned > 0) {- console.log(` Cleaned ${aggregate.orphan_facts_cleaned} orphan fact(s) from prior partial runs (D11 replay safety).`);- }- if (aggregate.fallback_slugify_count > 0) {- console.log(` Preserved ${aggregate.fallback_slugify_count} fact(s) without an entity target after unresolved fallback_slugify.`);- }- if (aggregate.resolution_errors > 0) {- console.log(` Preserved ${aggregate.resolution_errors} fact(s) without an entity target after best-effort resolution errors.`);- }- if (anyBudgetExhausted) {- console.log(unpricedModels.size > 0- ? ` no_pricing: ${[...unpricedModels].join(', ')}. Configure pricing.overrides; raising --max-cost-usd cannot resolve missing pricing.`- : ` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);+ // #5448: --json is a universal cli-flag-registry flag, so scripts add it+ // expecting an envelope. Emit the same counters as the Done: summary as one+ // JSON object on stdout; progress and diagnostics stay on stderr.+ if (parsed.json) {+ console.log(JSON.stringify({+ ...aggregate,+ sources: sourceIds,+ dry_run: parsed.dryRun ?? false,+ outcome,+ spent_usd: totalSpent,+ budget_exhausted: anyBudgetExhausted,+ no_pricing_models: [...unpricedModels],+ }, null, 2));+ } else {+ console.log(+ `\nDone: ${outcome} across ${aggregate.segments_processed} segments ` ++ `from ${aggregate.pages_processed}/${aggregate.pages_considered} pages ` ++ `in ${sourceIds.length} source(s). ` ++ `Spent ~$${totalSpent.toFixed(4)}.`,+ );+ if (aggregate.pages_skipped > 0) {+ console.log(` Skipped ${aggregate.pages_skipped} page(s) without eligible segments or outside the selected types:`);+ console.log(` ${aggregate.pages_skipped_unparsed} with no parseable speaker turns (retryable); ${aggregate.pages_skipped_type_mismatch} with a type mismatch; ${aggregate.pages_skipped_insufficient_turns} with insufficient turns; ${aggregate.pages_skipped_since} with no eligible segments after --since; ${aggregate.pages_skipped_unrecognized_speaker} declined for speaker attribution.`);+ }+ if (aggregate.pages_skipped_too_large > 0) {+ console.log(` Skipped ${aggregate.pages_skipped_too_large} page(s) exceeding ${MAX_PAGE_BODY_BYTES / 1024 / 1024}MB body cap.`);+ }+ if (aggregate.pages_skipped_disappeared > 0) {+ console.log(` Skipped ${aggregate.pages_skipped_disappeared} page(s) that disappeared between enumeration and fetch.`);+ }+ if (aggregate.pages_skipped_completed > 0) {+ console.log(` Skipped ${aggregate.pages_skipped_completed} page(s) with fresh durable completion outcomes.`);+ }+ if (aggregate.pages_skipped_non_extractable > 0) {+ console.log(` Skipped ${aggregate.pages_skipped_non_extractable} page(s) previously scanned as not extractable.`);+ }+ if (aggregate.pages_skipped_unrecognized_speaker > 0) {+ console.log(` Declined ${aggregate.pages_skipped_unrecognized_speaker} page(s) with unrecognized speaker headings (attribution would be wrong; retried next run).`);+ }+ if (aggregate.pages_marked_non_extractable > 0) {+ console.log(` Marked ${aggregate.pages_marked_non_extractable} page(s) as scanned, not extractable.`);+ }+ if (aggregate.pages_failed > 0) {+ console.error(` Failed ${aggregate.pages_failed} page(s); they remain unfinished and will retry.`);+ }+ if (aggregate.pages_llm_fallback > 0) {+ console.log(` Parsed ${aggregate.pages_llm_fallback} page(s) with the opt-in LLM fallback.`);+ }+ if (aggregate.pages_lock_skipped > 0) {+ console.log(` Skipped ${aggregate.pages_lock_skipped} page(s) held by another worker / process (will retry next run).`);+ }+ if (aggregate.orphan_facts_cleaned > 0) {+ console.log(` Cleaned ${aggregate.orphan_facts_cleaned} orphan fact(s) from prior partial runs (D11 replay safety).`);+ }+ if (aggregate.fallback_slugify_count > 0) {+ console.log(` Preserved ${aggregate.fallback_slugify_count} fact(s) without an entity target after unresolved fallback_slugify.`);+ }+ if (aggregate.resolution_errors > 0) {+ console.log(` Preserved ${aggregate.resolution_errors} fact(s) without an entity target after best-effort resolution errors.`);+ }+ if (anyBudgetExhausted) {+ console.log(unpricedModels.size > 0+ ? ` no_pricing: ${[...unpricedModels].join(', ')}. Configure pricing.overrides; raising --max-cost-usd cannot resolve missing pricing.`+ : ` Budget cap reached. Re-run with a higher --max-cost-usd to continue.`);+ }}// v0.41.15.0 (codex #3): exit 3 when pages were skipped due todiff --git a/test/extract-conversation-facts-diagnostics.serial.test.ts b/test/extract-conversation-facts-diagnostics.serial.test.tsindex 3f4742349f..90aff6af4c 100644--- a/test/extract-conversation-facts-diagnostics.serial.test.ts+++ b/test/extract-conversation-facts-diagnostics.serial.test.ts@@ -161,6 +161,34 @@ describe('#5364 diagnostics across workers, sources, CLI, and cycle', () => {}});+ test('#5448: --json (a universal registry flag) prints one JSON envelope on stdout instead of Unknown flag', async () => {+ const log = spyOn(console, 'log').mockImplementation(() => {});+ const error = spyOn(console, 'error').mockImplementation(() => {});+ const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit:${code}`); }) as never);+ try {+ await runExtractConversationFacts(engine, ['--dry-run', '--sleep', '0', '--types', 'conversation', '--json']);+ expect(log.mock.calls).toHaveLength(1);+ const envelope = JSON.parse(String(log.mock.calls[0]![0]));+ expect(envelope).toMatchObject({+ dry_run: true,+ outcome: '(dry run) segmentation only; no facts extracted',+ pages_considered: 10,+ pages_processed: 6,+ segments_processed: 6,+ pages_skipped: 4,+ spent_usd: 0,+ budget_exhausted: false,+ no_pricing_models: [],+ });+ expect([...envelope.sources].sort()).toEqual(['default', 'speaker-a', 'speaker-b']);+ expect(calls).toBe(0);+ } finally {+ exit.mockRestore();+ error.mockRestore();+ log.mockRestore();+ }+ });+test('cycle totals equal exact per-source subsets in dry-run and durable replay', async () => {const dry = await runPhaseConversationFactsBackfill(engine, { dryRun: true });expect(dry.status).toBe('ok');