Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(guards): ratchets after A2/A4 merge (pages.ts tags, dispatchToolCall under 300, callable reachable, structural suites); gbrain call envelope via dispatch

garrytan8ad4c206c30b
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index a85bee7a7c..f04d9be99a 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -80,7 +80,6 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/core/ingestion/sources/file-watcher.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },
- { path: 'src/core/ops/callable.ts', reason: 'held: agent operator wave A0 freeze; tools/list + dispatch wiring lands in A2 on the collector' },
{ path: 'src/core/readiness.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (E/F readiness producers) land on the collector' },
{ path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },
];
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 65e75800a5..e46ca62054 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -63,5 +63,4 @@ src/core/sources-ops.ts addSource 317 seed: W5 baseline, refactor wave 1 (decomp
src/core/think/index.ts runThink 450 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/transcripts/ingest.ts runTranscriptsIngest 317 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/workspace-push.ts workspacePush 312 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/mcp/dispatch.ts dispatchToolCall 325 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 eval wave N5-1: hot-memory invalidation after mutating ops (success and failure paths)
src/mcp/http-transport.ts startHttpTransport 408 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ce7b18ca38..20ec9ce8a5 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -39,6 +39,6 @@ src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in
src/core/config.ts 1824 ratchet +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
-src/core/ops/pages.ts 644 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso
+src/core/ops/pages.ts 652 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only)
src/core/search/mode.ts 1527 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part
src/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 9b194a4d89..0add47e6c1 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -146,6 +146,7 @@ test/eval-synthesize-concepts-routing.test.ts dispatch-layer source pins (routin
test/eval-synthesize-concepts-routing.test.ts subprocess smoke — end-to-end routing 1 source-surface-helper
test/eval-takes-bootstrap.test.ts corpus integrity 4 readFileSync
test/exit-classification.test.ts consumer wire-up — helper used by all 3 sites (no inline filters left) 5 doctor-source-helper,readFileSync,source-surface-helper
+test/exit-codes.test.ts exit code table 5 readFileSync
test/export-publication.test.ts (file-level) 6 readFileSync
test/extract-atoms-drain-errors.test.ts runExtractAtomsDrainForSource forwards typed per-item failures (#4730) 1 readFileSync
test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on provider_failure (issue #3218) 3 readFileSync,source-surface-helper
diff --git a/src/commands/call.ts b/src/commands/call.ts
index 8eaa9b27ba..0267ec900d 100644
--- a/src/commands/call.ts
+++ b/src/commands/call.ts
@@ -7,10 +7,9 @@ import { getCliOptions } from '../core/cli-options.ts';
import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
-import { cliRenderContext, toAgentError } from '../core/agent-output.ts';
import { exitCodeForCode } from '../core/error-catalogue.ts';
+import { localCallErrorEnvelope } from '../mcp/dispatch.ts';
import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
-import { operations } from '../core/operations.ts';
/**
* `gbrain call <tool> <json>` — trusted local op-dispatch surface.
@@ -104,11 +103,7 @@ export async function runCall(
if (await reportPersistenceCliError(error, true, out)) return;
// Agent contract v1 (A1): `gbrain call` is a JSON surface, so a failure is
// the same envelope an MCP caller gets, on stdout, with the registry's exit.
- const op = operations.find(o => o.name === tool);
- const envelope = toAgentError(error, {
- transport: 'cli', op: tool, mutating: op?.mutating === true, idempotent: op?.idempotent === true,
- outcome: op?.mutating ? 'unknown' : 'failed', render: cliRenderContext(),
- });
+ const envelope = localCallErrorEnvelope(tool, error);
await out(JSON.stringify(envelope, null, 2) + '\n');
console.error(`Error [${envelope.code}]: ${envelope.message}`);
setCliExitVerdict(exitCodeForCode(envelope.code));
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 4a0c3899c5..a530de0958 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -13,7 +13,7 @@ import type { OperationContext, AuthInfo } from '../core/operations.ts';
import { loadConfig } from '../core/config.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';
-import { toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';
+import { cliRenderContext, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';
import { isCallable } from '../core/ops/callable.ts';
import { logVerbUsage } from '../core/verbs/usage-log.ts';
import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';
@@ -477,6 +477,16 @@ export function dispatchRenderContext(opts: DispatchOpts): RenderContext {
};
}
+/** `gbrain call`'s failure envelope: same normaliser, CLI render context, the op's own effect tags. */
+export function localCallErrorEnvelope(tool: string, e: unknown) {
+ const op = operations.find(o => o.name === tool);
+ return toAgentError(e, {
+ transport: 'cli', op: tool, mutating: op?.mutating === true, idempotent: op?.idempotent === true,
+ outcome: op?.mutating ? 'unknown' : 'failed', render: cliRenderContext(),
+ db: { url: configuredDbUrlForClassify(), brainId: brainIdForClassify() },
+ });
+}
+
/** The one error result path: toAgentError → exactly one content block. */
export function errorResult(e: unknown, opts: DispatchOpts, extra: { op?: string; mutating?: boolean; idempotent?: boolean; notices?: Notice[] } = {}): ToolResult {
if (extra.notices?.length && e instanceof OperationError) e.notices = [...(e.notices ?? []), ...extra.notices];
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 04a44c88df..cd9018afec 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -486,8 +486,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
// unconditionally, so gates-off served the exact listed-but-denied
// catalog lie E5 (test/truthful-catalog.e2e-lite.test.ts) pins out.
const gateDisabled = await disabledOpsForPublishGates(engine, fileConfig);
- // Agent contract v1 (A2): the one callability predicate + the bound-client fence.
- const publishGates = publishGatesFromDisabled(surfacedOps, gateDisabled);
+ const publishGates = publishGatesFromDisabled(surfacedOps, gateDisabled); // A2: one callability predicate + bound-client fence
const visibleTools = tools.filter(t => {
const op = operationsByName[t.name];
return op && isCallable(op, { transport: 'http', surface, scopes: auth.auth!.scopes, publishGates, allowedOps: surfaceAllowedOps })
diff --git a/test/callable-predicate.test.ts b/test/callable-predicate.test.ts
index 9ed47ded32..a565762d34 100644
--- a/test/callable-predicate.test.ts
+++ b/test/callable-predicate.test.ts
@@ -16,7 +16,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
const SURFACES = ['verbs', 'starter', 'full'] as const;
const SCOPE_SETS: readonly string[][] = [['read'], ['read', 'write'], ['admin'], ['agent'], ['admin', 'skills_member_self']];
-const GATE_STATES = [{}, { 'mcp.publish_skills': true, 'mcp.publish_advisor': true }];
+const GATE_STATES: Record<string, boolean>[] = [{}, { 'mcp.publish_skills': true, 'mcp.publish_advisor': true }];
/** The pre-A2 HTTP list filter, kept here as the independent oracle. */
function legacyHttpList(surface: typeof SURFACES[number], scopes: string[], gates: Record<string, boolean>): string[] {