Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(conversation-facts): one zero-result factory for the run, the CLI aggregate and the backfill phase

garrytan1bc0f99e7fe7
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 6719322536..e8fafde188 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -17,7 +17,7 @@ src/commands/embed.ts embedAllStale 566 seed: W5 baseline, refactor wave 1 (deco
src/commands/embed.ts runEmbedCore 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 wave 8 lane D1 #5885: stale-drain takes pass call and its watchdog progress counter
src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/extract-conversation-facts.ts processPage 320 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes); +12 fix wave 9 lane P (#5025, D-N2): not-extractable skip call (decision in facts/conversation-skip.ts) and the email-thread segment gap
-src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts)
+src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts); lowered to 355 at the wave-9 follow-ups merge (zero result via emptyExtractConversationFactsResult)
src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/import.ts runImport 972 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts)
src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d3295cc636..b15b15907f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -7,7 +7,7 @@ src/cli.ts 3214 ratchet +3 agent operator gate fixes: repair-failed connect wrap
src/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.ts
src/commands/embed.ts 2227 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); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
-src/commands/extract-conversation-facts.ts 2236 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 path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages)
+src/commands/extract-conversation-facts.ts 2185 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 path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult()
src/commands/extract.ts 2580 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); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page
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 codes
src/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.ts
index 852743c020..8c0d5d7d57 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -1309,6 +1309,17 @@ function nonExtractableAuditFact(
};
}
+/** A result with every counter at zero, the starting point of a run or an aggregate. */
+export function emptyExtractConversationFactsResult(): ExtractConversationFactsResult {
+ return {
+ pages_considered: 0, pages_processed: 0, pages_skipped: 0, pages_skipped_unparsed: 0, pages_skipped_type_mismatch: 0,
+ pages_skipped_insufficient_turns: 0, pages_skipped_since: 0, pages_skipped_too_large: 0, pages_skipped_disappeared: 0,
+ pages_skipped_completed: 0, pages_skipped_non_extractable: 0, pages_marked_non_extractable: 0, pages_skipped_unrecognized_speaker: 0,
+ pages_failed: 0, failed_pages: [], pages_llm_fallback: 0, pages_lock_skipped: 0, orphan_facts_cleaned: 0, segments_processed: 0,
+ facts_extracted: 0, facts_inserted: 0, fallback_slugify_count: 0, resolution_errors: 0,
+ };
+}
+
/**
* Core entry point — one source per call. Caller (CLI / Minion / cycle
* phase) handles multi-source iteration externally.
@@ -1330,31 +1341,7 @@ export async function runExtractConversationFactsCore(
}
const managed = await managedConversationPublisher(engine, sourceId, opts);
- const result: ExtractConversationFactsResult = {
- pages_considered: 0,
- pages_processed: 0,
- pages_skipped: 0,
- pages_skipped_unparsed: 0,
- pages_skipped_type_mismatch: 0,
- pages_skipped_insufficient_turns: 0,
- pages_skipped_since: 0,
- pages_skipped_too_large: 0,
- pages_skipped_disappeared: 0,
- pages_skipped_completed: 0,
- pages_skipped_non_extractable: 0,
- pages_marked_non_extractable: 0,
- pages_skipped_unrecognized_speaker: 0,
- pages_failed: 0,
- failed_pages: [],
- pages_llm_fallback: 0,
- pages_lock_skipped: 0,
- orphan_facts_cleaned: 0,
- segments_processed: 0,
- facts_extracted: 0,
- facts_inserted: 0,
- fallback_slugify_count: 0,
- resolution_errors: 0,
- };
+ const result = emptyExtractConversationFactsResult();
// F2: honor brain-wide kill-switch unless overridden.
if (!opts.overrideDisabled) {
@@ -1997,31 +1984,7 @@ export async function runExtractConversationFacts(
}
// Aggregate result across all sources.
- const aggregate: ExtractConversationFactsResult = {
- pages_considered: 0,
- pages_processed: 0,
- pages_skipped: 0,
- pages_skipped_unparsed: 0,
- pages_skipped_type_mismatch: 0,
- pages_skipped_insufficient_turns: 0,
- pages_skipped_since: 0,
- pages_skipped_too_large: 0,
- pages_skipped_disappeared: 0,
- pages_skipped_completed: 0,
- pages_skipped_non_extractable: 0,
- pages_marked_non_extractable: 0,
- pages_skipped_unrecognized_speaker: 0,
- pages_failed: 0,
- failed_pages: [],
- pages_llm_fallback: 0,
- pages_lock_skipped: 0,
- orphan_facts_cleaned: 0,
- segments_processed: 0,
- facts_extracted: 0,
- facts_inserted: 0,
- fallback_slugify_count: 0,
- resolution_errors: 0,
- };
+ const aggregate = emptyExtractConversationFactsResult();
let totalSpent = 0;
let anyBudgetExhausted = false;
const unpricedModels = new Set<string>();
diff --git a/src/core/cycle/conversation-facts-backfill.ts b/src/core/cycle/conversation-facts-backfill.ts
index b40b5fa077..411ed0cc61 100644
--- a/src/core/cycle/conversation-facts-backfill.ts
+++ b/src/core/cycle/conversation-facts-backfill.ts
@@ -52,6 +52,7 @@ import { withBudgetTracker } from '../ai/gateway.ts';
import { listSources } from '../sources-ops.ts';
import {
runExtractConversationFactsCore,
+ emptyExtractConversationFactsResult,
isAbortError,
type ExtractConversationFactsResult,
} from '../../commands/extract-conversation-facts.ts';
@@ -223,34 +224,7 @@ export async function runPhaseConversationFactsBackfill(
const sourcesNotOwned: string[] = [];
let totalSpent = 0;
- const zeroResult = (): ExtractConversationFactsResult => ({
- pages_considered: 0,
- pages_processed: 0,
- pages_skipped: 0,
- pages_skipped_unparsed: 0,
- pages_skipped_type_mismatch: 0,
- pages_skipped_insufficient_turns: 0,
- pages_skipped_since: 0,
- pages_skipped_too_large: 0,
- pages_skipped_disappeared: 0,
- pages_skipped_completed: 0,
- pages_skipped_non_extractable: 0,
- pages_marked_non_extractable: 0,
- pages_skipped_unrecognized_speaker: 0,
- pages_failed: 0,
- failed_pages: [],
- pages_llm_fallback: 0,
- // v0.41.15.0 (D6 + D11): new counters from the per-page lock
- // + delete-orphans-first replay safety.
- pages_lock_skipped: 0,
- orphan_facts_cleaned: 0,
- segments_processed: 0,
- facts_extracted: 0,
- facts_inserted: 0,
- // #4052: alias_exact resolution counters (required on the result type).
- fallback_slugify_count: 0,
- resolution_errors: 0,
- });
+ const zeroResult = emptyExtractConversationFactsResult;
// #3627: the per-source caps (max_cost_usd / max_walltime_min) were parsed
// but never enforced — one runaway source could eat the whole brain-wide