Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): json_document_missing events name the release, guard and exit code (#6629)
time-attack0f349c3f3b51
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex ac57b7aefb..37ebcbcd66 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -19,7 +19,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/onboard/hosted-option.ts` — the `hosted_option` coaching notice (gbrain.io, hosted GBrain): the one home of its URL, copy and `?ref=` tags. `gbrain setup` appends it when it created the brain, `printInAgentReady` prints it after the in-agent ready text when init created the brain (its mute hint names that install's own launcher), and `gbrain mcp expose`'s `Session.finish` adds it (JSON `notices`, one human line) on the run that wrote the first receipt and at Tailscale/service friction exits (`EXPOSE_FRICTION_REASONS`), never on the consent-pending document, `--dry-run`, `--status` or `--remove`. Bare `gbrain init` never shows it. Refs split publish (`cli-mcp-expose`) from friction exits (`cli-mcp-expose-friction`). Muted by the owner list or the `stdio` audience (`hostedOptionMuted`, i.e. `mutedNoticeCodes('stdio')`); `writeHostedOption` prints one plain line on a TTY and the notice block otherwise. No network call. Tests: `test/hosted-option.test.ts`, `test/setup.test.ts`, `test/mcp-expose.test.ts`.- `src/core/onboard/mcp-onboarding.ts` — onboarding coaching for the owner's stdio pipe. `collectOnboardOpportunities(engine, signal, between?)` is the one home of init's six counts (parallel for `runInitNudge`, sequential with yields for the background refresh; the stale-chunk count uses `countStaleChunks`' predicate, so soft-deleted and `embed_skip` pages are not backlog); a failed count is `null` and never reads as a gap, and `onboardGaps` applies init's thresholds (link < 0.7, timeline < 0.9; an empty brain has none). The per-brain cache (6 h TTL, `GBRAIN_HOME/onboard-counts-<brain>.json`, atomic write, partial runs not persisted) is loaded by `startOnboardingRefresher` and refreshed in the background only while the idle gate reports no request in flight (3 s budget); it also holds the pitchable `gbrain features` recommendations (`pitchableFeatures`, offer state read-only) and the stale-chunk backfill estimate. `mcpOnboardingNotices` is dispatch's one producer on the stdio success path: `first_run_decisions` (writeback + skills via `mcpFirstRunNotices`, from the second successful call, nothing persisted) and one coaching notice per class (`onboard_stale_chunks`, `onboard_link_coverage`, `onboard_timeline_coverage`, `onboard_no_takes`) when `ONBOARD_CALL_AFFINITY` names the call and the class's result predicate holds, plus `features_auto_fix` on `get_backlinks`/`traverse_graph`; fixes are the read-only `get_health` / `gbrain onboard --check` preview, the dismissal line names `mute_notice` only where it is callable. `mutedFirstRunDecisionsNotice` feeds doctor (`memory_writeback`) and `gbrain onboard --check`. HTTP never calls it. Test seams `__warmOnboardingCacheForTests`, `__awaitOnboardingRefreshForTests`, `__resetMcpOnboardingForTests`. Tests: `test/mcp-onboarding.test.ts`, `test/init-nudge.test.ts`, `test/mcp-notice-channels.test.ts`.- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.-- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.+- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook (document mode, exit 0; the event records `command`, `version`, `guard: 'document'` and `exit_code: 0`, never argv values; `outcome` keeps its value, #6629/D26). The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `privateFactNotice` (#6606: a local `remember --visibility private` save is recall-only and never pushed into a session; names the world re-save and the private copy to forget), `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`. D2: `hiddenTakesNotice(hidden, route, fix)` → `hidden_tool_content` (info, per-call): a get_page/search/query result left out takes (counts and the result's own slugs, never take text); the fix is the hidden-tool route's next step.- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).diff --git a/src/cli/json-guard.ts b/src/cli/json-guard.tsindex b5d8f94030..ac77dd6381 100644--- a/src/cli/json-guard.ts+++ b/src/cli/json-guard.ts@@ -5,11 +5,13 @@* `jsonSubcommands[<first positional after the command>]`); they write their* result through writeStdoutFinal / writeNdjsonLine, so undeclared commands* keep their current stdout. Also wires the E11 `json_document_missing`- * record for the exit-0 bug case.+ * record for the exit-0 bug case (document mode only), stamped with the+ * gbrain version, the guard and the exit code (#6629).*/import { jsonRequested, setJsonDocumentMissingHook } from '../core/cli-force-exit.ts';import { recordAgentContractEvent } from '../core/agent-contract-log.ts';import { findCliCommand } from './command-table.ts';+import { VERSION } from '../version.ts';export function agentJsonGuardMode(argv: readonly string[]): { json?: 'document' | 'ndjson' } {const at = argv.findIndex(a => !a.startsWith('-') && findCliCommand(a) !== undefined);@@ -19,6 +21,8 @@ export function agentJsonGuardMode(argv: readonly string[]): { json?: 'document'const subs = record?.jsonSubcommands;const json = record?.json ?? (sub !== undefined && subs && Object.hasOwn(subs, sub) ? subs[sub] : undefined);if (!json || !jsonRequested(argv)) return {};- setJsonDocumentMissingHook(() => recordAgentContractEvent({ transport: 'cli', command, code: 'json_document_missing', outcome: 'committed' }));+ // #6629: which release and guard produced the event; never argv values, paths or output. `outcome` stays as-is (D26).+ setJsonDocumentMissingHook(() => recordAgentContractEvent({ transport: 'cli', command, code: 'json_document_missing', outcome: 'committed',+ version: VERSION, guard: 'document', exit_code: 0 }));return { json };}diff --git a/src/core/agent-contract-log.ts b/src/core/agent-contract-log.tsindex 8c70ffb85f..b61eb955f9 100644--- a/src/core/agent-contract-log.ts+++ b/src/core/agent-contract-log.ts@@ -27,6 +27,12 @@ export interface AgentContractEvent {outcome?: string;/** Internal normaliser fault class (never a message). */fault?: string;+ /** #6629: the gbrain release that wrote the event. */+ version?: string;+ /** #6629: the `--json` guard mode the event concerns. */+ guard?: 'document' | 'ndjson';+ /** #6629: the process exit code the event was recorded at. */+ exit_code?: number;}export function agentContractLogPath(): string {diff --git a/test/cli-json-guard.test.ts b/test/cli-json-guard.test.tsindex 0cfcd1f481..f86d5846ed 100644--- a/test/cli-json-guard.test.ts+++ b/test/cli-json-guard.test.ts@@ -7,7 +7,7 @@* patches process-global stdout/exit.*/import { describe, expect, test } from 'bun:test';-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -26,6 +26,34 @@ async function run(body: string): Promise<{ out: string; err: string; code: numb}}+describe('#6629 json_document_missing event', () => {+ test('the event names the release, guard and exit code, and carries no argv values', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6629-'));+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6629-run-'));+ const script = join(dir, 'run.ts');+ const src = join(import.meta.dir, '..', 'src');+ writeFileSync(script, `import * as g from ${JSON.stringify(HELPER)};+import { agentJsonGuardMode } from ${JSON.stringify(join(src, 'cli', 'json-guard.ts'))};+const { json } = agentJsonGuardMode(['doctor', '--json', '--fast', 'private-arg-value']);+g.installStdoutPipeDelivery({ json });+console.log('forgot the document');+process.exit(0);`);+ try {+ const proc = Bun.spawn([process.execPath, script], { stdout: 'pipe', stderr: 'pipe', env: { ...process.env, GBRAIN_HOME: home } });+ expect(await proc.exited).toBe(0);+ const raw = readFileSync(join(home, '.gbrain', 'agent-contract', 'events.jsonl'), 'utf8').trim();+ const { ts, ...event } = JSON.parse(raw.split('\n').pop()!);+ expect(typeof ts).toBe('string');+ const { VERSION } = await import('../src/version.ts');+ expect(event).toEqual({ transport: 'cli', command: 'doctor', code: 'json_document_missing', outcome: 'committed', version: VERSION, guard: 'document', exit_code: 0 });+ expect(raw).not.toContain('private-arg-value');+ } finally {+ rmSync(home, { recursive: true, force: true });+ rmSync(dir, { recursive: true, force: true });+ }+ });+});+describe('--json guard (document mode)', () => {test('console.log and stdout.write go to stderr; the final document alone reaches fd 1', async () => {const r = await run(`g.installStdoutPipeDelivery({ json: 'document' });