Garry's Opinionated OpenClaw/Hermes Agent Brain
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--brainand the command's source flag (--source;--source-idfor a record declaringroutes_source: '--source-id', extract, whose--sourceis a mode selector and never blocks the pin) before a bare--for commands that route them (shared ops registered byoperations.ts; CLI-only commands from the generatedCLI_ROUTING_FLAGS, built from the command table'sphase/routes_sourceand each command's code). Holds the CLI process's routing provider (installCliRouting, installed bysrc/cli/fix-routing-provider.ts; never forserve) 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 intest/agent-journey-recovery.serial.test.ts.src/core/agent-output.ts— the contract v1 types and renderers every surface shares:Action(stored; never carriesnextorcommand; the escalation flagask_user: truemarks a refusal whose every way out is the user's decision) andRenderedAction,Notice/RenderedNotice,AgentEnvelope,RenderContext.deriveNextis the published decision table (a storedask_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, anddestructivealways →ask_user; elserun).renderActiondropsmcpunlessctx.isCallable(an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actoruserandtell_user_to_run), pinsctx.routing(--brain/--source) into every gbrain argv viasrc/core/fix-routing.ts, renderscommandonly from argv viashellQuote, rewrites a CLI-only agent fix to actoruser(stdio) /host_admin(http).inertTextflattens newlines and breaks marker tokens in every interpolated value.docsUrlpinsv<VERSION>for a published package,masterfor a source checkout,LLMS_REPO_BASEfor forks whensrc/core/repo-base.tsparseRepoBaseaccepts it (W4.12: a plainhttps://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 throughrepoBaseOrThrow).redactForTransportis the one HTTP redaction pass (paths, PIDs, key names, posture keys).toAgentErroris total and table-driven (OperationError incl. F0 refresh refusals →fix.argv, StructuredAgentError, BudgetExhausted/no_pricing withinputs, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, theGBRAIN_DB_ACCESSclassifier, unknown throws →internal_errornaming 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 insrc/(class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/legacy_error/renamed_from/exit/retryable, andreason_overrides: a reason whose class and exit replace the code's on the envelope and the CLI exit);RegistryCodeis its key union.NOTICE_CODES: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, thenbun run build:error-codes. Completeness is AST-checked bytest/error-catalogue.test.tsandscripts/check-agent-contract.ts.src/core/error-docs.ts— renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable, plus anOverride:line per reason override) fordocs/guides/error-codes.md(scripts/build-error-codes.ts,check:error-codesin verify) andgbrain 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:recordAgentContractEventappends{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.readAgentContractEventsfeeds doctor'sagent_contractcheck (src/commands/doctor/checks/agent-contract.ts). #6758: every event carriesversion(defaults to the writing build'sVERSION); on a warn the check addsdetails.builds(this_build,other_builds,unknown_buildfor older unversioned lines,versions) anddetails.incident(historicalwhen no counted event came from this build,sincethe 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 usesprocessNoticeLedger(); HTTP passesServeHttpContext.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/safetynotices are never deduped, except that a notice's unrenderedNotice.dedupe_keyreplaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (degradedRecallNoticesets it only when every stage/reason pair is configuration-persistent: a keyless brain'sembed_unavailable; HTTP ignores it for degraded notices;renderNoticenever copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and toMUTEABLE_ASK_CODES(onlyfirst_run_decisions). Mute store<GBRAIN_HOME>/notices/muted.json: owner list (global) + per-client lists;mute_noticeop (src/core/ops/notices.ts, write scope; HTTP per client, stdio under thestdioaudience that dispatch reads on stdio) andgbrain notices mute|unmute|list(src/cli/commands/notices.ts, owner;unmuteNoticeForOwnerclears the global and thestdiolists,listshows 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) andmemoize(key, compute)back the once-per-sessiongrant_blocked_operationsnotice; codes inSELF_DEDUPED_NOTICE_CODESwere deduped by their producer on its own key, soadmitapplies 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 stdiostdioVisibleTools, serve-httplistMcpTools, the legacy bearer transport's tools/list, anddispatchRenderContext(which tools a fix may name).publishGatesFromDisabledconverts 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/exitCliErrorrender throughrenderCliError(humanError [code]/Fix:/Why:/Docs:on stderr; under--jsonone envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; alegacyshape (unknown flag's{status, reason:'invalid_flag', message},pglite_busy'snext_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(theimport.meta.mainseam; keeps theGBRAIN_DB_ACCESSmarker + remediation on human output; apglite_busywith reasonlegacy_owner_unverifiedrenders 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 exportshelp: CliHelpSpec(summary,usage,flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}], 2–4examples,end_of_options?) and is loaded lazily through its command-table record'shelp: () => import('./help/<name>.ts')(literal, sobun build --compilebundles it andgbrain --versionloads none; pinned bytest/cli-command-table.test.tsandscripts/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--yesis listed wherever the handler parses it.printCuratedHelpanswersgbrain <cmd> --help/-hfirst in main()'s help short-circuit, engine-free (human table with type/values/consent;--help --jsonone document{command, …spec, contract_version}).curatedFlagError(command, args)(called in main() after the unknown-flag check) refuses a missing/non-numericnumbervalue or an out-of-setenumvalue withinvalid_params(exit 2) viaflagValueError, example value drawn from the spec's examples;--flag=valueand--flag value, stops at a bare--;stringflags (e.g. onboard's--max-usd off) are not checked.unknownFlagErrordraws 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 --jsoncontract 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 retriageanddream reset-keyuse it (test/dream-help-json-8510.test.ts). Other self-help commands that declarejsonstill 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]) andflagValueErrorraiseinvalid_paramsusage 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/*-flagstest.src/cli/flag-validation.ts— the pre-dispatch unknown-flag validator (validateCommandFlags,findUnknownOpFlag) and the CLI alias table (buildCliAliases,cliAliases), moved verbatim out ofsrc/cli/main.ts, which re-exports them.src/cli/skill-surface.tsimports them from here, so the skill drift surface never imports the dispatcher; main registers that surface withsetSkillSurfaceProvider(src/core/skill-health.ts) so doctor, which the operations graph also loads, checks skill drift without importing the command table. Pinned bytest/cli-flag-validation.test.ts.src/cli/flag-equals.ts—--flag=valueon CLI_ONLY commands (#7619).cliOnlyFlagArgsinsrc/cli/main.tsrunssplitFlagEqualsonce 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-parsedsearch modes|stats|tune|diagnosesubcommands, the validation-exempt paths (jobs submit, whose consent check reads the=spending cap, andconfigexceptset) and the directbun run src/commands/auth.tsentry (which strips and applies the global flags, handsauth local-writerto its own parser and runs the unknown-flag validator,findUnknownFlagwith the sameunknown_flagenvelope and legacy keys, all as main does). Per registered--flag=valuetoken: a switch refuses (invalid_params, exit 2: a boolean in the command's own table, curated help orSYNC_FLAGSfor sync, a--no-negation, the command'sCOMMAND_SWITCHES(also the switches no shared evidence covers, such asagent --detach), or a nameknownSwitches()finds boolean in the handler-freeOPERATION_MANIFESTor any curated help, so--yes=nis never answered with--yes <value>);EQUALS_READERS, keyed by command orcommand sub(thesync --statusalias reads assync status,forget --purgeis its own path, andreposreads thesourceskeys throughREADER_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 valueonly 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 34purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (extract links --source-id=xwalked every source), so keys name the narrowest path. A short flag never takes=(-y=nrefuses).NO_VALUE_FLAG_PATHS(theedge-proposalssubcommands butlist, 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 runis scanned only whereparseRunFlagsreads flags: the leading zone throughRUN_VALUE_FLAGS(each value passes untouched) andBOOLEAN_TAIL_FLAGSfromsrc/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, andparseRunFlagsitself throws on a value flag written as two arguments there (#7672). A bare--ends the scan only onEND_OF_OPTIONSpaths (agent run,frontmatter validate), whose handler stops there;serve,auth,frontmatter generate,questionsandagent logsread 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-parsedsearchsubcommands, which have no registry row, every=token but--json=truerefuses with a neutral message that names the subcommand, echoes no value and vouches for no switch.--json=truebecomes--json. Refusals name--flag=…, never the value.OWN_EQUALS_PARSERS(own=-aware parsers on every path that refuse=on their switches,retrieval-upgradeandmigrate embeddingsincluded; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens),call,config set,eval brainbenchand every subcommandsrc/cli/strict-args.tsgoverns (strictSpecFor) keep their argv.scripts/generate-flag-registry.tsskips this module. Pinned bytest/cli-flag-equals.test.ts(a table over every registered CLI_ONLY flag, both-direction pins ofEQUALS_READERSagainst every=reader insrcand ofOWN_EQUALS_PARSERSagainst every=option parser, stray-positional, dropped-scope, consent and--rows, own-parser switch refusals) andtest/serve-flag-equals.test.ts(real CLI processes on PGLite,--jsonenvelope, the directauth.tsentry,serve -- --access=andfrontmatter generatebehind--helpor--included).src/cli/search-row-format.ts—formatSearchRow: the humangbrain search|queryline per row ([score] slug -- preview); a saved-fact row printsfact:<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 incli-options.ts):timeCliPhasebooksconnect,contextandremoteinrunSharedOperation/runThinClientRouted;searchTimingsDocumentmakes--jsonprint{results, timings_ms, cost}(bare array without the flag) andsearchTimingsLinethe 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 fromParamDefinsideparseOpArgs(number → finite, string enum → declared values),invalid_paramswith an example otherwise; mirrors MCPvalidateParams.opStructuredValueturns 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.parseOpArgsalso 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 whenrunInitreturns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the--prefer-postgresladder still prints only its envelope).buildInitFirstRunNoticesis the G5 seam: onefirst_run_decisionsask notice withdecisions[](search_mode,writeback,harness_wiring,skills_scaffold, then the settings in effectupkeepandconversation_archive, GST-2768: on or offered,archiveLine); the stdio onboarding cache reuses it with writeback and skills only, andsetupFirstRunNoticesisgbrain setup's form (frominit --json:harness_wiringdropped,why/user_messageframed as settings in effect that the agent relays in the install reply instead of a reply-to-continue question; Cat 41 wave 2, pinned bytest/init-first-run.test.ts).firstRunBundle/harnessRegistrationCommandtakegbrain init --surface. Tests:test/cli-json-guard.test.ts.src/core/onboard/hosted-option.ts— thehosted_optioncoaching notice (gbrain.io, hosted GBrain): the one home of its URL, copy and?ref=tags.gbrain setupappends it when it created the brain,printInAgentReadyprints it after the in-agent ready text when init created the brain (its mute hint names that install's own launcher), andgbrain mcp expose'sSession.finishadds it (JSONnotices, 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,--statusor--remove. Baregbrain initnever shows it. Refs split publish (cli-mcp-expose) from friction exits (cli-mcp-expose-friction). Muted by the owner list or thestdioaudience (hostedOptionMuted, i.e.mutedNoticeCodes('stdio'));writeHostedOptionprints 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 forrunInitNudge, sequential with yields for the background refresh; the stale-chunk count usescountStaleChunks' predicate, so soft-deleted andembed_skippages are not backlog); a failed count isnulland never reads as a gap, andonboardGapsapplies 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 bystartOnboardingRefresherand refreshed in the background only while the idle gate reports no request in flight (3 s budget); it also holds the pitchablegbrain featuresrecommendations (pitchableFeatures, offer state read-only) and the stale-chunk backfill estimate.mcpOnboardingNoticesis dispatch's one producer on the stdio success path:first_run_decisions(writeback + skills viamcpFirstRunNotices, 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) whenONBOARD_CALL_AFFINITYnames the call and the class's result predicate holds, plusfeatures_auto_fixonget_backlinks/traverse_graph; fixes are the read-onlyget_health/gbrain onboard --checkpreview, the dismissal line namesmute_noticeonly where it is callable.mutedFirstRunDecisionsNoticefeeds doctor (memory_writeback) andgbrain 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:--helpcontract for every command-table record (exit 0, non-stub, curated flags only,--yesshown where parsed) against the shrink-onlytest/fixtures/cli-contract/help-baseline.json, and one success + one failure row perjson-declared record.src/cli/json-guard.ts— picks the--jsonguard mode for an invocation: on only whenjsonRequested(argv)and the command-table record declaresjson: 'document' | 'ndjson'; wires the E11json_document_missinghook (document mode, exit 0; the event recordscommand,version,guard: 'document'andexit_code: 0, never argv values;outcomekeeps its value, #6629/D26). The guard itself isinstallStdoutPipeDelivery({ json })insrc/core/cli-force-exit.ts: stdout writes and console.log/info/debug go to stderr, onlywriteStdoutFinal/writeNdjsonLinereach fd 1, a non-zero exit with no document writes the fallback document,spawnCliChildpipes child stdout to stderr. Test:test/cli-json-guard.test.ts. A record whose subcommands differ in shape declaresjsonSubcommands(keyed by the first positional after the command;eval).writeCliErroraddsstatus:'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) inbun run verifyandguards-manifest.tsv(fixturestest/fixtures/guards/check-agent-contract.ts/). Rules: suggestion-lessOperationError,throw new Errorin ops/mcp/handlers, hand-builtfix/next_actioncommand strings, legacy advice keys, raw interactive stdin/readline/raw-mode outsideinteraction.ts/consent.ts, raw "re-run with --yes" strings outsideconsent.ts,stdio: 'inherit'outsidespawnCliChild, marker literals outsideagent-output.ts/agent-markers.ts,verify.argvnaming 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 throughopError,new OperationError,usageError,invalidParamorhostOnlyErrorfrom a*suggestion/*hintparameter with a default, an optional marker or a??fallback) andgeneric-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 inscripts/agent-contract-baselines/<rule>.tsv;--updatelowers 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) → onedegraded_recallnotice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; arerank_failedstage names its reason, thefused_orderfallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason:timeout/rate_limitedrepeat the same call after 5/20 s (actor: provider,next: wait),authis the user's key (credentials), the rest run doctor verified byreranker_health(test/rerank-degraded-notice.serial.test.ts); none on a brain keyless by choice, whose why says no query text was sent and thatgbrain doctor --jsonnames the enable command).embeddingOptedOutForreads the opt-out markers (search/query degraded reasonembedding_disabled, recallkeyword_only_embedding_disabledinsearch_degradedorfacts_degraded.reason, thinkQUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED);factEmbeddingDisabled(src/core/embedding-disabled.ts) gates every query and fact embed. With the call's_meta.retrieval.coverage,degradedRecallNoticeleavesprojection_pendingout 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, thesealable/reimportclasses) never index on their own, so the why namesgbrain projections drain, the paid re-import and doctor'stext_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 explicitsource_idread).recallStagesFormaps recall'ssearch_degradedandfacts_degraded.reason(question ranking) to stages.recallInteropNoticesis 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, thesources_not_readablerefusal (class host_only) dispatch runs after a handler's empty result (emptyRead, so a read that returns rows costs no extra query): an unscopedsearch/query/recall/list_pages(nosource_id, no non-emptysource_ids) from a remote connection with no source grant (noallowedSources,hasSourceGrantnot true, no stdio binding; OAuth clients always carry a grant) whosefederatedSearchScopeholds 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; forrecallandquery, no world fact either) while another live, unarchived source does (GBRA-585). OneCASE WHEN EXISTSread, fail-open on any error. The message and suggestion never name a hidden source; the fix is the host'sgbrain sources federate <source>(hostFix, inputsource: 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.degradedrecall-affecting stages (keyword-only markers normalized toembed_unavailable;projection_pendingdropped when no pending page could match), the result body's degraded fields (recallsearch_degraded/facts_degraded,degraded_reason, get_pagefile_held, think/synthesizeGATHER_*warnings, search_exact, open_loops, rank_entities) and the call'skind: degradedresult notices, read before the notice ledger dedupes them; null when clean. Dispatch writes_meta.degradedand appendsdegradedStampLineas the last content block;src/cli/op-notices.tswithDegradedStampputs it on a--jsonobject asdegraded, 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-brainserve(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;runStatusModeServeis the one entry point for both transports and logsserve_status_mode_enter/serve_status_mode_recovered(reason,transport,elapsed_ms) as one-line JSON on stderr.probeStatusreads config +peekLockonly;reprobe(state, connect)is the one re-probe (no lock attempt while blocked,resetReadinessMemo()before the throw-only connect fromsrc/core/engine-connect.ts); a check that must run on every re-probe hooks theprobeAgainwrapper inrunStatusModeServe. stdio: a gated lazy engine (createDegradedEnginewith the configuredkind, reconnectstatusReconnect, ≤1 attempt / 5 s inside tool calls) marked withStatusModeState;statusPayload→{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}.--http:runHttpStatusServebinds onenode:httplistener with a mutable handler (/health503 +Retry-After: 5+instance;/mcpstateless SDK server with onlygbrain_status; every other route a 503serve_status_onlyenvelope), each response built from the allowlist inhttpStatusPayload/httpStatusEnvelopewithreasoncollapsed tounavailable; a single-flight chained 5 s tick runs the re-probe, and on a connectrunServe(..., { 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 markerGBRAIN_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) andstdioCapabilityReadiness(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 getsunknown_toolnaming itself and its CLI equivalent (cliEquivalent:cliOnlyargv, curated overrides,cliHints.name, elsegbrain call). Whererequest_toolsis callable and session widening is on, the fix isrequest_tools {surface:'full'}(next: run, argv kept); otherwise the CLI equivalent with actoruserand auser_message;whynames the lasting route (GBRAIN_SURFACE=fullin the harness's per-server env, or a--surface fullre-registration) and that an inheritedGBRAIN_SURFACEoverrides a pinned--surface. Read-only access never offers a widen. HTTP stays opaque.scripts/generate-plugin-tree.tsappends 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 withtoolConnection(opts).hiddenToolNextturns 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 getstrusted_local_only(errorpermission_denied) with the exact CLI command.src/core/behavior-change-notice.ts— the one-timebehavior_changessafety notice: a livechat_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_CHANGESis the one table of disclosed changes, each with the release that introduced it; rows a PR adds live inbehavior-changes.d/<id>.mdand reach the table throughsrc/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 usesince: releasedIn(id)(FENCE_REPAIR_MEASUREDis the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates);BEHAVIOR_NOTICE_SINCEis the newest row's release (neverVERSION), so the notice idbehavior_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 underGBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline(gbrain initstamps a database it creates; otherwise the first look records0whenupgrade-state.jsonshows an upgrade from an older release or the oldestsources.created_atis pastFRESH_BRAIN_GRACE_MS). Markers: CLI and stdio claim awxfile per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up toHTTP_SHOWN_CAPclient ids, each with the release it was shown, in thenotices.behavior_changes.httpconfig row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery:completeEngineStartupinsrc/cli.ts(stderr; notserveordoctor), andsessionSafetyNoticesinsrc/mcp/dispatch.tson success and failure results.gbrain doctor --only behavior_changesreads 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" headergbrain post-upgradeprints: behavior-table rows after a release, grouped by their behavior-changes.dkind:(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 atgbrain doctor --only behavior_changes.src/core/post-upgrade-notice.ts— F7post_upgradesafety notice (contract_version + behavior-table URL):gbrain post-upgradewrites it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME).src/cli/op-notices.ts(alsoretrievalIncompleteLine, search/query'sRetrieval incomplete:line:projection_pendingonly whencoveragesays some pending page could match, with the count, once per window across calls) renders op notices on the local CLI (--jsonobjects gainnotices; 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 fromremote+transport),paramUse(ctx, param, value?)(--no-pullvsno_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 relayuser_message),invalidParam(B2/B3: param, choices or type+description, one example; never echoes the raw value),scopeDeniedError(B5:insufficient_scope, frozenerrorvialegacy_error, client id + current scopes inwhy, the exactgbrain auth rescope/rescope-tokencommand, consentcredentials). 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 canonicalpage_not_foundwith the frozen wire/journalerrorpage_identity_changed; a replaced page keepspage_identity_changed),isMissingPageMessage(replays recover the distinction from the stored message; no schema change),yamlLocator(content-freeat line L, column C). Replays (writeResponseinpersistence/service.ts) setOperationError.receiptFields(never serialized);toAgentErrorfills 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_requestwhen 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,--checkin verify andregen:all): the protocol page's transcripts from the frozen wire goldens, the AGENTS.md quick contract, andskills/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_idslists only the caller's own grant source ([]for a sentinel), identical whether the named source exists; remember'sfixrepeats the call against that source (GBRA-200).