Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
38.6 KB
Raw Blame

Key files: Agent operator contract

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG. Spec: docs/designs/AGENT_OPERATOR_WAVE.md; wire goldens: test/fixtures/agent-contract/v1/.

  • src/core/fix-routing.ts — A1 render-time routing pin: pinRouting(argv, routing) appends --brain and the command's source flag (--source; --source-id for a record declaring routes_source: '--source-id', extract, whose --source is a mode selector and never blocks the pin) before a bare -- for commands that route them (shared ops registered by operations.ts; CLI-only commands from the generated CLI_ROUTING_FLAGS, built from the command table's phase/routes_source and each command's code). Holds the CLI process's routing provider (installCliRouting, installed by src/cli/fix-routing-provider.ts; never for serve) and the first source the invocation resolved (noteResolvedSource, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: test/fix-routing.test.ts; journey proof in test/agent-journey-recovery.serial.test.ts.

  • 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... (line truncated to 2000 chars)

  • 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, and reason_overrides: a reason whose class and exit replace the code's on the envelope and the CLI exit); 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, plus an Override: line per reason override) 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). #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. A notice's unrendered `Notic... (line truncated to 2000 chars)

  • 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; a pglite_busy with reason legacy_owner_unverified renders its own ask_user fix, retryable: false, exit 3). Test: test/cli-error-render.test.ts.

  • src/cli/help/<command>.ts + src/cli/help/render.ts + src/cli/help/validate.ts — D3/D4 curated CLI help. Each spec module exports help: CliHelpSpec (summary, usage, flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}], 2–4 examples, end_of_options?) and is loaded lazily through its command-table record's help: () => import('./help/<name>.ts') (literal, so bun build --compile bundles it and gbrain --version loads none; pinned by test/cli-command-table.test.ts and scripts/check-compile-autoload.sh). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and --yes is listed wherever the handler parses it. printCuratedHelp answers gbrain <cmd> --help/-h first in main()'s help short-circuit, engine-free (human table with type/values/consent; --help --json one document {command, …spec, contract_version}). curatedFlagError(command, args) (called in main() after the unknown-flag check) refuses a missing/non-numeric number value or an out-of-set enum value with invalid_params (exit 2) via flagValueError, example value drawn from the spec's examples; --flag=value and --flag value, stops at a bare --; string flags (e.g. onboard's --max-usd off) are not checked. unknownFlagError draws did-you-mean candidates from the curated flags. Tests: test/cli-help-curated.test.ts, test/cli-help-curated-cli.test.ts. #8510: printHelpText(command, text, args) gives the same --help --json contract to a handler that prints its own help text with no curated spec: one {command, help, contract_version} document under --json, the text unchanged otherwise; dream, dream retriage and dream reset-key use it (test/dream-help-json-8510.test.ts). Other self-help commands that declare json still print their help through console.log, which the guard sends to stderr.

  • src/cli/flag-values.ts — strict numeric values for CLI-only flags (D4): intFlagValue / numberFlagValue (digits only, safe integer, [min, max]) and flagValueError raise invalid_params usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync --interval, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's *-numeric-flags/*-flags test.

  • src/cli/flag-validation.ts — the pre-dispatch unknown-flag validator (validateCommandFlags, findUnknownOpFlag) and the CLI alias table (buildCliAliases, cliAliases), moved verbatim out of src/cli/main.ts, which re-exports them. src/cli/skill-surface.ts imports them from here, so the skill drift surface never imports the dispatcher; main registers that surface with setSkillSurfaceProvider (src/core/skill-health.ts) so doctor, which the operations graph also loads, checks skill drift without importing the command table. Pinned by test/cli-flag-validation.test.ts.

  • src/cli/flag-equals.ts — --flag=value on CLI_ONLY commands (#7619). cliOnlyFlagArgs in src/cli/main.ts runs splitFlagEquals once after routing and the help printers that run no handler, before the self-help handlers' help path, strict arguments, flag validation and dispatch, so no = token reaches a handler that would drop it. It also covers the hand-parsed search modes|stats|tune|diagnose subcommands, the validation-exempt paths (jobs submit, whose consent check reads the = spending cap, and config except set) and the direct bun run src/commands/auth.ts entry (which strips and applies the global flags, hands auth local-writer to its own parser and runs the unknown-flag validator, findUnknownFlag with the same unknown_flag envelope and legacy keys, all as main does). Per registered --flag=value token: a switch refuses (invalid_params, exit 2: a boolean in the command's own table, curated help or SYNC_FLAGS for sync, a --no- negation, the command's COMMAND_SWITCHES (also the switches no shared evidence covers, such as agent --detach), or a name knownSwitches() finds boolean in the handler-free OPERATION_MANIFEST or any curated help, so --yes=n is never answered with --yes <value>); EQUALS_READERS, keyed by command or command sub (the sync --status alias reads as sync status, forget --purge is its own path, and repos reads the sources keys through READER_ALIASES), keeps the token where the handler on that path reads the = form itself, empty values included (that handler owns refusing them); elsewhere an empty or flag-like value refuses; the token splits into --flag value only when the command's own table declares a value; every other = form refuses with the two-argument spelling. Splitting a flag the subcommand never reads leaves its value as a stray positional that handlers taking the first numeric or non-flag token act on (forget --purge --reason=3 34 purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (extract links --source-id=x walked every source), so keys name the narrowest path. A short flag never takes = (-y=n refuses). NO_VALUE_FLAG_PATHS (the edge-proposals subcommands but list, which take the first numeric token as the id) refuse a value flag's = form with advice to leave it out, never --flag <value>. agent run is scanned only where parseRunFlags reads flags: the leading zone through RUN_VALUE_FLAGS (each value passes untouched) and BOOLEAN_TAIL_FLAGS from src/commands/agent.ts, plus flag-shaped --x= tokens, then, when the prompt holds no bare --, the trailing switches it hoists; one of its flags written with = inside the prompt, up to its first bare --, refuses with advice to write it before the prompt or put -- before the prompt, and parseRunFlags itself throws on a value flag written as two arguments there (#7672). A bare -- ends the scan only on END_OF_OPTIONS paths (agent run, frontmatter validate), whose handler stops there; serve, auth, frontmatter generate, questions and agent logs read flags after it, so past -- an = token that is not a registered flag refuses (the unknown-flag validator stops at --). A true/false word or 0/1 on a flag with no table entry (--apply=false, --expect=on) refuses naming both readings, never --apply <value>, and says a value never turns a switch off. sources pull --path= refuses, because main's database-free route matches only the exact token. On the hand-parsed search subcommands, which have no registry row, every = token but --json=true refuses with a neutral message that names the subcommand, echoes no value and vouches for no switch. --json=true becomes --json. Refusals name --flag=…, never the value. OWN_EQUALS_PARSERS (own =-aware parsers on every path that refuse = on their switches, retrieval-upgrade and migrate embeddings included; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens), call, config set, eval brainbench and every subcommand src/cli/strict-args.ts governs (strictSpecFor) keep their argv. scripts/generate-flag-registry.ts skips this module. Pinned by test/cli-flag-equals.test.ts (a table over every registered CLI_ONLY flag, both-direction pins of EQUALS_READERS against every = reader in src and of OWN_EQUALS_PARSERS against every = option parser, stray-positional, dropped-scope, consent and -- rows, own-parser switch refusals) and test/serve-flag-equals.test.ts (real CLI processes on PGLite, --json envelope, the direct auth.ts entry, serve -- --access= and frontmatter generate behind --help or -- included).

  • src/cli/search-row-format.ts — formatSearchRow: the human gbrain search|query line per row ([score] slug -- preview); a saved-fact row prints fact:<fact_id> <entity> and its date header and text on one line, never a page slug (#8411).

  • src/cli/search-timings.ts — gbrain search|query --timings (#7158; global flag claimed by search/query/ask in cli-options.ts): timeCliPhase books connect, context and remote in runSharedOperation/runThinClientRouted; searchTimingsDocument makes --json print {results, timings_ms, cost} (bare array without the flag) and searchTimingsLine the stderr line. Absent phase = did not run. Guide: docs/guides/search-explain.md. Test: test/cli-search-timings.test.ts.

  • src/cli/op-param-values.ts — opParamValue: typed values for shared ops from ParamDef inside parseOpArgs (number → finite, string enum → declared values), invalid_params with an example otherwise; mirrors MCP validateParams. opStructuredValue turns object/array flag text into its value: JSON, or for a string-item array a bare value or comma list (--types company, --types person,company, #7173); test/cli-types-param.test.ts. parseOpArgs also honours a bare -- (D6). Test: test/cli-op-typed-args.test.ts.

  • src/commands/init-json.ts + src/commands/init-first-run.ts — init --json (D2): the success document accumulates across init's branches and is written once when runInit returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the --prefer-postgres ladder still prints only its envelope). buildInitFirstRunNotices is the G5 seam: one first_run_decisions ask notice with decisions[] (search_mode, writeback, harness_wiring, skills_scaffold, then the settings in effect upkeep and conversation_archive, GST-2768: on or offered, archiveLine); the stdio onboarding cache reuses it with writeback and skills only, and setupFirstRunNotices is gbrain setup's form (from init --json: harness_wiring dropped, why/user_message framed as settings in effect that the agent relays in the install reply instead of a reply-to-continue question; Cat 41 wave 2, pinned by test/init-first-run.test.ts). firstRunBundle/harnessRegistrationCommand take gbrain init --surface. Tests: test/cli-json-guard.test.ts.

  • src/core/onboard/hosted-option.ts — the hosted_option coaching notice (gbrain.io, hosted GBrain): the one home of its URL, copy and ?ref= tags. gbrain setup appends it when it created the brain, printInAgentReady prints it after the in-agent ready text when init created the brain (its mute hint names that install's own launcher), and gbrain mcp expose's Session.finish adds it (JSON notices, one human line) on the run that wrote the first receipt and at Tailscale/service friction exits (EXPOSE_FRICTION_REASONS), never on the consent-pending document, --dry-run, --status or --remove. Bare gbrain init never shows it. Refs split publish (cli-mcp-expose) from friction exits (cli-mcp-expose-friction). Muted by the owner list or the stdio audience (hostedOptionMuted, i.e. mutedNoticeCodes('stdio')); writeHostedOption prints one plain line on a TTY and the notice block otherwise. No network call. Tests: test/hosted-option.test.ts, test/setup.test.ts, test/mcp-expose.test.ts.

  • src/core/onboard/mcp-onboarding.ts — onboarding coaching for the owner's stdio pipe. collectOnboardOpportunities(engine, signal, between?) is the one home of init's six counts (parallel for runInitNudge, sequential with yields for the background refresh; the stale-chunk count uses countStaleChunks' predicate, so soft-deleted and embed_skip pages are not backlog); a failed count is null and never reads as a gap, and onboardGaps applies init's thresholds (link < 0.7, timeline < 0.9; an empty brain has none). The per-brain cache (6 h TTL, GBRAIN_HOME/onboard-counts-<brain>.json, atomic write, partial runs not persisted) is loaded by startOnboardingRefresher and refreshed in the background only while the idle gate reports no request in flight (3 s budget); it also holds the pitchable gbrain features recommendations (pitchableFeatures, offer state read-only) and the stale-chunk backfill estimate. mcpOnboardingNotices is dispatch's one producer on the stdio success path: first_run_decisions (writeback + skills via mcpFirstRunNotices, from the second successful call, nothing persisted) and one coaching notice per class (onboard_stale_chunks, onboard_link_coverage, onboard_timeline_coverage, onboard_no_takes) when ONBOARD_CALL_AFFINITY names the call and the class's result predicate holds, plus features_auto_fix on get_backlinks/traverse_graph; fixes are the read-only get_health / gbrain onboard --check preview, the dismissal line names mute_notice only where it is callable. mutedFirstRunDecisionsNotice feeds doctor (memory_writeback) and gbrain onboard --check. HTTP never calls it. Test seams __warmOnboardingCacheForTests, __awaitOnboardingRefreshForTests, __resetMcpOnboardingForTests. Tests: test/mcp-onboarding.test.ts, test/init-nudge.test.ts, test/mcp-notice-channels.test.ts.

  • test/cli-contract.test.ts — D5: --help contract for every command-table record (exit 0, non-stub, curated flags only, --yes shown where parsed) against the shrink-only test/fixtures/cli-contract/help-baseline.json, and one success + one failure row per json-declared record.

  • src/cli/json-guard.ts — picks the --json guard mode for an invocation: on only when jsonRequested(argv) and the command-table record declares json: 'document' | 'ndjson'; wires the E11 json_document_missing hook (document mode, exit 0; the event records command, version, guard: 'document' and exit_code: 0, never argv values; outcome keeps its value, #6629/D26). The guard itself is installStdoutPipeDelivery({ json }) in src/core/cli-force-exit.ts: stdout writes and console.log/info/debug go to stderr, only writeStdoutFinal/writeNdjsonLine reach fd 1, a non-zero exit with no document writes the fallback document, spawnCliChild pipes child stdout to stderr. Test: test/cli-json-guard.test.ts. A record whose subcommands differ in shape declares jsonSubcommands (keyed by the first positional after the command; eval). writeCliError adds status:'error' to the envelope under the ndjson guard; writeCliRefusal (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under --json. D5 (test/cli-contract.test.ts) has one row per declaration, <command> <sub> included.

  • scripts/check-agent-contract.ts — syntax-only AST scanner (≈2 s) in bun run verify and guards-manifest.tsv (fixtures test/fixtures/guards/check-agent-contract.ts/). Rules: suggestion-less OperationError, throw new Error in ops/mcp/handlers, hand-built fix/next_action command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside interaction.ts/consent.ts, raw "re-run with --yes" strings outside consent.ts, stdio: 'inherit' outside spawnCliChild, marker literals outside agent-output.ts/agent-markers.ts, verify.argv naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: defaulted-suggestion (a function that builds an error through opError, new OperationError, usageError, invalidParam or hostOnlyError from a *suggestion/*hint parameter with a default, an optional marker or a ?? fallback) and generic-suggestion (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). funnelSites(files?) lists every funnel call site (invalid, fail, usage, deny, …) with its literal suggestion texts, resolving file-level string constants; test/helpers/agent-envelope.ts (expectFunnelSuggestions, envelopeFor, caught) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in scripts/agent-contract-baselines/<rule>.tsv; --update lowers them and refuses growth.

  • src/core/interop-notices.ts — Lane F notice producers (pure; callers emit). DEGRADED_STAGE_GUIDANCE (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one degraded_recall notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a rerank_failed stage names its reason, the fused_order fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: timeout/rate_limited repeat the same call after 5/20 s (actor: provider, next: wait), auth is the user's key (credentials), the rest run doctor verified by reranker_health (test/rerank-degraded-notice.serial.test.ts); none on a brain keyless by choice, whose why says no query text was sent and that gbrain doctor --json names the enable command). embeddingOptedOutFor reads the opt-out markers (search/query degraded reason embedding_disabled, recall keyword_only_embedding_disabled in search_degraded or facts_degraded.reason, think QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED); factEmbeddingDisabled (src/core/embedding-disabled.ts) gates every query and fact embed. With the call's _meta.retrieval.coverage, degradedRecallNotice leaves projection_pending out when no pending page could match the query, otherwise names the count in its why, and escalates when it is the only stage. That why is worded by class (#7492): text pages are being indexed; could-affect images (could_affect.pending_images, the sealable/reimport classes) never index on their own, so the why names gbrain projections drain, the paid re-import and doctor's text_projection_readiness, and when projection_pending is the only doctor stage the fix is that read-only check (gbrain doctor --only text_projection_readiness --json). sourceBindingNarrowedNotice (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit source_id read). recallStagesFor maps recall's search_degraded and facts_degraded.reason (question ranking) to stages. recallInteropNotices is dispatch's one producer call. chatKeyFix (credentials + paid, both providers, free fallback, never a key on a command line), keylessThinkNotice, thinkNotSavedNotice, degradedDedupNotice, privateFactNotice (#6606: a local... (line truncated to 2000 chars)

  • src/core/sources-not-readable.ts — assertUnscopedReadReachesPages, the sources_not_readable refusal (class host_only) dispatch runs after a handler's empty result (emptyRead, so a read that returns rows costs no extra query): an unscoped search/query/recall/list_pages (no source_id, no non-empty source_ids) from a remote connection with no source grant (no allowedSources, hasSourceGrant not true, no stdio binding; OAuth clients always carry a grant) whose federatedSearchScope holds no live page every reader of its source can read (pages kept to named readers, or private when remote reads exclude them, do not count, and the message says so; for recall and query, no world fact either) while another live, unarchived source does (GBRA-585). One CASE WHEN EXISTS read, fail-open on any error. The message and suggestion never name a hidden source; the fix is the host's gbrain sources federate <source> (hostFix, input source: ask the user), with the token rescope named in the suggestion. A scope holding pages that matched nothing and a brain with no pages read as before (test/mcp-sources-not-readable.test.ts).

  • src/core/degraded-stamp.ts — GBRA-200 degraded stamp (pure). degradedStampFor(op, result, meta, notices) derives {reasons} from the call's _meta.retrieval.degraded recall-affecting stages (keyword-only markers normalized to embed_unavailable; projection_pending dropped when no pending page could match), the result body's degraded fields (recall search_degraded/facts_degraded, degraded_reason, get_page file_held, think/synthesize GATHER_* warnings, search_exact, open_loops, rank_entities) and the call's kind: degraded result notices, read before the notice ledger dedupes them; null when clean. Dispatch writes _meta.degraded and appends degradedStampLine as the last content block; src/cli/op-notices.ts withDegradedStamp puts it on a --json object as degraded, else on stderr (the routed thin-client path uses the server's stamp). Vocabulary: AGENT_OPERATOR_v1.md, "Degraded stamp". Tests: test/degraded-stamp.test.ts (each class, pure), test/degraded-stamp-paths.serial.test.ts (dispatch on PGLite: provider down, timeout, rank bound, recall, think, keyless dedupe), test/degraded-stamp-cli.test.ts (real CLI).

  • src/mcp/status-mode.ts + src/commands/serve-status.ts + src/commands/serve-http-status.ts + src/core/serve-http-status-marker.ts — F4 status-only serve, stdio and --http. cli.ts hands over a host-brain serve (not --fail-fast/GBRAIN_SERVE_FAIL_FAST=1) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; runStatusModeServe is the one entry point for both transports and logs serve_status_mode_enter / serve_status_mode_recovered (reason, transport, elapsed_ms) as one-line JSON on stderr. probeStatus reads config + peekLock only; reprobe(state, connect) is the one re-probe (no lock attempt while blocked, resetReadinessMemo() before the throw-only connect from src/core/engine-connect.ts); a check that must run on every re-probe hooks the probeAgain wrapper in runStatusModeServe. stdio: a gated lazy engine (createDegradedEngine with the configured kind, reconnect statusReconnect, ≤1 attempt / 5 s inside tool calls) marked with StatusModeState; statusPayload → {status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}. --http: runHttpStatusServe binds one node:http listener with a mutable handler (/health 503 + Retry-After: 5 + instance; /mcp stateless SDK server with only gbrain_status; every other route a 503 serve_status_only envelope), each response built from the allowlist in httpStatusPayload/httpStatusEnvelope with reason collapsed to unavailable; a single-flight chained 5 s tick runs the re-probe, and on a connect runServe(..., { adoptServer }) builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (brain_unopenable); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker GBRAIN_HOME/serve-http-status-<port>.json {pid, instance_nonce, brain_id, bind, port, reason, since}... (line truncated to 2000 chars)

  • src/mcp/initialize-context.ts — per-initialize inputs for the generated instructions (httpInstructionTools: the tools/list filters with publish gates read on initialize; instructionReadiness: config plane + probed tier within 250 ms, HTTP view redacted) and stdioCapabilityReadiness (F2). Test: test/mcp-capabilities-readiness.test.ts.

  • src/mcp/hidden-tool-hint.ts + src/core/ops/cli-equivalent.ts — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets unknown_tool naming itself and its CLI equivalent (cliEquivalent: cliOnly argv, curated overrides, cliHints.name, else gbrain call). Where request_tools is callable and session widening is on, the fix is request_tools {surface:'full'} (next: run, argv kept); otherwise the CLI equivalent with actor user and a user_message; why names the lasting route (GBRAIN_SURFACE=full in the harness's per-server env, or a --surface full re-registration) and that an inherited GBRAIN_SURFACE overrides a pinned --surface. Read-only access never offers a widen. HTTP stays opaque. scripts/generate-plugin-tree.ts appends the same map as a per-skill note to generated starter-gap skills. Test: test/hidden-tool-hint.test.ts. D2: hiddenToolRoute(op, ToolConnection) is the one decision for every transport (callable | widen {surface} | host {read_only|surface|grant}): a widen is offered only when the widened connection could call the tool (read-only access, GBRAIN_MCP_FORCE_SURFACE, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with toolConnection(opts). hiddenToolNext turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).

  • Operation.cliOnly + cliOnlyRefusal (src/core/ops/callable.ts) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets trusted_local_only (error permission_denied) with the exact CLI command.

  • src/core/behavior-change-notice.ts — the one-time behavior_changes safety notice: a live chat_fallback_chain (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (cycle.lint_fix), smaller transcript parts re-embedded once (TRANSCRIPT_REINGEST_MULTIPLIER), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). BEHAVIOR_CHANGES is the one table of disclosed changes, each with the release that introduced it; rows a PR adds live in behavior-changes.d/<id>.md and reach the table through src/core/behavior-changes.generated.ts (RELEASED_BEHAVIOR_CHANGES, spread at its end (the notice lists releases oldest first whatever the table order)) once a release dates them, and function rows use since: releasedIn(id) (FENCE_REPAIR_MEASURED is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); BEHAVIOR_NOTICE_SINCE is the newest row's release (never VERSION), so the notice id behavior_changes@<since> moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline (gbrain init stamps a database it creates; otherwise the first look records 0 when upgrade-state.json shows an upgrade from an older release or the oldest sources.created_at is past FRESH_BRAIN_GRACE_MS). Markers: CLI and stdio claim a wx file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to HTTP_SHOWN_CAP client ids, each with the release it was shown, in the notices.behavior_changes.http config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: completeEngineStartup in src/cli.ts (stderr; not serve or doctor), and sessionSafetyNotices in src/mcp/dispatch.ts on success and failure results. gbrain doctor --only behavior_changes reads every row newer than the baseline without writing. Pinned by `test/behavior-c... (line truncated to 2000 chars)

  • src/core/upgrade-summary.ts — the short "what changed since vX" header gbrain post-upgrade prints: behavior-table rows after a release, grouped by their behavior-changes.d kind: (Needs you: breaking and action; Behavior changes: default; fix and add counted; rows without a kind counted as not classified yet), the first sentence of each, pointing at gbrain doctor --only behavior_changes.

  • src/core/post-upgrade-notice.ts — F7 post_upgrade safety notice (contract_version + behavior-table URL): gbrain post-upgrade writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). src/cli/op-notices.ts (also retrievalIncompleteLine, search/query's Retrieval incomplete: line: projection_pending only when coverage says some pending page could match, with the count, once per window across calls) renders op notices on the local CLI (--json objects gain notices; human output on stderr).

  • 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.

  • scripts/build-agent-protocol.ts — generated regions of the agent operator protocol (bun run build:agent-protocol, --check in verify and regen:all): the protocol page's transcripts from the frozen wire goldens, the AGENTS.md quick contract, and skills/conventions/agent-operator-protocol.md, the whole protocol page bundled with the skills (a shared dep every copy path carries) with its relative links made absolute. Drift test: test/agent-protocol-doc.test.ts.

  • src/core/persistence/write-grant.ts — the one refusal for a remote write naming a source outside the caller's write grant (remember and every page mutation): writable_source_ids lists only the caller's own grant source ([] for a sentinel), identical whether the named source exists; remember's fix repeats the call against that source (GBRA-200).