Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(scanner): B9 rules flag-in-mcp-text, in-scope-placeholder, retry-on-mutating with fixtures and shrink-only baselines
garrytan72fbe0026fc0
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex d20958734c..b5be97fd3d 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -11,4 +11,6 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `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 (`empty_retrieval`, `unknown_param`, `listing_truncated`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.- `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/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.serial.test.ts`.-- `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). Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.+- `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), a bare `--flag` in MCP-visible error text or op descriptions outside a full `gbrain …` command (`flag-in-mcp-text`), a `<placeholder>` in a fix argv without declared `inputs` or in an error suggestion (`in-scope-placeholder`), "retry" advice from a mutating non-idempotent op handler (`retry-on-mutating`), plus unregistered codes and code naming (never baselined). Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.+- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.+- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.diff --git a/scripts/agent-contract-baselines/flag-in-mcp-text.tsv b/scripts/agent-contract-baselines/flag-in-mcp-text.tsvnew file mode 100644index 0000000000..54f01a5331--- /dev/null+++ b/scripts/agent-contract-baselines/flag-in-mcp-text.tsv@@ -0,0 +1,6 @@+# shrink-only baseline for scripts/check-agent-contract.ts rule flag-in-mcp-text: path<TAB>count+src/core/ops/attribution.ts 1+src/core/ops/extraction.ts 2+src/core/ops/insights.ts 1+src/core/ops/search.ts 2+src/mcp/surface.ts 6diff --git a/scripts/agent-contract-baselines/in-scope-placeholder.tsv b/scripts/agent-contract-baselines/in-scope-placeholder.tsvnew file mode 100644index 0000000000..e7f8cca697--- /dev/null+++ b/scripts/agent-contract-baselines/in-scope-placeholder.tsv@@ -0,0 +1,5 @@+# shrink-only baseline for scripts/check-agent-contract.ts rule in-scope-placeholder: path<TAB>count+src/commands/sources-retry-held.ts 2+src/core/connectors/connector-text.ts 1+src/core/ops/context.ts 2+src/core/persistence/effect-git.ts 1diff --git a/scripts/agent-contract-baselines/retry-on-mutating.tsv b/scripts/agent-contract-baselines/retry-on-mutating.tsvnew file mode 100644index 0000000000..0bb73719d2--- /dev/null+++ b/scripts/agent-contract-baselines/retry-on-mutating.tsv@@ -0,0 +1,2 @@+# shrink-only baseline for scripts/check-agent-contract.ts rule retry-on-mutating: path<TAB>count+src/core/ops/jobs.ts 1diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.tsindex 493ccf7b3e..7ae1ec4264 100644--- a/scripts/check-agent-contract.ts+++ b/scripts/check-agent-contract.ts@@ -19,6 +19,12 @@* stdio-inherit `stdio: 'inherit'` outside spawnCliChild (cli-force-exit.ts)* marker-literal [AGENT] / [SHOW USER] / "ACTION FOR THE AGENT:" outside agent-output.ts / agent-markers.ts* verify-not-read-only a fix `verify.argv` naming a command not declared read_only+ * flag-in-mcp-text a bare `--flag` in MCP-visible error text or an op description (src/core/ops, src/mcp)+ * outside a full `gbrain …` command; render per surface with paramUse()/invalidParam()+ * in-scope-placeholder a `<placeholder>` in a fix argv without declared `inputs`, or in an error suggestion+ * (fill the value from scope; only genuinely unknown values are `inputs`)+ * retry-on-mutating "retry" advice in an error raised by a mutating, non-idempotent op handler+ * (say "inspect state before resubmitting"; retry only with the same request identity)* unregistered-code a literal error code thrown in src/ missing from src/core/error-registry.ts (never baselined)* code-naming a registry code that is not snake_case or carries a transport prefix (never baselined)*@@ -36,11 +42,13 @@ const DOCS = 'docs/designs/AGENT_OPERATOR_WAVE.md (B9)';export type Rule =| 'suggestionless-operation-error' | 'throw-new-error-in-ops' | 'hand-built-command' | 'legacy-advice-key'| 'interactive-io' | 'yes-rerun-string' | 'stdio-inherit' | 'marker-literal' | 'verify-not-read-only'+ | 'flag-in-mcp-text' | 'in-scope-placeholder' | 'retry-on-mutating'| 'unregistered-code' | 'code-naming';export const BASELINED_RULES: readonly Rule[] = ['suggestionless-operation-error', 'throw-new-error-in-ops', 'hand-built-command', 'legacy-advice-key','interactive-io', 'yes-rerun-string', 'stdio-inherit', 'marker-literal', 'verify-not-read-only',+ 'flag-in-mcp-text', 'in-scope-placeholder', 'retry-on-mutating',];export interface Hit { rule: Rule; file: string; line: number; text: string }@@ -49,6 +57,33 @@ const LEGACY_ADVICE_KEYS = new Set(['next_action', 'fix_argv', 'agent_action', 'const MARKER_RE = /\[\/?AGENT\]|\[\/?SHOW USER\]|ACTION FOR THE AGENT:/;const YES_RERUN_RE = /re-?run\b[^.\n]{0,40}--yes/i;const TRANSPORT_PREFIX = /^(mcp|http|cli|stdio)_/;+const ERROR_CALLEE = /^(OperationError|verbError|opError|OperationError\.bare|hostOnlyError)$/;+const FLAG_RE = /(?:^|[\s(`'"])--[a-z][a-z0-9-]*/;+const PLACEHOLDER_RE = /<(?:source|source[-_]id|slug|id|request[-_]id|client[-_]id|page|uuid|brain|name)>/;+const RETRY_RE = /\bretry\b/i;+const SAFE_RETRY_RE = /(?:do not|don't|never) retry|same request_id|same request identity/i;++/** Text args of an error constructor call: message (1) and suggestion (2); hostOnlyError's message is arg 2. */+function errorTextArgs(n: ts.CallExpression | ts.NewExpression, sf: ts.SourceFile): ts.Expression[] {+ const callee = n.expression.getText(sf);+ const args = n.arguments ?? [];+ return callee === 'hostOnlyError' ? args.slice(2, 3) : args.slice(1, 3);+}++/** The op object literal (has `mutating:` and `handler:`) whose handler encloses `n`, if any. */+function enclosingOp(n: ts.Node): ts.ObjectLiteralExpression | undefined {+ for (let p = n.parent; p; p = p.parent) {+ if (ts.isPropertyAssignment(p) && propName(p) === 'handler' && ts.isObjectLiteralExpression(p.parent)) return p.parent;+ }+ return undefined;+}++function literalProp(obj: ts.ObjectLiteralExpression, name: string): string | undefined {+ for (const p of obj.properties) {+ if (ts.isPropertyAssignment(p) && propName(p) === name) return p.initializer.getText();+ }+ return undefined;+}/** Read-only invocations a verify step may always name (doctor --only is the canonical one). */const STATIC_READ_ONLY = new Set(['doctor', 'errors', 'status', 'get', 'search', 'query', 'list', 'write-request', 'write-requests', 'whoami', 'stats']);/** Read-only subcommands of otherwise-mutating commands. */@@ -73,6 +108,16 @@ function stringText(n: ts.Node): string | undefined {return undefined;}+/** String text of a literal or a `'a' + 'b'` concatenation of literals. */+function flatText(n: ts.Node, sf: ts.SourceFile): string | undefined {+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.PlusToken) {+ const l = flatText(n.left, sf); const r = flatText(n.right, sf);+ return l !== undefined && r !== undefined ? l + r : undefined;+ }+ if (ts.isParenthesizedExpression(n)) return flatText(n.expression, sf);+ return stringText(n);+}+function literalCodes(n: ts.Node): string[] {if (ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n)) return [n.text];if (ts.isConditionalExpression(n)) return [...literalCodes(n.whenTrue), ...literalCodes(n.whenFalse)];@@ -152,6 +197,27 @@ export function scan(root: string = ROOT): Hit[] {const args = n.arguments ?? [];if (args.length < 3 || args[2]!.getText(sf) === 'undefined') add('suggestionless-operation-error', n);}+ if ((ts.isCallExpression(n) || ts.isNewExpression(n)) && ERROR_CALLEE.test(n.expression.getText(sf))) {+ const texts = errorTextArgs(n, sf);+ for (const arg of texts) {+ const t = stringText(arg);+ if (t === undefined) continue;+ if (isOpsOrMcp && FLAG_RE.test(t) && !t.includes('gbrain ')) add('flag-in-mcp-text', arg);+ }+ const suggestion = n.expression.getText(sf) === 'hostOnlyError' ? undefined : stringText((n.arguments ?? [])[2] ?? n);+ if (suggestion !== undefined && (n.arguments ?? [])[2] && PLACEHOLDER_RE.test(suggestion)) add('in-scope-placeholder', n.arguments![2]!);+ const op = enclosingOp(n);+ if (op && suggestion !== undefined && (n.arguments ?? [])[2] && literalProp(op, 'mutating') === 'true' && literalProp(op, 'idempotent') !== 'true'+ && RETRY_RE.test(suggestion) && !SAFE_RETRY_RE.test(suggestion)) add('retry-on-mutating', n.arguments![2]!);+ }+ if (ts.isArrayLiteralExpression(n) && ts.isPropertyAssignment(n.parent) && propName(n.parent) === 'argv'+ && ts.isObjectLiteralExpression(n.parent.parent) && literalProp(n.parent.parent, 'inputs') === undefined+ && n.elements.some(e => /^<[^>]+>$/.test(stringText(e) ?? ''))) add('in-scope-placeholder', n);+ if (isOpsOrMcp && path.startsWith('src/core/ops/') && ts.isPropertyAssignment(n) && propName(n) === 'description'+ && ts.isObjectLiteralExpression(n.parent) && literalProp(n.parent, 'handler') !== undefined) {+ const t = flatText(n.initializer, sf);+ if (t !== undefined && FLAG_RE.test(t) && !t.includes('gbrain ')) add('flag-in-mcp-text', n);+ }if (ts.isThrowStatement(n) && n.expression && ts.isNewExpression(n.expression) && n.expression.expression.getText(sf) === 'Error'&& (isOpsOrMcp || insideHandler(n))) add('throw-new-error-in-ops', n);if (ts.isPropertyAssignment(n)) {diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.tsindex 81cc538046..9be7c2980c 100644--- a/src/core/ops/request-tools.ts+++ b/src/core/ops/request-tools.ts@@ -225,7 +225,7 @@ const request_tools: Operation = {throw opError('rate_limited','surface persistence is rate-limited to ~5 changes per hour per client (D14.5).',- `Retry after ~${rl.retryAfter ?? 60}s.`,+ `Nothing changed. Call request_tools with this surface again after ~${rl.retryAfter ?? 60}s.`,);}// Atomic re-check: a concurrent operator pin between the SELECT anddiff --git a/src/core/persistence/purge-params.ts b/src/core/persistence/purge-params.tsindex 085bc1e12d..ad2d675e55 100644--- a/src/core/persistence/purge-params.ts+++ b/src/core/persistence/purge-params.ts@@ -1,12 +1,18 @@-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { hostFix } from '../ops/op-fix.ts';++const SAFE_SLUG = /^[a-z0-9][a-z0-9._/-]*$/i;/** Shape/trust checks do not read the current page or resolve a replay target. */export function assertPurgeParams(params: Record<string, unknown>, remote: boolean | undefined): void {+ const slug = typeof params.slug === 'string' && SAFE_SLUG.test(params.slug) ? params.slug : undefined;if (params.purge !== undefined && typeof params.purge !== 'boolean') {- throw new OperationError('invalid_params', 'purge must be a boolean.', 'Pass purge: true (CLI: gbrain delete <slug> --purge).');+ throw opError('invalid_params', 'purge must be a boolean.', `Pass purge: true (CLI: gbrain delete ${slug ?? '<slug>'} --purge).`);}if (params.purge === true && remote !== false) {- throw new OperationError('permission_denied', 'purge is only available to the local CLI.',- 'Remote callers soft-delete only; run `gbrain delete <slug> --purge` on the host to remove a page immediately.');+ throw opError('permission_denied', 'purge is only available to the local CLI.',+ `Remote callers soft-delete only (omit purge; restore_page can undo it for 72h). To remove the page immediately the user runs \`gbrain delete ${slug ?? '<slug>'} --purge\` on the brain host.`,+ slug ? { fix: hostFix({ remote: true }, ['gbrain', 'delete', '--purge', '--', slug],+ 'Purging skips the 72-hour restore window, so only the trusted CLI on the brain host may do it.', { consent: ['destructive'] }) } : {});}}diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-flag-text/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-flag-text/src/core/error-registry.tsnew file mode 100644index 0000000000..b70481c8a7--- /dev/null+++ b/test/fixtures/guards/check-agent-contract.ts/bad-flag-text/src/core/error-registry.ts@@ -0,0 +1,3 @@+export const CODES = {+ invalid_params: { class: 'caller', summary: 'x' },+} as const;diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-flag-text/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-flag-text/src/core/ops/sample.tsnew file mode 100644index 0000000000..0edc8f0ee6--- /dev/null+++ b/test/fixtures/guards/check-agent-contract.ts/bad-flag-text/src/core/ops/sample.ts@@ -0,0 +1,2 @@+declare function opError(...args: unknown[]): Error;+export function f() { throw opError('invalid_params', 'Bad input.', 'Re-run with --no-pull.'); }diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-placeholder/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-placeholder/src/core/error-registry.tsnew file mode 100644index 0000000000..b70481c8a7--- /dev/null+++ b/test/fixtures/guards/check-agent-contract.ts/bad-placeholder/src/core/error-registry.ts@@ -0,0 +1,3 @@+export const CODES = {+ invalid_params: { class: 'caller', summary: 'x' },+} as const;diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-placeholder/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-placeholder/src/core/ops/sample.tsnew file mode 100644index 0000000000..cef03c1bc1--- /dev/null+++ b/test/fixtures/guards/check-agent-contract.ts/bad-placeholder/src/core/ops/sample.ts@@ -0,0 +1 @@+export const fix = { argv: ['gbrain', 'get', '<slug>'], consent: [], actor: 'agent', why: 'w', requires_exclusive: false };diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-retry-mutating/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-retry-mutating/src/core/error-registry.tsnew file mode 100644index 0000000000..b70481c8a7--- /dev/null+++ b/test/fixtures/guards/check-agent-contract.ts/bad-retry-mutating/src/core/error-registry.ts@@ -0,0 +1,3 @@+export const CODES = {+ invalid_params: { class: 'caller', summary: 'x' },+} as const;diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-retry-mutating/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-retry-mutating/src/core/ops/sample.tsnew file mode 100644index 0000000000..2b814c3573--- /dev/null+++ b/test/fixtures/guards/check-agent-contract.ts/bad-retry-mutating/src/core/ops/sample.ts@@ -0,0 +1,2 @@+declare function opError(...args: unknown[]): Error;+export const op = { name: 'put_x', mutating: true, handler: async () => { throw opError('invalid_params', 'Failed.', 'Retry the call.'); } };diff --git a/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.tsindex 2b1322857c..db96a0a539 100644--- a/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts+++ b/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts@@ -1,2 +1,4 @@declare function opError(...args: unknown[]): Error;export function f() { throw opError('invalid_params', 'Bad input.', 'Pass a slug.', { fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'w', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--json'] } } }); }+export const inputFix = { argv: ['gbrain', 'pricing', 'set', '<model>'], inputs: [{ name: 'model', how: 'h' }], consent: [], actor: 'agent', why: 'w', requires_exclusive: false };+export const op = { name: 'put_x', mutating: true, idempotent: true, handler: async () => { throw opError('invalid_params', 'Failed.', 'Retry with the same request_id; run `gbrain sync --no-pull` first.'); } };