Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): agent_contract tells events from other builds apart from current faults (#6758)
garrytan031f71cc779d
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 37ebcbcd66..937c93356e 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -8,7 +8,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`; the escalation flag `ask_user: true` marks a refusal whose every way out is the user's decision) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (a stored `ask_user: true` → `ask_user`; no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace, returned as the parser normalizes it (fix wave 13 P1.16); an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).-- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).+- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`). #6758: every event carries `version` (defaults to the writing build's `VERSION`); on a warn the check adds `details.builds` (`this_build`, `other_builds`, `unknown_build` for older unversioned lines, `versions`) and `details.incident` (`historical` when no counted event came from this build, `since` the oldest), and the message names the events another build recorded. Test: `test/doctor-status-set.test.ts`.- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `degraded_recall`, `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`, …) and, on HTTP, `degraded`/`safety` notices are never deduped, except that a notice's unrendered `Notice.dedupe_key` replaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (`degradedRecallNotice` sets it only when every stage/reason pair is configuration-persistent: a keyless brain's `embed_unavailable`; HTTP ignores it for degraded notices; `renderNotice` never copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute). D4: `claim(key)` (true once per key) and `memoize(key, compute)` back the once-per-session `grant_blocked_operations` notice; codes in `SELF_DEDUPED_NOTICE_CODES` were deduped by their producer on its own key, so `admit` applies mute only. `hidden_tool_content` is per-call.- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.test.ts`.diff --git a/src/commands/doctor/checks/agent-contract.ts b/src/commands/doctor/checks/agent-contract.tsindex 75bdf15a1f..d040e870bb 100644--- a/src/commands/doctor/checks/agent-contract.ts+++ b/src/commands/doctor/checks/agent-contract.ts@@ -6,13 +6,18 @@* suggestion-less envelopes, unattended runs refused for consent, derived* spend caps exhausted, or a `--json` command that printed no document. The* fix is the exact preapproval command when one would have let the run- * proceed. Engine-free, read-only; the log never holds params or messages.+ * proceed. #6758: on a warn, `details.builds` splits the counted events by+ * the build that recorded them, and `details.incident` is `historical` when+ * none came from this build (they age out of the window), with `since` the+ * oldest one.+ * Engine-free, read-only; the log never holds params or messages.*/import { readAgentContractEvents, type AgentContractEvent } from '../../../core/agent-contract-log.ts';import { PREAPPROVE_PAID_MAX_USD_PER_RUN, PREAPPROVE_PERSISTENT_INSTALL, preapprovalCommand } from '../../../core/consent-preapproval.ts';import type { Action } from '../../../core/agent-output.ts';import type { Check } from '../../doctor.ts';import { doctorVerify } from '../check-fix.ts';+import { VERSION } from '../../../version.ts';import type { DoctorEntry } from '../context.ts';const NAME = 'agent_contract';@@ -73,8 +78,17 @@ export function agentContractCheck(events: readonly Event[], now = Date.now()):return { name: NAME, status: 'ok', message: `No agent dead ends in the last ${AGENT_CONTRACT_WINDOW_DAYS} days (${recent.length} non-success event(s) logged).`, details };}const fix = paidRefused.length || capped.length ? preapprovePaid() : installRefused.length ? preapproveInstall() : undefined;+ const counted = [...new Set([...faults, ...refused, ...capped, ...noDoc])];+ const versions = [...new Set(counted.flatMap((e) => e.version && e.version !== VERSION ? [e.version] : []))].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));+ const builds = { this_build: counted.filter((e) => e.version === VERSION).length, other_builds: counted.filter((e) => e.version && e.version !== VERSION).length,+ unknown_build: counted.filter((e) => !e.version).length, versions };+ const incident = { scope: builds.this_build > 0 ? 'current' : 'historical', since: counted.reduce((min, e) => (e.ts < min ? e.ts : min), counted[0]!.ts) };+ const range = versions.length > 1 ? `${versions[0]} to ${versions.at(-1)}` : versions[0];+ const elsewhere = [builds.other_builds ? `${builds.other_builds} of ${counted.length} were recorded by another gbrain build (${range})` : '',+ builds.unknown_build ? `${builds.unknown_build} by a build that did not record its version` : ''].filter(Boolean).join(' and ');+ const history = elsewhere ? ` ${elsewhere}; recheck after upgrading, or once they age out of the ${AGENT_CONTRACT_WINDOW_DAYS}-day window.` : '';return {- name: NAME, status: 'warn', message: `Last ${AGENT_CONTRACT_WINDOW_DAYS} days: ${parts.join('; ')}.`, details,+ name: NAME, status: 'warn', message: `Last ${AGENT_CONTRACT_WINDOW_DAYS} days: ${parts.join('; ')}.${history}`, details: { ...details, builds, incident },...(fix ? { fix } : { fix_unavailable_reason: 'operator_judgement' as const }),};}diff --git a/src/core/agent-contract-log.ts b/src/core/agent-contract-log.tsindex b61eb955f9..e095b57cbf 100644--- a/src/core/agent-contract-log.ts+++ b/src/core/agent-contract-log.ts@@ -14,6 +14,7 @@ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } fromimport { dirname } from 'node:path';import { gbrainPath } from './config.ts';import type { Effect, Transport } from './agent-output.ts';+import { VERSION } from '../version.ts';const MAX_BYTES = 1024 * 1024;@@ -27,7 +28,7 @@ export interface AgentContractEvent {outcome?: string;/** Internal normaliser fault class (never a message). */fault?: string;- /** #6629: the gbrain release that wrote the event. */+ /** #6629, #6758: the gbrain release that wrote the event (stamped on every event; absent on lines older builds wrote). */version?: string;/** #6629: the `--json` guard mode the event concerns. */guard?: 'document' | 'ndjson';@@ -50,8 +51,9 @@ export function appendBoundedJsonl(path: string, record: Record<string, unknown>} catch { /* fail-open */ }}+/** #6758: every event names the build that wrote it, so doctor can tell history from a current fault. */export function recordAgentContractEvent(event: AgentContractEvent): void {- appendBoundedJsonl(agentContractLogPath(), { ts: new Date().toISOString(), ...event });+ appendBoundedJsonl(agentContractLogPath(), { ts: new Date().toISOString(), ...event, version: event.version ?? VERSION });}/** Read back recent events (newest last). Never throws. */diff --git a/test/doctor-status-set.test.ts b/test/doctor-status-set.test.tsindex b8c264434e..4bcea6999b 100644--- a/test/doctor-status-set.test.ts+++ b/test/doctor-status-set.test.ts@@ -19,6 +19,8 @@ import { checkError, finalizeCheckFixes, infoCheck } from '../src/commands/doctoimport { doctorCheckNames, onlyNeedsEngine, parseOnlyChecks } from '../src/commands/doctor/registry.ts';import { throttleDoctorHeartbeat } from '../src/commands/doctor/heartbeat.ts';import { agentContractCheck } from '../src/commands/doctor/checks/agent-contract.ts';+import { readAgentContractEvents, recordAgentContractEvent } from '../src/core/agent-contract-log.ts';+import { VERSION } from '../src/version.ts';import { backupCoachingDue } from '../src/core/backup/status-file.ts';import type { ProgressReporter } from '../src/core/progress.ts';import { withEnv } from './helpers/with-env.ts';@@ -227,3 +229,39 @@ describe('connection errors name their source; brain score unknown when DB checkexpect(classifyPgAccessError(err, { url: 'postgresql://[email protected]:5432/postgres' }).remediation).toMatch(/Supabase/);});});++describe('#6758 agent_contract: events from other builds are history, counted apart', () => {+ const now = Date.parse('2026-10-03T00:00:00Z');+ const ts = new Date(now - 3_600_000).toISOString();+ const older = new Date(now - 2 * 86_400_000).toISOString();+ test('faults split by the build that recorded them; all from other builds reads as historical', () => {+ const c = agentContractCheck([+ { ts: older, op: 'find_orphans', transport: 'stdio', code: 'internal_error', version: '0.60.100.0' },+ { ts, op: 'find_orphans', transport: 'stdio', code: 'internal_error', version: '0.60.200.0' },+ { ts, op: 'search', transport: 'stdio', code: 'internal_error' },+ ], now);+ expect(c.status).toBe('warn');+ expect(c.details).toMatchObject({ internal_errors: 3, builds: { this_build: 0, other_builds: 2, unknown_build: 1, versions: ['0.60.100.0', '0.60.200.0'] },+ incident: { scope: 'historical', since: older } });+ expect(c.message).toContain('2 of 3 were recorded by another gbrain build (0.60.100.0 to 0.60.200.0)');+ expect(c.message).toContain('1 by a build that did not record its version');+ });+ test('a fault from this build is current', () => {+ const c = agentContractCheck([+ { ts: older, op: 'x', transport: 'stdio', code: 'internal_error', version: '0.60.100.0' },+ { ts, op: 'y', transport: 'stdio', code: 'internal_error', version: VERSION },+ ], now);+ expect(c.details).toMatchObject({ builds: { this_build: 1, other_builds: 1, unknown_build: 0 }, incident: { scope: 'current', since: older } });+ });+ test('recordAgentContractEvent stamps the build that wrote the event', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-agent-contract-version-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ recordAgentContractEvent({ transport: 'cli', command: 'embed', code: 'internal_error', outcome: 'failed' });+ recordAgentContractEvent({ transport: 'cli', command: 'embed', code: 'internal_error', version: '0.1.0.0' });+ expect(readAgentContractEvents().map(e => e.version)).toEqual([VERSION, '0.1.0.0']);+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+ });+});+