Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cycle): skip the embed phase when embeddings are disabled (#5536)
garrytan152629b6086a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex d0e89fcf3c..ebdb8f1612 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/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.tssrc/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)-src/core/cycle.ts 3189 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder+src/core/cycle.ts 3192 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +3 #5536: keyless embed phase clean-skips when embedding_disabled is setsrc/core/cycle/synthesize.ts 3293 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option)src/core/cycle/extract-atoms.ts 1834 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesizesrc/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance optiondiff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 314d3a7d19..02c3865988 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -45,7 +45,7 @@import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, statSync, realpathSync } from 'fs';import { join } from 'path';-import { gbrainPath } from './config.ts';+import { gbrainPath, loadConfig } from './config.ts';import type { BrainEngine } from './engine.ts';import { createProgress, type ProgressReporter } from './progress.ts';import { getCliOptions, cliOptsToProgressOptions } from './cli-options.ts';@@ -1577,6 +1577,9 @@ async function runPhaseResolveSymbolEdges(async function runPhaseEmbed(engine: BrainEngine, dryRun: boolean, signal?: AbortSignal): Promise<PhaseResult> {try {+ if (!dryRun && (loadConfig()?.embedding_disabled === true || await engine.getConfig('embedding_disabled') === 'true')) {+ return { phase: 'embed', status: 'skipped', duration_ms: 0, summary: 'embeddings disabled; no provider call made', details: { reason: 'embedding_disabled' } };+ }const { runEmbedCore } = await import('../commands/embed.ts');// #1737: thread the cycle's abort signal so the embed phase (the long,// 10-15 min one) bails within a batch instead of running to completiondiff --git a/test/autopilot-global-maintenance.test.ts b/test/autopilot-global-maintenance.test.tsindex 4275464dfb..d0ab26d441 100644--- a/test/autopilot-global-maintenance.test.ts+++ b/test/autopilot-global-maintenance.test.ts@@ -246,6 +246,37 @@ describe('autopilot-global-maintenance handler stamps last_global_at (PGLite)',return handlers;}+ test('keyless global maintenance skips embed and still completes other work', async () => {+ await engine.setConfig('embedding_disabled', 'true');+ const handlers = await captureHandlers();+ const handler = handlers.get('autopilot-global-maintenance');+ const repoPath = mkdtempSync(join(tmpdir(), 'gbrain-keyless-maintenance-'));+ const result = await handler!({+ id: 4100,+ data: { phases: ['embed', 'orphans'], repoPath },+ signal: undefined,+ });+ const embed = result.report.phases.find((p: any) => p.phase === 'embed');+ expect(embed?.status).toBe('skipped');+ expect(embed?.details.reason).toBe('embedding_disabled');+ expect(result.report.phases.find((p: any) => p.phase === 'orphans')?.status).toBe('ok');+ expect(['ok', 'clean']).toContain(result.report.status);+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).not.toBeNull();+ });++ test('enabled embeddings still report a provider configuration failure', async () => {+ const handlers = await captureHandlers();+ const handler = handlers.get('autopilot-global-maintenance');+ const repoPath = mkdtempSync(join(tmpdir(), 'gbrain-enabled-embed-maintenance-'));+ const result = await handler!({+ id: 4103,+ data: { phases: ['embed'], repoPath },+ signal: undefined,+ });+ expect(result.report.phases.find((p: any) => p.phase === 'embed')?.status).toBe('fail');+ expect(await engine.getConfig(LAST_GLOBAL_AT_KEY)).toBeNull();+ });+test('autopilot-cycle handler normalizes a legacy per-source payload down to freshness phases', async () => {// Pre-v0.46.20 fanout payloads carried NON_GLOBAL_PHASES (mixed +// background). A legacy job draining after upgrade must not re-run thatdiff --git a/test/dream-keyless-exit.test.ts b/test/dream-keyless-exit.test.tsindex d98f14c63c..222ea8cea6 100644--- a/test/dream-keyless-exit.test.ts+++ b/test/dream-keyless-exit.test.ts@@ -14,15 +14,13 @@* a live run):* - chat-dependent phases skip cleanly (`propose_takes` → the gateway's* "no Anthropic API key configured" diagnosis);- * - the embed phase surfaces `EmbeddingDisabledError` as a structured- * phase FAILURE (runEmbedCore's assertEmbeddingEnabled throws; the- * CLI-only clean refusal in runEmbed/isKeylessStaleRefusal does NOT- * cover the cycle's runEmbedCore call) — so the report status is- * 'partial', never 'failed', and `gbrain dream` exits 1 only on- * 'failed' (src/commands/dream.ts). If the cycle's embed phase ever- * learns the same keyless clean-skip the CLI spelling has, the pins- * below move from 'partial'/fail-set-['embed'] to a clean skip —- * update them deliberately in that commit.+ * - the embed phase clean-skips when `embedding_disabled` is set+ * (runPhaseEmbed in src/core/cycle.ts, the cycle-side twin of the+ * CLI's runEmbed/isKeylessStaleRefusal) — status 'skipped', reason+ * 'embedding_disabled', no provider call and no phase error;+ * - the report status is still 'partial' on this fixture because lint+ * and orphans warn on the one-page seed brain, never 'failed', and+ * `gbrain dream` exits 1 only on 'failed' (src/commands/dream.ts).** Test shape mirrors test/agent-scheduler-contract.serial.test.ts (keyless* PGLite brain, real CLI spawn, exit-code assertions). Non-serial on@@ -48,6 +46,7 @@ interface PhaseResultish {phase: string;status: 'ok' | 'warn' | 'fail' | 'skipped';summary: string;+ details?: Record<string, unknown>;error?: { class: string; code: string; message: string };}interface CycleReportish {@@ -175,10 +174,8 @@ describe.skipIf(SKIP)('keyless `gbrain dream` exits 0 (nightly-cron contract)',const report = parseReport(r.stdout);expect(report.schema_version).toBe('1');- // 'partial', never 'failed': the embed phase fails structurally keyless- // (see file docstring) but dream only exits 1 on report.status ===- // 'failed'. A move to 'ok'/'clean' here means the embed phase learned- // the keyless clean-skip — re-pin deliberately, don't loosen.+ // 'partial', never 'failed': lint/orphans warn on the seed brain (see+ // file docstring) and dream only exits 1 on report.status === 'failed'.expect(report.status).toBe('partial');// Anti-vacuity: the cycle really ran the filesystem half — the seed page@@ -197,19 +194,19 @@ describe.skipIf(SKIP)('keyless `gbrain dream` exits 0 (nightly-cron contract)',expect(synthesize.status).toBe('skipped');expect(synthesize.summary).toContain('dream.synthesize.session_corpus_dir is unset');- // The ONLY failing phase is embed, and its error is the documented- // deferred-setup refusal (EmbeddingDisabledError text) — a structured- // posture message, not a crash.- expect(failedPhases(report)).toEqual(['embed']);+ // No phase fails keyless: embed clean-skips on the deferred-setup+ // sentinel instead of surfacing EmbeddingDisabledError as a failure.+ expect(failedPhases(report)).toEqual([]);const embed = byName(report, 'embed');- expect(embed.error?.message ?? '').toContain('--no-embedding');- expect(embed.error?.message ?? '').toContain('deferred setup');+ expect(embed.status).toBe('skipped');+ expect(embed.summary).toBe('embeddings disabled; no provider call made');+ expect(embed.details?.reason).toBe('embedding_disabled');+ expect(report.totals.pages_embedded).toBe(0);- // No phase reports a crash: the embed refusal above is the single error- // in the whole report, and nothing anywhere smells like an unhandled- // programmer error.+ // No phase reports an error at all, and nothing anywhere smells like an+ // unhandled programmer error.for (const p of report.phases) {- if (p.phase !== 'embed') expect(p.error).toBeUndefined();+ expect(p.error).toBeUndefined();const text = `${p.summary} ${p.error?.message ?? ''}`;expect(text).not.toMatch(/TypeError|ReferenceError|is not a function|undefined is not/);}@@ -224,10 +221,11 @@ describe.skipIf(SKIP)('keyless `gbrain dream` exits 0 (nightly-cron contract)',const report = parseReport(r.stdout);expect(report.status).toBe('partial');- // Same degraded posture on re-run — embed is still the only failure and- // nothing new broke because the first cycle already banked its work.- expect(failedPhases(report)).toEqual(['embed']);- expect(byName(report, 'embed').error?.message ?? '').toContain('--no-embedding');+ // Same degraded posture on re-run — embed still clean-skips and nothing+ // new broke because the first cycle already banked its work.+ expect(failedPhases(report)).toEqual([]);+ expect(byName(report, 'embed').status).toBe('skipped');+ expect(byName(report, 'embed').details?.reason).toBe('embedding_disabled');}, 300_000);test('3. the plain (human) spelling exits 0 too, naming the degraded posture', () => {@@ -236,9 +234,10 @@ describe.skipIf(SKIP)('keyless `gbrain dream` exits 0 (nightly-cron contract)',throw new Error(`plain keyless dream exited ${r.exitCode}\nstderr:\n${r.stderr.slice(-2500)}\nstdout:\n${r.stdout.slice(-1500)}`);}expect(r.exitCode).toBe(0);- // printHuman's partial rendering: the header line + the embed refusal- // text so an operator reading the cron log sees WHY embed shows ✗.+ // printHuman's partial rendering: the header line + the embed skip+ // reason so an operator reading the cron log sees WHY embed shows -.expect(r.stdout).toContain('Dream cycle (partial)');- expect(r.stdout).toContain('--no-embedding');+ expect(r.stdout).toContain('embeddings disabled; no provider call made');+ expect(r.stdout).not.toContain('✗ embed');}, 300_000);});