Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(cli): D2 --json guard on doctor (incl. --remediate, --remediation-plan, no brain), sync and embed
garrytan302b63668703
diff --git a/scripts/agent-contract-baselines/stdio-inherit.tsv b/scripts/agent-contract-baselines/stdio-inherit.tsvindex f7b24fc2c6..4863b0b825 100644--- a/scripts/agent-contract-baselines/stdio-inherit.tsv+++ b/scripts/agent-contract-baselines/stdio-inherit.tsv@@ -6,6 +6,5 @@ src/commands/migrations/v0_11_0.ts 2src/commands/skillopt.ts 1src/commands/takes.ts 1src/commands/upgrade.ts 6-src/core/cli-options.ts 1src/core/minions/child-worker-supervisor.ts 1src/core/thin-client-upgrade-prompt.ts 1diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a3bdad4885..4eb2c5bdf7 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -6,7 +6,7 @@src/cli.ts 3162 ratchet +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResultsrc/commands/autopilot.ts 1639 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)src/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.ts-src/commands/embed.ts 2217 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; +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/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.ts 2528 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)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)diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex fe1c911ede..2533e4a360 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -45,7 +45,7 @@"test/checkpoint-harvest.serial.test.ts": 9,"test/cli-error-render.serial.test.ts": 3,"test/cli-help-without-brain.serial.test.ts": 16,- "test/cli-json-guard.serial.test.ts": 6,+ "test/cli-json-guard.serial.test.ts": 17,"test/cli-util-prompt.serial.test.ts": 3,"test/code-callers-pin.serial.test.ts": 11,"test/code-def-refs-pin.serial.test.ts": 12,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 665fa41338..b2423c79d6 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -320,7 +320,7 @@"serial:test/checkpoint-harvest.serial.test.ts": 4977,"serial:test/cli-error-render.serial.test.ts": 3000,"serial:test/cli-help-without-brain.serial.test.ts": 9329,- "serial:test/cli-json-guard.serial.test.ts": 6000,+ "serial:test/cli-json-guard.serial.test.ts": 17000,"serial:test/cli-util-prompt.serial.test.ts": 2644,"serial:test/code-callers-pin.serial.test.ts": 2975,"serial:test/code-def-refs-pin.serial.test.ts": 5089,diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.tsindex 905f20a8bb..0c28b03182 100644--- a/src/cli/cli-error.ts+++ b/src/cli/cli-error.ts@@ -20,6 +20,7 @@ import {import { redactUrlsInText } from '../core/url-redact.ts';import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';import { suggestNearest } from '../core/levenshtein.ts';+import { isConsentRefusal, printConsentRefusal } from '../core/consent.ts';import { findCliCommand } from './command-table.ts';export interface CliErrorWriteOpts {@@ -43,6 +44,7 @@ export function cliCommandOf(argv: readonly string[] = process.argv.slice(2)): s/** Render and write `e`; returns the exit code (the caller exits or sets the verdict). */export function writeCliError(e: unknown, command: string, opts: CliErrorWriteOpts = {}): number {const json = opts.json ?? jsonRequested(opts.argv ?? process.argv.slice(2));+ if (isConsentRefusal(e)) return printConsentRefusal(e, { json });const r = renderCliError(e, { json, command, tty: process.stderr.isTTY === true });let stderr = r.stderr;if (r.stdout !== undefined) {diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 164d0a5e85..9480d7d362 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -203,7 +203,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'apply-migrations', phase: 'pre-connect', thinClient: 'refuse', load: () => import('./commands/apply-migrations.ts') },{ name: 'repair-jsonb', phase: 'pre-connect', thinClient: 'refuse', load: () => import('./commands/repair-jsonb.ts') },{ name: 'skillpack-check', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/skillpack-check.ts') },- { name: 'doctor', phase: 'pre-connect-own-engine', thinClient: 'none', load: () => import('./commands/doctor.ts') },+ { name: 'doctor', phase: 'pre-connect-own-engine', thinClient: 'none', json: 'document', load: () => import('./commands/doctor.ts') },// CLI_ONLY: cathedral-5: deterministic compiled-context views (engine-needing; refused on thin// clients; help answers engine-free).// selfHelp: cathedral-5: compile-context ships its own detailed usage (targets, check-mode exit@@ -241,7 +241,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'import', phase: 'post-connect', thinClient: 'none', load: () => import('./commands/import.ts') },{ name: 'export', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/export.ts') },{ name: 'files', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/files.ts') },- { name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/embed.ts') },+ { name: 'embed', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/embed.ts') },{ name: 'serve', phase: 'post-connect', thinClient: 'refuse', load: () => import('./commands/serve.ts') },// thin client: Agent-bootstrap [CX2-5]: the maintenance sweep runs against the LOCAL engine (the// serve-resident sweep's trusted CLI entry). On a thin client it would fabricate a scratch PGLite@@ -277,7 +277,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// selfHelp: v0.37 fix wave (Lane D.4 + CDX2-12): sync's --no-embed flag was unreachable via help// because the dispatcher's generic CLI-only short-circuit fired before runSync could print its own// usage block. Adding `sync` here routes `gbrain sync --help` into runSync.- { name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/sync.ts') },+ { name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', load: () => import('./commands/sync.ts') },// selfHelp: #3834: extract ships detailed help for its mode-specific flags. Keep the generic// CLI-only stub from hiding that contract.{ name: 'extract', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/extract.ts') },diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.tsindex 6d9f2a64fe..85e5440646 100644--- a/src/cli/commands/embed.ts+++ b/src/cli/commands/embed.ts@@ -4,7 +4,8 @@* handleCliOnly switch (refactor wave 1, W4 cli); the record lives in* src/cli/command-table.ts.*/-import { setCliExitVerdict } from '../../core/cli-force-exit.ts';+import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';+import { lastBackgroundJob } from '../../core/cli-options.ts';import { BUDGET_STOP_EXIT_CODE } from '../../core/exit-codes.ts';import type { BrainEngine } from '../../core/engine.ts';import type { CliDispatchContext } from '../command-table.ts';@@ -17,6 +18,12 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC// and cron/CI/health gates read total silence as success. Surface// non-zero on failures > 0. (undefined = backgrounded via --background.)const embedResult = await runEmbed(engine, args, SELECTED_CONFIG_BY_ENGINE.get(engine) ?? null);+ // D2: under --json the result is the one document (a budget stop carries+ // remaining_stale + resume_command and exits 11; --background names its job).+ if (jsonRequested(args)) {+ const job = lastBackgroundJob();+ await writeStdoutFinal(`${JSON.stringify(embedResult ?? { status: 'backgrounded', ...(job !== null ? { job_id: job } : {}) }, null, 2)}\n`);+ }if (embedResult && embedResult.failures > 0) {setCliExitVerdict(1);} else if (embedResult && 'reason' in embedResult && embedResult.reason === 'time_budget') {diff --git a/src/cli/commands/sync.ts b/src/cli/commands/sync.tsindex b24ef379dc..2ae535c56e 100644--- a/src/cli/commands/sync.ts+++ b/src/cli/commands/sync.ts@@ -5,8 +5,19 @@* src/cli/command-table.ts.*/import type { BrainEngine } from '../../core/engine.ts';+import { opError } from '../../core/ops/contract.ts';export async function run(engine: BrainEngine, args: string[]): Promise<void> {- const { runSync } = await import('../../commands/sync.ts');- await runSync(engine, args);+ const { runSync, SyncLockBusyError } = await import('../../commands/sync.ts');+ try {+ await runSync(engine, args);+ } catch (e) {+ // D1/D2: a busy sync lock is a retryable sync_in_progress refusal (its+ // message names the holder and the --break-lock recovery), not an+ // unclassified internal error.+ if (!(e instanceof SyncLockBusyError)) throw e;+ throw opError('sync_in_progress', e.message,+ `Wait for the running sync to finish and retry. If its holder is dead, run \`gbrain sync --break-lock\` (with the same --source).`,+ { reason: 'lock_busy', detail: e.lockKey });+ }}diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 7072343caa..d23a6aee5f 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../core/engine.ts';-import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';import { getIdleBlockers } from '../core/migrate.ts';import { parseFlags as parseSkillsDirFlags, resolveSkillsDir } from './check-resolvable.ts';import { createProgress } from '../core/progress.ts';@@ -529,7 +529,7 @@ function outputResults(const score = report.health_score;if (json) {- console.log(JSON.stringify(report));+ void writeJsonDocument(JSON.stringify(report)); // D2: the one --json documentreturn hasFail;}@@ -607,7 +607,7 @@ function outputResults(async function runLocksCheck(engine: BrainEngine | null, jsonOutput: boolean): Promise<void> {if (!engine) {if (jsonOutput) {- console.log(JSON.stringify({ status: 'unavailable', reason: 'no_engine' }));+ void writeJsonDocument(JSON.stringify({ status: 'unavailable', reason: 'no_engine' }));} else {console.log('gbrain doctor --locks requires a database connection. Configure a URL and retry.');}@@ -616,7 +616,7 @@ async function runLocksCheck(engine: BrainEngine | null, jsonOutput: boolean): Pif (engine.kind !== 'postgres') {if (jsonOutput) {- console.log(JSON.stringify({ status: 'not_applicable', engine: engine.kind }));+ void writeJsonDocument(JSON.stringify({ status: 'not_applicable', engine: engine.kind }));} else {console.log(`gbrain doctor --locks is Postgres-only. Current engine: ${engine.kind}. No blockers possible (no connection pool).`);}@@ -626,7 +626,7 @@ async function runLocksCheck(engine: BrainEngine | null, jsonOutput: boolean): Pconst blockers = await getIdleBlockers(engine);if (jsonOutput) {- console.log(JSON.stringify({ status: blockers.length === 0 ? 'ok' : 'blockers_found', blockers }, null, 2));+ void writeJsonDocument(JSON.stringify({ status: blockers.length === 0 ? 'ok' : 'blockers_found', blockers }, null, 2));if (blockers.length > 0) process.exit(1);return;}diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex fdda05f0cc..e21d579778 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -23,7 +23,7 @@* there is no repair step to run, or a resume is refused.*/import type { BrainEngine } from '../../core/engine.ts';-import { setCliExitVerdict } from '../../core/cli-force-exit.ts';+import { setCliExitVerdict, writeJsonDocument } from '../../core/cli-force-exit.ts';import { clearHealthMemo } from '../../core/health-memo.ts';import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';import type { RepairPlanStep } from '../../core/remediation/repairs.ts';@@ -99,7 +99,7 @@ export async function runRemediationPlan(engine: BrainEngine, args: string[]): Pconst targetScore = parseIntFlag(args, '--target-score') ?? 90;const plan = await computeRemediationPlan(engine, { targetScore, repairs: { noEmbed: args.includes('--no-embed') } });if (args.includes('--json')) {- console.log(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),+ await writeJsonDocument(JSON.stringify({ ...plan, plan: plan.plan.map(step => ({ ...step, command: jobStepCommand(step) })),combined_command: combinedRemediateCommand(plan, targetScore) }, null, 2));return;}@@ -315,7 +315,7 @@ export async function runRemediate(engine: BrainEngine, args: string[]): Promiseconst healthy = !dryRun && after.every(f => f.state === 'ok');if (jsonOutput) {- console.log(JSON.stringify({ ...result, findings, repairs_completed: repairsCompleted, healthy, exit_status: exitStatus }, null, 2));+ await writeJsonDocument(JSON.stringify({ ...result, findings, repairs_completed: repairsCompleted, healthy, exit_status: exitStatus }, null, 2));} else {if (dryRun && result.submitted.length > 0) {console.log(`[remediate --dry-run] Would run ${result.submitted.length} step(s):`);diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 39ed93991c..2b1fca77a0 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -21,6 +21,7 @@ import {import { createProgress, type ProgressReporter } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';+import { writeCliError } from '../cli/cli-error.ts';import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';import { loadConfig, type GBrainConfig } from '../core/config.ts';import { slog, serr } from '../core/console-prefix.ts';@@ -994,6 +995,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConfreturn result;} catch (e) {if (progressStarted) progress.finish();+ if (args.includes('--json')) process.exit(writeCliError(e, 'embed', { json: true })); // D2: one v1 envelope on stdout// v0.41.6.0 D1: preflight throws EmbeddingCredentialError; surface the// paste-ready userMessage instead of the bare exception text.const { EmbeddingCredentialError } = await import('../core/embed-preflight.ts');diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex fcb8a423a2..86bf1b633a 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -33,6 +33,10 @@ import {isFailedPartial,} from './report.ts';import { runSyncTrigger } from './trigger.ts';+import { writeJsonDocument } from '../../core/cli-force-exit.ts';++/** D2: under the `--json` guard only writeStdoutFinal reaches fd 1 (writeJsonDocument). */+const emitJson = (text: string): void => { void writeJsonDocument(text); };type SyncAllSourceRow = { id: string; name: string; local_path: string | null; config: Record<string, unknown>; last_commit: string | null; chunker_version: string | null };@@ -133,7 +137,7 @@ async function runSyncBreakLock(// (no local_path) don't hold sync locks.const activeSources = sources.filter((s) => s.local_path);if (activeSources.length === 0) {- if (jsonOut) console.log(JSON.stringify({ status: 'no_sources' }));+ if (jsonOut) emitJson(JSON.stringify({ status: 'no_sources' }));else console.error('No active sources to break-lock against.');process.exit(0);}@@ -234,7 +238,7 @@ async function resolveCliSyncSource(catch (error) {if (!syncAll) {if (!(error instanceof EmbeddingCredentialError)) throw error;- if (jsonOut) console.log(JSON.stringify({ status: 'embedding_credentials_missing', diagnosis: error.diagnosis }));+ if (jsonOut) emitJson(JSON.stringify({ status: 'embedding_credentials_missing', diagnosis: error.diagnosis }));else console.error(`\n${error.userMessage}\n`);process.exit(1);}@@ -344,7 +348,7 @@ async function runSyncAll(if (runnableSources.length === 0) {if (jsonOut) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({schema_version: 1,sources: skippedMissingPath.slice()@@ -667,7 +671,7 @@ function emitSyncAllEnvelope(input: {? { embed_backfill: embedBackfillBySource.get(r.sourceId) }: {}),}));- console.log(JSON.stringify({+ emitJson(JSON.stringify({schema_version: 1,sources: sortedSources,parallel: effectiveParallel,@@ -843,7 +847,7 @@ async function runSingleSourceSync(}}if (jsonOut) {- console.log(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),+ emitJson(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),...(result.managedWrite ? { managed_write: result.managedWrite } : {}) }));}return;diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex f898c093f2..e245a2f6ff 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -505,6 +505,34 @@ const ROWS: Row[] = [error: e.code, code: e.code, message: e.problem, why: e.cause_text, suggestion: e.fix, docs: e.doc_url,}),},+ {+ // A keyless brain (`init --no-embedding`) asked to embed: a capability+ // disabled by choice, not a server fault.+ match: named('EmbeddingDisabledError'),+ map: (e: Error) => ({+ error: 'embedding_disabled', code: 'embedding_disabled', reason: 'disabled_by_choice', message: e.message.split('\n')[0],+ suggestion: 'Keyword search keeps working without embeddings. To turn them on, see `gbrain embeddings enable --help`.',+ fix: { argv: ['gbrain', 'embeddings', 'enable', '--help'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows the command that enables embeddings for this brain and what it costs.' },+ }),+ },+ {+ // embed preflight: no usable embedding credentials (userMessage is the paste-ready diagnosis).+ match: named('EmbeddingCredentialError'),+ map: (e: Error & { userMessage?: string }) => {+ const [first, ...rest] = (e.userMessage ?? e.message).split('\n').filter(l => l.trim());+ return { error: 'unavailable', code: 'unavailable', reason: 'embedding_credentials', message: first ?? e.message,+ suggestion: rest.join(' ').trim() || 'Configure an embedding provider key, then retry.' };+ },+ },+ {+ match: named('EmbeddingDimMismatchError'),+ map: (e: Error & { recipeMessage?: string }) => {+ const [first, ...rest] = (e.recipeMessage ?? e.message).split('\n').filter(l => l.trim());+ return { error: 'embedding_width_mismatch', code: 'embedding_width_mismatch', message: first ?? e.message,+ suggestion: rest.join(' ').trim() || 'Run `gbrain doctor --json` to see the brain\'s vector width.' };+ },+ },// ── generic rows: the DB classifier runs before these ──{match: e => named('AIConfigError')(e) || named('AITransientError')(e),diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.tsindex bf7e4e3f6b..e79fe9682b 100644--- a/src/core/cli-force-exit.ts+++ b/src/core/cli-force-exit.ts@@ -825,6 +825,18 @@ export function jsonRequested(argv: readonly string[]): boolean {return false;}+/**+ * D2: a command's `--json` document. Under the guard it is THE final document+ * (writeStdoutFinal); unguarded (an undeclared command, an in-process caller,+ * a test) it goes through the caller's legacy writer, console.log by default,+ * so those paths see no change.+ */+export function writeJsonDocument(text: string, unguarded: (text: string) => void = t => console.log(t)): Promise<void> {+ if (jsonGuardMode) return writeStdoutFinal(text.endsWith('\n') ? text : `${text}\n`);+ unguarded(text);+ return Promise.resolve();+}+/** One NDJSON line on fd 1 (the only stdout path for `json: 'ndjson'` commands under the guard). */export async function writeNdjsonLine(line: unknown): Promise<void> {const status = (line as { status?: unknown } | null)?.status;diff --git a/src/core/cli-options.ts b/src/core/cli-options.tsindex 7042444c27..adc1c7c36d 100644--- a/src/core/cli-options.ts+++ b/src/core/cli-options.ts@@ -434,6 +434,10 @@ export interface MaybeBackgroundOpts {source?: string;}+let lastBackgroundJobId: number | null = null;+/** D2: the job `maybeBackground` submitted in this process (for `--json` result documents). */+export function lastBackgroundJob(): number | null { return lastBackgroundJobId; }+/*** If `--background` is in args, submit a Minion job and return true* (caller should exit). Otherwise return false (caller does inline work).@@ -475,16 +479,15 @@ export async function maybeBackground(opts: MaybeBackgroundOpts): Promise<booleamax_attempts: 2,});process.stdout.write(`job_id=${job.id}\n`);+ lastBackgroundJobId = job.id;if (follow) {// exec `gbrain jobs follow <id>` so the user sees live stream// without losing the durable-queue submission.- const { spawn } = await import('child_process');+ const { spawnCliChild } = await import('./cli-force-exit.ts');const cmd = process.argv[0] ?? 'bun';const script = process.argv[1] ?? '';- const child = spawn(cmd, [script, 'jobs', 'follow', String(job.id)], {- stdio: 'inherit',- });+ const child = spawnCliChild(cmd, [script, 'jobs', 'follow', String(job.id)]);await new Promise<void>((resolve) => child.on('exit', () => resolve()));}return true; // caller exitsdiff --git a/src/core/consent.ts b/src/core/consent.tsindex 8d8a8cb123..9186c5f72e 100644--- a/src/core/consent.ts+++ b/src/core/consent.ts@@ -20,6 +20,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname } from 'node:path';import { CONTRACT_VERSION, cliRenderContext, renderAction, shellQuote, type Action, type Actor, type CliErrorRender, type Effect, type RenderContext, type RenderedAction } from './agent-output.ts';import { agentBlock } from './agent-markers.ts';+import { writeJsonDocument } from './cli-force-exit.ts';import { recordAgentContractEvent } from './agent-contract-log.ts';import { gbrainPath } from './config.ts';import { PREAPPROVE_PAID_MAX_USD_PER_RUN, PREAPPROVE_PERSISTENT_INSTALL, preapprovalCommand, readConsentPreapprovals, type ConsentPreapprovals } from './consent-preapproval.ts';@@ -355,7 +356,8 @@ export function renderConsentRefusal(p: ConfirmationPayload, opts: { json: boole/** Write a refusal and return its exit code (3). The one way a CLI handler reports `confirmation_required`. */export function printConsentRefusal(e: ConsentRefusal, opts: { json: boolean }): number {const out = renderConsentRefusal(e.consent, opts);- if (out.stdout) process.stdout.write(out.stdout);+ // D2: under the --json guard only writeStdoutFinal reaches fd 1 (the payload / [AGENT] block is the final document).+ if (out.stdout) void writeJsonDocument(out.stdout, t => process.stdout.write(t));if (out.stderr) process.stderr.write(out.stderr);return out.exitCode;}diff --git a/src/core/doctor-remote.ts b/src/core/doctor-remote.tsindex ad89153407..41022f03b4 100644--- a/src/core/doctor-remote.ts+++ b/src/core/doctor-remote.ts@@ -18,6 +18,7 @@ import { callRemoteTool, RemoteMcpError, unpackToolResult } from './mcp-client.timport { isScopeErrorCode } from './error-catalogue.ts';import { safeCompare, driftLevel, loadPromptState } from './thin-client-upgrade-prompt.ts';import { VERSION } from '../version.ts';+import { writeJsonDocument } from './cli-force-exit.ts';export interface RemoteCheck {name: string;@@ -47,7 +48,7 @@ export async function runRemoteDoctor(config: GBrainConfig, args: string[]): Proconst report = await collectRemoteDoctorReport(config);if (jsonOutput) {- console.log(JSON.stringify(report));+ await writeJsonDocument(JSON.stringify(report));} else {printHumanReport(report);}diff --git a/src/core/sync-lock.ts b/src/core/sync-lock.tsindex 327933fd26..5be79046b4 100644--- a/src/core/sync-lock.ts+++ b/src/core/sync-lock.ts@@ -6,6 +6,10 @@*/import type { BrainEngine } from './engine.ts';import type { SyncResult } from '../commands/sync.ts';+import { writeJsonDocument } from './cli-force-exit.ts';++/** D2: under the `--json` guard only writeStdoutFinal reaches fd 1 (writeJsonDocument). */+const emitJson = (text: string): void => { void writeJsonDocument(text); };/*** v0.42.x (#1794, Part B): typed lock-busy error so callers can distinguish a@@ -89,7 +93,7 @@ export async function runBreakLock(try { snap = await inspectLock(engine, lockKey); }catch (e) {const msg = e instanceof Error ? e.message : String(e);- if (opts.json) console.log(JSON.stringify({ status: 'error', error: msg, lock: lockKey }));+ if (opts.json) emitJson(JSON.stringify({ status: 'error', error: msg, lock: lockKey }));else console.error(`Failed to inspect lock ${lockKey}: ${msg}`);return 1;}@@ -108,13 +112,13 @@ export async function runBreakLock(`appears wedged, the cause is not a held lock; inspect checkpoint/resume ` +`state with \`gbrain sync --source ${sourceId}\` or \`gbrain doctor\`.`;if (opts.json) {- console.log(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId, wedge_hint: wedgeHint }));+ emitJson(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId, wedge_hint: wedgeHint }));} else {console.log(wedgeHint);}return 0;}- if (opts.json) console.log(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId }));+ if (opts.json) emitJson(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId }));else console.log(`Lock ${lockKey} is not held (nothing to break).`);return 0;}@@ -132,7 +136,7 @@ export async function runBreakLock(// who need to clear a cross-host lock use --force-break-lock.if (snap.holder_host !== localHost) {if (opts.json) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({status: 'refused', reason: 'cross_host', lock: lockKey, source_id: sourceId,snapshot: snap, local_host: localHost,}));@@ -146,7 +150,7 @@ export async function runBreakLock(engine, lockKey, snap.holder_pid, opts.maxAgeSeconds, snap.acquisition_token,);if (opts.json) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({status: deleted ? 'broken' : 'refused',reason: deleted ? 'max_age_breached' : 'within_max_age',lock: lockKey,@@ -178,7 +182,7 @@ export async function runBreakLock(if (opts.force) {const { deleted } = await deleteLockRow(engine, lockKey, snap.holder_pid, snap.acquisition_token);if (opts.json) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({status: deleted ? 'force_broken' : 'race_already_cleared',lock: lockKey, source_id: sourceId, snapshot: snap,}));@@ -194,7 +198,7 @@ export async function runBreakLock(// Safe path: must be local host AND (TTL-expired OR (PID-dead AND age >= 60s)).if (snap.holder_host !== localHost) {if (opts.json) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({status: 'refused',reason: 'cross_host',lock: lockKey, source_id: sourceId, snapshot: snap, local_host: localHost,@@ -232,7 +236,7 @@ export async function runBreakLock(if (!safe) {if (opts.json) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({status: 'refused', reason, lock: lockKey, source_id: sourceId, snapshot: snap,}));} else {@@ -249,7 +253,7 @@ export async function runBreakLock(const { deleted } = await deleteLockRow(engine, lockKey, snap.holder_pid, snap.acquisition_token);if (opts.json) {- console.log(JSON.stringify({+ emitJson(JSON.stringify({status: deleted ? 'broken' : 'race_already_cleared',reason, lock: lockKey, source_id: sourceId, snapshot: snap,}));diff --git a/test/cli-json-guard.serial.test.ts b/test/cli-json-guard.serial.test.tsindex 39e500b5df..f06885cde0 100644--- a/test/cli-json-guard.serial.test.ts+++ b/test/cli-json-guard.serial.test.ts@@ -159,3 +159,59 @@ describe('D2 command migrations: init', () => {}});});++describe('D2 command migrations: doctor, sync, embed on a keyless brain', () => {+ let home = '';+ const cli = (args: string[]) => runCli(args, { home, cwd: home, timeoutMs: 120_000 });++ test('setup: keyless PGLite brain + a git-backed source', async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-json-cmds-'));+ expect((await cli(['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ const repo = join(home, 'notes');+ mkdirSync(repo);+ writeFileSync(join(repo, 'example.md'), '---\ntitle: Example\n---\nHello world\n');+ const git = (args: string[]) => Bun.spawnSync(['git', '-c', '[email protected]', '-c', 'user.name=fixture', ...args], { cwd: repo });+ git(['init', '-q']); git(['add', '.']); git(['commit', '-qm', 'init']);+ expect((await cli(['sources', 'add', 'notes', '--path', repo])).exitCode).toBe(0);+ }, 150_000);++ test('doctor --json --fast: one report document', async () => {+ const r = await cli(['doctor', '--json', '--fast']);+ expect(onlyDocument(r.stdout)).toMatchObject({ schema_version: 2 });+ expect(typeof onlyDocument(r.stdout).health_score).toBe('number');+ }, 120_000);++ test('sync --json success: one envelope; a failing sync: one v1 error document', async () => {+ const ok = await cli(['sync', '--source', 'notes', '--no-pull', '--json']);+ expect(ok.exitCode).toBe(0);+ expect(onlyDocument(ok.stdout)).toMatchObject({ schema_version: 1, source_id: 'notes', added: 1 });+ const bad = await cli(['sync', '--source', 'notes', '--json']);+ expect(bad.exitCode).toBe(1);+ const doc = onlyDocument(bad.stdout);+ expect(typeof doc.code).toBe('string');+ expect(typeof doc.suggestion).toBe('string');+ expect(doc.contract_version).toBe(1);+ }, 120_000);++ test('embed --json: keyless --stale is a result document (exit 0); --all is embedding_disabled (exit 1)', async () => {+ const stale = await cli(['embed', '--stale', '--json']);+ expect(stale.exitCode).toBe(0);+ expect(onlyDocument(stale.stdout)).toMatchObject({ failures: 0 });+ const all = await cli(['embed', '--all', '--json']);+ expect(all.exitCode).toBe(1);+ expect(onlyDocument(all.stdout)).toMatchObject({ error: 'embedding_disabled', code: 'embedding_disabled', fix: { argv: ['gbrain', 'embeddings', 'enable', '--help'] } });+ }, 120_000);++ test('doctor --json with no brain: the no_brain envelope', async () => {+ const empty = mkdtempSync(join(tmpdir(), 'gbrain-json-nobrain-'));+ try {+ const r = await runCli(['doctor', '--json'], { home: empty, cwd: empty });+ expect(r.exitCode).toBe(1);+ expect(onlyDocument(r.stdout)).toMatchObject({ code: 'no_brain', fix: { argv: ['gbrain', 'init', '--pglite', '--no-embedding'] } });+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+ });++ test('teardown', () => { rmSync(home, { recursive: true, force: true }); });+});diff --git a/test/cli-options.test.ts b/test/cli-options.test.tsindex 7245a9b9d6..027aec2631 100644--- a/test/cli-options.test.ts+++ b/test/cli-options.test.ts@@ -244,7 +244,7 @@ describe('cli.ts global-flag stripping (integration)', () => {encoding: 'utf-8',env: { ...process.env, NO_COLOR: '1' },});- expect(res.status).toBe(1);+ expect(res.status).toBe(2); // usage error (agent contract v1 A3/D1)expect(res.stderr).toContain('Unknown command: not-a-real-command-4557');expect(res.stderr).not.toContain('Unknown command: --explain');});