Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(agent-contract): CI round 1 — keep contract.ts out of the snapshot-schema closure, DB classifier before generic rows, fatal seam left to Lane D, mute_notice ledgers, spec-mandated test updates
garrytan5b20e9855651
diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex 0f5ccb9fcf..099ad1fe32 100644--- a/docs/architecture/managed-mutating-writers.tsv+++ b/docs/architecture/managed-mutating-writers.tsv@@ -63,6 +63,7 @@ op run_onboard no_canonical_write Runs remediation steps; each step keeps its owop run_skillopt no_canonical_write Skill files and proposals outside the brain database.op loops_close coordinator open_loops state rows; the commitment fact is retired (expired, fence row struck) through the loop-fact-retirement coordinator mutation (#5869).op loops_mute no_canonical_write Loop suppression rows.+op mute_notice no_canonical_write Notice mute list in <GBRAIN_HOME>/notices/muted.json; no brain table or canonical file.op loops_unmute no_canonical_write Loop suppression rows.cli src/commands/enrich.ts coordinator gbrain enrich preflights maintenance authority, then publishMaintenancePage per page.cli src/commands/extract-conversation-facts.ts coordinator Bulk conversation facts commit through the coordinator capability after a derived-facts preflight.diff --git a/src/cli.ts b/src/cli.tsindex d4d2dc2e4e..5061e94c47 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -37,8 +37,7 @@ import { formatVolunteeredPage } from './core/context/volunteer.ts';import type { Operation, OperationContext } from './core/operations.ts';import { currentCliWriteWait } from './core/persistence/write-wait.ts';import { isScopeErrorCode } from './core/error-catalogue.ts';-import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery, jsonRequested, noteRenderedErrorCode } from './core/cli-force-exit.ts';-import { renderCliError } from './core/agent-output.ts';+import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';import { agentJsonGuardMode } from './cli/json-guard.ts';import { serializeMarkdown } from './core/markdown.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';@@ -3136,12 +3135,6 @@ if (import.meta.main) {if (shouldForceExitAfterMain()) flushThenExit(currentExitCode());},(e) => {- if (e?.code !== 'pglite_busy' && jsonRequested(process.argv.slice(2))) {- const r = renderCliError(e, { json: true, command: process.argv[2] ?? '', tty: false });- noteRenderedErrorCode(JSON.parse(r.stdout!).code);- void writeStdoutFinal(r.stdout!).finally(() => flushThenExit(r.exitCode));- return;- }if (e?.code === 'pglite_busy' && process.argv.includes('--json')) {console.log(JSON.stringify({ error: 'pglite_busy', retryable: true, reason: e.reason,next_action: 'Wait for the current command or server to close, then retry. Do not remove a live lock.' }));diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 18db0c5711..d459bc6773 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -13,7 +13,7 @@import { existsSync } from 'node:fs';import { join } from 'node:path';import { VERSION } from '../version.ts';-import { OperationError } from './ops/contract.ts';+import { OperationError, __registerOperationErrorRenderer } from './ops/contract.ts';import { StructuredAgentError } from './errors.ts';import { canonicalCodeFor, codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';import { VERB_NAMES } from './verbs.ts';@@ -444,7 +444,7 @@ const ROWS: Row[] = [if (argv) fix = { argv, consent: [], actor: 'agent', why: e.message, requires_exclusive: false };}return {- error: e.code, code: e.canonicalCode, message: e.message, suggestion: e.suggestion,+ error: e.code, code: canonicalCodeFor(e.canonicalCode), message: e.message, suggestion: e.suggestion,reason: e.reason, why: e.why, fix, docs: e.docs, notices: e.notices, detail: e.detail,protocol_version: e.protocolVersion === 1 ? 1 : undefined,write_request: j.write_request, write_error: e.writeError,@@ -503,6 +503,7 @@ const ROWS: Row[] = [error: e.code, code: e.code, message: e.problem, why: e.cause_text, suggestion: e.fix, docs: e.doc_url,}),},+ // ── generic rows: the DB classifier runs before these ──{match: e => named('AIConfigError')(e) || named('AITransientError')(e),map: (e: Error & { fix?: string }) => ({@@ -528,6 +529,9 @@ const ROWS: Row[] = [},];+/** Index of the first generic row (AIConfigError); rows before it are typed and beat the DB classifier. */+const FIRST_GENERIC_ROW = ROWS.findIndex(r => r.match(Object.assign(new Error('x'), { name: 'AIConfigError' })));+function argvFromPricing(command: string): string[] | undefined {const s = command.replace(/<([a-z0-9-]+)>/gi, 'PLACEHOLDER_$1');const argv = argvFromCommand(s);@@ -591,8 +595,12 @@ function genericEnvelope(e: unknown, ctx: AgentErrorContext): AgentEnvelope {/** Total: never throws; on an internal fault returns the prior generic envelope and logs the class (E11). */export function toAgentError(e: unknown, ctx: AgentErrorContext): AgentEnvelope {try {+ // Typed rows first (OperationError … CredentialError); then the DB-access+ // classifier, which must win over the generic GBrainError/AI/phase rows+ // (a connect failure is often a GBrainError); then the unknown fallback.const row = ROWS.find(r => r.match(e));- let parts = row ? row.map(e, ctx) : dbParts(e, ctx) ?? unknownParts(e, ctx);+ const typed = row && ROWS.indexOf(row) < FIRST_GENERIC_ROW;+ let parts = typed ? row.map(e, ctx) : dbParts(e, ctx) ?? (row ? row.map(e, ctx) : unknownParts(e, ctx));if (!parts.fix) {const recovery = recoveryFix(parts, ctx);if (recovery) parts = { ...parts, fix: recovery };@@ -695,3 +703,8 @@ export function fallbackJsonDocument(exitCode: number, lastCode?: string): Recorcontract_version: CONTRACT_VERSION,};}++__registerOperationErrorRenderer({+ fix: a => renderAction(a, cliRenderContext()),+ notice: n => renderNotice(n, cliRenderContext()),+});diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 2b921d2b89..d39b92219b 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -34,10 +34,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--brain', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],'claw-test': ['--agent', '--apply', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],- 'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],- 'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],- 'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],- 'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],+ 'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source', '--yes'],+ 'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source', '--yes'],+ 'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source', '--yes'],+ 'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source', '--yes'],'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--harness', '--help', '--http', '--input', '--json', '--limit', '--markdown', '--min', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--no-hooks', '--only', '--out', '--path', '--pattern', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--stale', '--status', '--suite', '--surface', '--target', '--threshold', '--timeout', '--to', '--url', '--wait', '--what-if-threshold', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 90e197df58..4a4e64e81c 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -10,8 +10,18 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { MEMORY_VERBS_VERSION } from '../verbs.ts';import { publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from '../persistence/types.ts';-import { cliRenderContext, renderAction, renderNotice, CONTRACT_VERSION, type Action, type Notice } from '../agent-output.ts';-import { canonicalCodeFor, type RegistryCode } from '../error-catalogue.ts';+// Type-only: this module sits in the PGLite snapshot-schema import closure+// (via persistence/digest.ts), so it must not pull agent-output's runtime+// graph (version.ts, the DB classifier) in. agent-output registers the wire+// renderer below when it loads.+import type { Action, Notice } from '../agent-output.ts';+import type { RegistryCode } from '../error-registry.ts';++/** Agent contract v1: the wire renderer for `fix`/`notices` in toJSON(), registered by agent-output.ts on load. */+interface OperationErrorWireRenderer { fix(a: Action): unknown; notice(n: Notice): unknown }+let wireRenderer: OperationErrorWireRenderer | null = null;+/** @internal agent-output.ts only. Unregistered (agent-output never loaded) → the stored Action is emitted as-is. */+export function __registerOperationErrorRenderer(r: OperationErrorWireRenderer): void { wireRenderer = r; }// --- Types ---@@ -88,9 +98,13 @@ export class OperationError extends Error {this.name = 'OperationError';}- /** The canonical registry code (`code` on the wire); `this.code` stays the frozen `error` value. */+ /**+ * The canonical registry code (`code` on the wire); `this.code` stays the+ * frozen `error` value. Registry-wide legacy aliases are applied by+ * toAgentError / the thin client (canonicalCodeFor), not here.+ */get canonicalCode(): string {- return this.canonical ?? canonicalCodeFor(this.code);+ return this.canonical ?? this.code;}/**@@ -101,7 +115,7 @@ export class OperationError extends Error {static bare(code: RegistryCode, message: string, reason: string): OperationError {const e = new OperationError(code, message);e.reason = reason;- e.contractVersion = CONTRACT_VERSION;+ e.contractVersion = 1;return e;}@@ -118,8 +132,8 @@ export class OperationError extends Error {...(this.writeError ? { write_error: this.writeError } : {}),...(this.reason !== undefined ? { reason: this.reason } : {}),...(this.why !== undefined ? { why: this.why } : {}),- ...(this.fix ? { fix: renderAction(this.fix, cliRenderContext()) } : {}),- ...(this.notices?.length ? { notices: this.notices.map(n => renderNotice(n, cliRenderContext())) } : {}),+ ...(this.fix ? { fix: wireRenderer ? wireRenderer.fix(this.fix) : this.fix } : {}),+ ...(this.notices?.length ? { notices: this.notices.map(n => wireRenderer ? wireRenderer.notice(n) : n) } : {}),...(this.contractVersion !== undefined ? { contract_version: this.contractVersion } : {}),};}@@ -151,7 +165,7 @@ export function opError(code: RegistryCode, message: string, suggestion: string,if (opts.why !== undefined) e.why = opts.why;if (opts.fix !== undefined) e.fix = opts.fix;if (opts.detail !== undefined) e.detail = opts.detail;- e.contractVersion = CONTRACT_VERSION;+ e.contractVersion = 1;return e;}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex a1a06f1cfe..22592effbc 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -15,7 +15,7 @@ import { resolveBrainId } from '../core/brain-resolver.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';import { cliRenderContext, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';import { isCallable } from '../core/ops/callable.ts';-import { mutedNoticeCodes, processNoticeLedger, type NoticeLedger } from '../core/notice-ledger.ts';+import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger } from '../core/notice-ledger.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';import { suggestNearest } from '../core/levenshtein.ts';@@ -76,6 +76,7 @@ let backupNoticeCheckedMs = 0;export function __resetBackupNoticeForTests(): void {backupNoticeShown = false;backupNoticeCheckedMs = 0;+ __resetProcessNoticeLedgerForTests();}/**diff --git a/test/e2e/serve-http-oauth.test.ts b/test/e2e/serve-http-oauth.test.tsindex 4ef6b57b00..6d3a7ecc69 100644--- a/test/e2e/serve-http-oauth.test.ts+++ b/test/e2e/serve-http-oauth.test.ts@@ -1544,8 +1544,10 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {arguments: { slug: 'e2e-c4-denied', content: '---\ntitle: t\n---\nbody' },});expect(denied.isError).toBe(true);- expect(JSON.parse(denied.content[0].text)).toEqual({+ // Agent contract v1: legacy keys keep their values; code + the rest of the envelope are additive.+ expect(JSON.parse(denied.content[0].text)).toMatchObject({error: 'insufficient_scope',+ code: 'insufficient_scope',message: "Operation put_page requires 'write' scope",your_scopes: ['read'],});@@ -1593,8 +1595,9 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {arguments: { slug: 'e2e-c4-agent-denied' },});expect(denied.isError).toBe(true);- expect(JSON.parse(denied.content[0].text)).toEqual({+ expect(JSON.parse(denied.content[0].text)).toMatchObject({error: 'insufficient_scope',+ code: 'insufficient_scope',message: "Operation get_page requires 'read' scope",your_scopes: ['agent'],});diff --git a/test/e2e/unbound-source-postgres.test.ts b/test/e2e/unbound-source-postgres.test.tsindex 1dfd70b151..17830a844b 100644--- a/test/e2e/unbound-source-postgres.test.ts+++ b/test/e2e/unbound-source-postgres.test.ts@@ -33,6 +33,7 @@ import { submitPageMutation } from '../../src/core/persistence/page-mutations.tsimport { performManagedSync } from '../../src/core/persistence/sync-run.ts';import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';import { runConfig } from '../../src/commands/config.ts';+import { docsUrl } from '../../src/core/agent-output.ts';const d = hasDatabase() ? describe : describe.skip;let engine: PostgresEngine;@@ -129,7 +130,7 @@ d('#5254 Postgres put_page to an unbound filesystem source', () => {expect(refused.response.isError).toBe(true);expect(refused.payload.error).toBe('owner_unavailable');expect(refused.payload.detail).toBe('unbound_source');- expect(refused.payload.docs).toBe(DOCS);+ expect(refused.payload.docs).toBe(docsUrl(DOCS)); // agent contract v1: absolute, version-pinned wire docsconst hint = refused.payload.suggestion as string;expect(hint).toContain('gbrain sources writer status default --json');expect(hint).toContain('gbrain sources writer claim default --path');@@ -208,7 +209,7 @@ d('#5254 Postgres put_page to an unbound filesystem source', () => {expect(result.response.isError).toBe(true);expect(result.payload.error).toBe('owner_unavailable');expect(result.payload.detail).toBe('unbound_source');- expect(result.payload.docs).toBe(DOCS);+ expect(result.payload.docs).toBe(docsUrl(DOCS));expect(result.payload.write_request.state).toBe('failed');expect(result.payload.suggestion).toContain('new request_id');expect(await engine.readPageSnapshot(slug, { sourceId: 'default', includeDeleted: true })).toBeNull();diff --git a/test/extract-conversation-facts-diagnostics.serial.test.ts b/test/extract-conversation-facts-diagnostics.serial.test.tsindex 90aff6af4c..503774b7df 100644--- a/test/extract-conversation-facts-diagnostics.serial.test.ts+++ b/test/extract-conversation-facts-diagnostics.serial.test.ts@@ -230,7 +230,7 @@ describe('#5364 diagnostics across workers, sources, CLI, and cycle', () => {const log = spyOn(console, 'log').mockImplementation(() => {});const exit = spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit:${code}`); }) as never);try {- await expect(runExtractConversationFacts(engine, ['--source-id', 'speaker-a', '--types', 'conversation', '--sleep', '0'])).rejects.toThrow('exit:3');+ await expect(runExtractConversationFacts(engine, ['--source-id', 'speaker-a', '--types', 'conversation', '--sleep', '0'])).rejects.toThrow('exit:1'); // agent contract v1 A3: lock skips exit 1 (retryable); 3 means confirmation_requiredexpect(log.mock.calls.map(call => call.join(' ')).join('\n')).toContain('Skipped 1 page(s) held by another worker');} finally {exit.mockRestore();diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.jsonindex 23bb0beb0f..73fdcfae93 100644--- a/test/fixtures/goldens/cli/dispatch-phase.json+++ b/test/fixtures/goldens/cli/dispatch-phase.json@@ -619,6 +619,25 @@"thinClient": "refuse","thinClientRoutedSubcommands": []},+ "errors": {+ "hasSwitchCase": false,+ "phase": "pre-connect",+ "preConnectRules": [+ {+ "condition": "command === 'errors'",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": false,+ "unconditionalFor": [+ "errors"+ ]+ }+ ],+ "thinClient": "none",+ "thinClientRoutedSubcommands": []+ },"eval": {"hasSwitchCase": true,"phase": "post-connect",@@ -1087,6 +1106,25 @@"thinClient": "none","thinClientRoutedSubcommands": []},+ "notices": {+ "hasSwitchCase": false,+ "phase": "pre-connect",+ "preConnectRules": [+ {+ "condition": "command === 'notices'",+ "connectsEngine": false,+ "refusesThinClient": false,+ "routesThinClient": false,+ "terminates": true,+ "thinClientCheck": false,+ "unconditionalFor": [+ "notices"+ ]+ }+ ],+ "thinClient": "none",+ "thinClientRoutedSubcommands": []+ },"onboard": {"hasSwitchCase": true,"phase": "post-connect",diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.jsonindex f35c4dfe86..1110dd7371 100644--- a/test/fixtures/goldens/cli/membership-sets.json+++ b/test/fixtures/goldens/cli/membership-sets.json@@ -122,6 +122,7 @@"embeddings","engine","enrich",+ "errors","eval","export","extract",@@ -150,6 +151,7 @@"models","mounts","notability-eval",+ "notices","onboard","orphans","pages",@@ -221,6 +223,7 @@"embeddings","engine","enrich",+ "errors","eval","export","extract",@@ -239,6 +242,7 @@"mcp","migrate","models",+ "notices","pages","pglite-repair","post-upgrade",diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 4c02d41187..a13442d5a9 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -688,6 +688,7 @@"matchesSlugAllowList","normalizeSlugPrefix","opAllowedForBoundClient",+ "opError","operations","operationsByName","parseTtlParam",@@ -720,6 +721,7 @@"acquireLock","getPgliteKernelLockPath","getPgliteMigrationLockPath",+ "heldLockFor","inspectLockHolder","isPidReusedByOtherProgram","isProcessAlive",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 99970b8152..ca12d551f7 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1644,7 +1644,7 @@"cause?: unknown","message: string","name: string",- "reason: \"unknown\" | \"timeout\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"network\" | \"auth\" | \"rate_limit\" | \"payload_too_large\"",+ "reason: \"unknown\" | \"timeout\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"payload_too_large\" | \"network\" | \"auth\" | \"rate_limit\"","stack?: string | undefined","status?: number | undefined"],@@ -2446,6 +2446,7 @@"brain?: { audience?: string; } | undefined","chat_fallback_chain?: string[] | undefined","chat_model?: string | undefined",+ "consent?: { preapprove?: { paid?: { max_usd_per_run?: number; }; persistent_install?: boolean; }; } | undefined","content_sanity?: { bytes_warn?: number; bytes_block?: number; junk_patterns_enabled?: boolean; disabled_patterns?: string[]; disabled?: boolean; junk_disposition?: \"quarantine\" | \"reject\"; max_markup_ratio?: number; prose_check_enabled?: boolean; } | undefined","cycle?: Record<string, string> | undefined","dashscope_api_key?: string | undefined",@@ -5407,6 +5408,7 @@"cliHints?: { name?: string; aliases?: string[]; positional?: string[]; stdin?: string; hidden?: boolean; } | undefined","description: string","handler: (ctx: OperationContext, params: Record<string, unknown>) => Promise<unknown>",+ "idempotent?: boolean | undefined","localOnly?: boolean | undefined","mutating?: boolean | undefined","name: string",@@ -5429,6 +5431,7 @@"config: GBrainConfig","deferEmbeds?: boolean | undefined","dryRun: boolean",+ "emitNotice?: ((n: Notice) => void) | undefined","emitResponseMeta?: ((key: string, value: unknown) => void) | undefined","engine: BrainEngine","explicitReadBinding?: ExplicitReadBinding | undefined",@@ -5451,16 +5454,23 @@{"kind": "class","members": [+ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"full_resync_required\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_pricing\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"overlapping_path\" | \"parse_error\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"request_already_submitted\" | \"requirements_changed\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_in_progress\" | \"target_escape\" | \"topology_change_required\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",+ "canonicalCode: string","cause?: unknown","code: ErrorCode",+ "contractVersion?: 1 | undefined","detail?: string | undefined","docs?: string | undefined",+ "fix?: Action | undefined","message: string","name: string",+ "notices?: Notice[] | undefined","protocolVersion?: number | undefined",+ "reason?: string | undefined","stack?: string | undefined","suggestion?: string | undefined",- "toJSON: () => { write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",+ "toJSON: () => { contract_version?: 1 | undefined; notices?: unknown[] | undefined; fix?: unknown; why?: string | undefined; reason?: string | undefined; write_error?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | undefined; write_request?: WriteReceipt | undefined; error: ErrorCode; code: string; message: string; suggestion: string | undefined; docs: string | undefined; detail: string | undefined; protocol_version: number | undefined; }",+ "why?: string | undefined","writeError?: \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | undefined","writeRequest?: WriteReceipt | undefined"],@@ -5469,6 +5479,7 @@"new (code: ErrorCode, message: string, suggestion?: string | undefined, docs?: string | undefined) => OperationError"],"statics": [+ "bare: (code: RegistryCode, message: string, reason: string) => OperationError","captureStackTrace: { (targetObject: object, constructorOpt?: Function): void; (targetObject: object, constructorOpt?: Function): void; (targetObject: object, constructorOpt?: Function): void; }","isError: { (error: unknown): error is Error; (value: unknown): value is Error; (value: unknown): value is Error; }","prepareStackTrace: (err: Error, stackTraces: NodeJS.CallSite[]) => any",@@ -5537,6 +5548,13 @@"(auth: Pick<AuthInfo, \"boundSlugPrefixes\" | \"fenceProjectionDegraded\" | \"allowedOperations\" | \"grantProjectionDegraded\"> | undefined, op: Pick<Operation, \"name\" | \"scope\" | \"mutating\">) => boolean"]},+ {+ "kind": "function",+ "name": "opError",+ "signature": [+ "(code: RegistryCode, message: string, suggestion: string, opts?: OpErrorOpts) => OperationError"+ ]+ },{"kind": "variable","name": "operations",@@ -5957,6 +5975,7 @@"kind": "interface","members": ["acquired: boolean",+ "acquiredAt?: number | undefined","heartbeat?: NodeJS.Timeout | undefined","lockDir: string","lockPath?: string | undefined",@@ -5979,7 +5998,9 @@{"kind": "interface","members": [+ "acquiredAt?: number | undefined","held: boolean",+ "http?: boolean | undefined","isServe?: boolean | undefined","pid?: number | undefined"],@@ -6028,6 +6049,13 @@"(dataDir: string) => string"]},+ {+ "kind": "function",+ "name": "heldLockFor",+ "signature": [+ "(dataDir: string | undefined) => LockHandle | null"+ ]+ },{"kind": "function","name": "inspectLockHolder",diff --git a/test/get-agent-job.test.ts b/test/get-agent-job.test.tsindex 65b0350122..cec929626d 100644--- a/test/get-agent-job.test.ts+++ b/test/get-agent-job.test.ts@@ -91,7 +91,8 @@ async function seedJob(opts: {describe('get_agent_job op surface', () => {it('declares scope=agent and a required numeric id param', () => {expect(get_agent_job.scope).toBe('agent');- expect(get_agent_job.mutating).toBeUndefined();+ // Agent contract v1 (A2): every op declares its effect; this read is non-mutating.+ expect(get_agent_job.mutating).toBe(false);expect((get_agent_job.params.id as any).required).toBe(true);expect((get_agent_job.params.id as any).type).toBe('number');expect(typeof (get_agent_job.params.id as any).description).toBe('string');diff --git a/test/notice-ledger.test.ts b/test/notice-ledger.test.tsindex 8dc8ffbe58..f3e6822f92 100644--- a/test/notice-ledger.test.ts+++ b/test/notice-ledger.test.ts@@ -73,3 +73,23 @@ describe('mute store', () => {}});});++describe('mute_notice op', () => {+ test('remote callers mute for their own client; non-muteable codes refuse with the valid list', async () => {+ const { noticesOperations } = await import('../src/core/ops/notices.ts');+ const op = noticesOperations.find(o => o.name === 'mute_notice')!;+ expect([op.mutating, op.idempotent, op.scope]).toEqual([true, true, 'write']);+ const home = mkdtempSync(join(tmpdir(), 'gbrain-mute-op-'));+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ const ctx = { remote: true, auth: { clientId: 'client-a' } } as never;+ expect(await op.handler(ctx, { code: 'backup_coverage' })).toMatchObject({ muted: true, scope: 'client', muted_codes: ['backup_coverage'] });+ expect([...mutedNoticeCodes()]).toEqual([]);+ expect([...mutedNoticeCodes('client-a')]).toEqual(['backup_coverage']);+ await expect(op.handler(ctx, { code: 'keyword_only' })).rejects.toMatchObject({ code: 'invalid_params' });+ });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex ee9b04fc5f..4d5cea1f05 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -180,6 +180,7 @@ const LEDGER: Record<string, string> = {loops_close: 'test/ops-loops.test.ts',loops_mute: 'test/ops-loops.test.ts',loops_unmute: 'test/ops-loops.test.ts',+ mute_notice: 'test/notice-ledger.test.ts',// v0.46.28.0+ master-wave ops, mapped at the test-gap-wave master merge.fetch: 'test/deep-research-fetch.test.ts',get_usage: 'test/chat-usage.test.ts',diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.tsindex f9b01d04ff..cbc1562cc2 100644--- a/test/remote-privacy-sweep.test.ts+++ b/test/remote-privacy-sweep.test.ts@@ -370,6 +370,8 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {loops_close: 'error',loops_mute: 'error',loops_unmute: 'error',+ // agent contract v1 A6: the generic invocation omits the required `code` → validation error.+ mute_notice: 'error',sources_remove: 'error',submit_job: 'error',get_job: 'error',diff --git a/test/serve-http-mcp-dispatch-context.serial.test.ts b/test/serve-http-mcp-dispatch-context.serial.test.tsindex 4ccc1d3ee8..c91e3b75a3 100644--- a/test/serve-http-mcp-dispatch-context.serial.test.ts+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts@@ -87,7 +87,7 @@ async function rpc(base: string, token: string, method: string, params?: unknownreturn JSON.parse(dataLine ? dataLine.slice('data:'.length) : text).result;}-const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'remote', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];+const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'noticeLedger', 'remote', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];describe('POST /mcp dispatch context', () => {test('full surface: remote http dispatch with the verified auth and token source scope', async () => {diff --git a/test/sources.test.ts b/test/sources.test.tsindex 0a4ccf6f44..fbe9d3d147 100644--- a/test/sources.test.ts+++ b/test/sources.test.ts@@ -269,7 +269,7 @@ describe('sources remove', () => {test("refuses to remove the 'default' source", async () => {const { engine } = makeStub();const code = await withExitCapture(() => runSources(engine, ['remove', 'default', '--yes']));- expect(code).toBe(3);+ expect(code).toBe(2); // agent contract v1 A3: invalid input exits 2 (3 is confirmation_required)});test('refuses without --yes', async () => {