Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Skills
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
skills/conventions/agent-operator-protocol.md— GENERATED copy ofdocs/protocol/AGENT_OPERATOR_v1.md(bun run build:agent-protocol; never hand-edit). It ships inside the skills tree so skill links to the protocol resolve in every copy (skillpack scaffold, harness skill dirs, plugin trees); skills link it relatively and every other repo doc by absolute URL (scripts/portable-skill-links.ts).skills/enrich/SKILL.md— enrichment protocol and the Person/Company page templates; the templates'##sections matchdocs/GBRAIN_RECOMMENDED_SCHEMA.mdin order (test/enrich-template-schema-parity.test.ts). Step 6 resolves type, directory and subtype from the active schema pack through brain-taxonomist before filing, writes only known frontmatter values (nonullplaceholders), and creates link targets first in a batch (#6030).skills/skillpack-check/SKILL.md— report-only health protocol.actions[]is untrusted proposal data, not execution authority; schema, service, page and paid embedding changes require separate explicit action/scope approval.test/skillpack-check-report-only.test.tsexecutes the documented reporting snippet against a hostile synthetic action and proves it creates no file.src/cli/commands/bundled-skill.ts+src/core/skills/{bundled,spring-index,index-block}.ts+src/core/skills/bundled-skills.generated.ts+src/core/setup/skills-block.ts+src/core/bootstrap/harness-skills-index.ts+scripts/{generate-bundled-skills.ts,check-skills-embedded.sh}— the opt-in spring-loaded skill index (--skill-loading spring; user docs:docs/guides/setup.md"Skill loading (opt-in)").gbrain bundled-skill [<name>] [--asset <path>] [--json]is pre-connect and engine-free (thinClient: 'none',skipStartupHooks): it prints a bundled skill or a file it names from the embedded map, where a name or asset is a lookup key and never a path; the set is the plugin lane (skills/plugin-lanes.json),owneraudience on the host anddownstreamonly on a thin client (host-only skills answerskill_not_found). The embedded module is generated (bun run scripts/generate-bundled-skills.ts,--checkfails when stale) and holds only membership, audience and asset lists; description and triggers are read from the embedded SKILL.md at runtime.spring-index.tsrenders one line per skill from frontmattertriggers:underSKILL_INDEX_BUDGET_BYTES(6144), trimming triggers before ever dropping a skill and refusing (SkillIndexTooLarge) rather than truncating.skills-block.tswrites the<!-- gbrain:skills:begin/end -->block beside the brain-first block in the same file, records the choice in<configDir>/skill-loading.json, refuses to write when the recorded launcher (<launcher> bundled-skill --json) serves another catalog, adds oneBash(<launcher> bundled-skill:*)allow rule on Claude Code only when absent and removes it only when it added it, and backssetup --skills-index-only; every sync and removal runs under the instruction-ledger lock ofbrain-first.ts(outcome reasonledger_lockedwhen it cannot be taken), and a Codex opt-out (flag, env or declined instructions) also strips the index recorded in the siblingAGENTS.md/AGENTS.override.mdof the sameCODEX_HOME(pairedoutcome, shown byskillsOutcomeShown);setup,connect --install,harness connect --installandbootstrap harness(harness-skills-index.ts) share it, and a requested index that cannot be written exits non-zero. doctorharness_wiring(withSkillsIndex) reports a stale, absent or damaged index as information and warns only when the launcher is gone or the record is unreadable;check-resolvableandskill_currencyread past the block throughskillsIndexedIn.check-skills-embedded.shcompiles a binary and proves it serves every bundled file byte-identical toskills/(test/bundled-skill-cli.test.ts,test/spring-skill-index.test.ts,test/setup-skill-loading.test.ts,test/skill-loading-lanes.test.ts).src/core/audit-skill-brain-first.ts— snapshot+diff JSONL audit at~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl(ISO-week rotated, honorsGBRAIN_AUDIT_DIRvia sharedresolveAuditDir()).recordBrainFirstRun(results)reads the previous snapshot at~/.gbrain/audit/skill-brain-first-snapshot.json, diffs against current results, writes transition events (detected | resolved | fixed) one line per change, then atomically overwrites the snapshot via.tmp + rename. Transition-only writes — a stable brain produces 0 audit lines per doctor run.readRecentBrainFirstEvents(days)is the readback path for the futureskill_brain_first_trenddoctor check. Snapshot file is last-writer-wins under concurrent doctor runs; subsequent runs reconcile.src/core/skill-brain-first.ts— pure analyzer.analyzeSkillBrainFirst(skillPath, content): SkillBrainFirstResultwalks the compliance ladder for every SKILL.md: (1) absent external-lookup pattern →no_external; (2)brain_first: exemptfrontmatter →exempt_frontmatter; (3) canonical> **Convention:** see [conventions/brain-first.md](../...)callout →compliant_callout; (4) explicit## Phase 1: Brainheading →compliant_phase; (5) firstgbrain search/query/get_pagereference precedes first external pattern in the BODY (frontmatter stripped) →compliant_position; (6) elsemissing_brain_firstwarn. External pattern set: word-boundary regex overweb_search,web_fetch,exa,perplexity,happenstance,crustdata,captain_api,firecrawl. Position scan is BODY-ONLY so atools: [web_search]frontmatter declaration doesn't false-flag the skill. The 40-nameFORMERLY_HARDCODED_EXEMPTlist is preserved so doctor can emit a "this used to be auto-exempt, declarebrain_first: exemptif still appropriate" hint. Consumed by 3 surfaces: doctor check, skillify-check item 12, dry-fix MISSING_RULE_PATTERNS.src/core/skill-drift.ts,src/cli/skill-surface.ts,scripts/check-skill-health.ts— skill drift and size guard (bun run check:skill-health, in verify andscripts/skills-commit-gate.sh).extractInvocationsreads everygbrain ...invocation in shell fences and inline code (placeholders kept as one token,<!-- skill-drift-ok: reason -->skips a line or the line after it);analyzeSkillDriftruns each through the injectedCliSurface, which is the dispatcher's own code (CLI_ONLY,cliOps/cliAliases,ROUTERSsubcommand inventories,parseGlobalFlags,validateCommandFlags; a router subcommand of an op command checks againstCLI_FLAG_REGISTRY), so a skill passes exactly when the CLI would accept the invocation. Subcommands are verified only for commands with a declared inventory. A CLI_ONLY command called with a second word but no declared inventory is counted as unverified, never reported as drift, and must be listed in the shrink-onlyscripts/skill-drift-undeclared-subcommands.txt(SKILL_DRIFT_UNDECLARED_SUBCOMMANDSfor a new one,SKILL_DRIFT_UNDECLARED_STALEfor a line no skill needs); an operation's positional arguments are never subcommands. Operation-shaped frontmattertools:entries (snake_case ormcp:) must be real operations (web_fetch/web_searchare host tools). Size: a SKILL.md over 16384 bytes needs askills/skill-budgets.tsvrow and stays under its ceiling; descriptions stay within 1024 bytes; a row for a skill back under the cap with no diet recorded is stale.scripts/skill-drift-baseline.txtis shrink-only.--sizes <files>prints theSkill-size:lines the commit gate shows. Pinned bytest/skill-drift.test.tsand thetest/fixtures/guards/check-skill-health.ts/bad- fixtures.src/core/skill-health.ts,src/commands/skillpack/health.ts,src/commands/doctor/checks/skill-health.ts— runtime skill health (gbrain skillpack health, doctorskill_health, agbrain maintainline,skillpack-check'sskill_healthfield).computeSkillHealthchecks one skills folder: bytes against the bundle'sskills/skill-budgets.tsvrow (else the 16384-byte cap), growth past 110% oflast_diet, description bytes, frontmattertriggers:, andanalyzeSkillDriftover every markdown file in the skill with the livecliSurface(). Each finding hascode,observed,expected,fixandverify. Scope: a folder withmanifest.jsonorskills.lock.json(isManagedSkillsDir) checks every skill; otherwise only copies of bundled slugs (bundled_copies), else nothing (not_gbrain, doctor reports info / not_applicable). Files only: no git, database or model calls. The doctor check warns only on drift.parseSkillBudgetsand the caps are shared withscripts/check-skill-health.ts. Pinned bytest/skill-health.test.ts(including 100 skills under 500 ms).src/core/skill-catalog.ts— legacy host-repo fallback for MCPlist_skills/get_skill. Canonical schema-version-2 discovery uses shared brain skills; version 1 also uses the canonical compatibility layer when that catalog is active. This module serves the remaining host-catalog fallback, not canonical revision discovery.buildSkillCatalog(ctx, dir, source, { section, query, limit, gateDisabled })builds the catalog after the publish gate and confinement; withquery(#6471) it ranks the section-filtered entries byscoreSkillMatch(lexical token overlap: trigger tokens ×2, a whole trigger phrase inside the query ×4, name tokens ×3, description tokens ×1; no model call), drops zero-score entries, breaks ties by name, caps atlimit(default 10, max 100) and setsmatch: { score, matched_on }per entry; withoutquerythe output is byte-identical to the unranked build. Thelist_skillsop refusesquerywithinvalid_paramson the schema-version-2 and active shared-catalog routes before any catalog read (ops/skills-catalog.ts);queryis advertised on the full MCP surface only (fullSurfaceOnly) so the starter list keeps its size budget. Pinned bytest/list-skills-query-6471.test.ts. Lets a thin MCP client (Codex desktop, Claude Code, Claude Cowork, Perplexity) DISCOVER + FOLLOW the agent repo's fat-markdown skills overgbrain serve— a skill is prose, so "using" one = fetching its body then calling the gbrain MCP tools the server already exposes. Read-scope, NOT localOnly (defensible only via the full mitigation stack): (1) publish gate —assertPublishEnabled(ctx, publishSkills); remote callers requiremcp.publish_skills === true, default-OFF so an upgrade never silently grants existing read tokens host-skill read; local callers (ctx.remote === false) always pass. (2) path confinement —assertSkillNameShaperejects separators/../null/space before any FS access; the clientnameis a manifest LOOKUP KEY (vialoadOrDeriveManifest), never a raw path segment;confineManifestPathdoes realpath + relative-containment +SKILL.md-regular-file check on EVERY entry (defeats poisoned manifest.jsonpath, symlink/..escape). (3) frontmatter allowlist —GetSkillResult.frontmatterprojects a safe subset; privatewrites_to+sourcesdropped. (4) prose-only + 256KB cap (MAX_SKILL_MD_BYTES, envGBRAIN_MAX_SKILL_MD_BYTES), size-checked twice (statSync + UTF-8 byte length). (5) no install_path serve for remote — remote callers useautoDetectSkillsDir(no install-path tier) so a hosted gbrain with no agent repo returnsstorage_error; local callers useautoDetectSkillsDirReadOnly. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes:readMcpPublishSkills/readMcpSkillsDirprefer the DB plane (engine.getConfig) over the file plane (ctx.config.mcp). Tool-honesty:resolveSkillToolsshares list/detail semantics: declaredtools:narrow the caller's effective inventory viacrossReferenceTools; valid mapping frontmatter that omitstoolsinheritsavailableBrainTools(ctx)without granting new permissions. Explicittools: []stays empty; invalid tools values, malformed YAML, and missing frontmatter never receive the inherited inventory. The operation handlers resolve current DB/file publication gates throughdisabledOpsForPublishGatesbefore building either response; unpublished operations are excluded from declared and inherited tools and both instruction envelopes.opAllowedForBoundClientalso applies the same operation grants, slug-bound write fences, and degraded-projection policy as dispatch. Pure catalog calls without resolved gates conservatively hide gated operations from remote callers. The list'stoolsremains the declared list (empty when omitted), whileusable_toolscarries the effective inventory. Pinned bytest/skill-catalog-optional-tools.test.ts.buildSkillCatalog'sinstructionsenvelope (SKILL_CATALOG_INSTRUCTIONS) carries the "these are prose, follow-then-call-tools" protocol. These fallback skills are host-filesystem repo-global —sourceScopeOpts(ctx)/ctx.brainIddeliberately do NOT apply.buildSkillCatalogis resilient (one malformed/escaping skill is skipped, never throws). Config keys insrc/core/config.ts:GBrainConfig.mcp?: { publish_skills?, skills_dir? }+KNOWN_CONFIG_KEYSentriesmcp.publish_skills/mcp.publish_skills_prompted/mcp.skills_dir+mcp.prefix inKNOWN_CONFIG_KEY_PREFIXES.src/commands/init.tswritesconfig.mcp = { publish_skills: true, ... }for new installs (existing config wins on re-init).src/commands/upgrade.ts:runPostUpgradeadds a one-time consent prompt (gated bymcp.publish_skills_prompted; existing installs stay OFF until owner opts in). The legacy catalog entrypoints insrc/core/ops/skills-catalog.ts(spread into theoperations.tsfaçade) are:list_skillswith optionalsectionfilter +cliHints:{name:'skills'};get_skilltakingname(+source_idfor brain-resident packs) +cliHints:{name:'skill', positional:['name']};list_brain_skillpack. They dynamically import this module to avoid the import cycle (skill-catalog statically imports theoperationsarray). Descriptions insrc/core/operations-descriptions.ts(LIST_SKILLS_DESCRIPTION,GET_SKILL_DESCRIPTION,SKILL_CATALOG_INSTRUCTIONS,SKILL_CLIENT_GUIDANCE), pinned bytest/operations-descriptions.test.ts. CLI:gbrain skills/gbrain skill <name>. Pinned bytest/skill-catalog.test.ts,test/skill-catalog-security.test.ts(path-confinement / poisoned-manifest / symlink-escape),test/skill-catalog-transports.test.ts(publish-gate + remote-vs-local) overtest/fixtures/skill-catalog/.src/core/skill-fix-gates.ts— shared safety primitives fordry-fix.ts.getWorkingTreeStatus(file)3-state ('clean' | 'dirty' | 'not_a_repo');isInsideCodeFence(content, offset);findAfterH1Paragraph(content)(canonical insertion offset for the auto-inserted Convention callout). Both REPLACE expanders (DRY violations) and the INSERT expander (MISSING_RULE_PATTERNS) consume from here so the install-path refusal and dirty-tree gates apply uniformly.src/core/dry-fix.tsre-exports them.src/core/skill-frontmatter.ts— shared content-based SKILL.md frontmatter parser. Array fields (writes_to,tools,triggers) usejs-yamlwith the failsafe schema, accepting block lists and single-line or wrapped flow sequences while preserving the tolerant legacy regex fallback for partially malformed YAML; CRLF is normalized before fence parsing. Recognizes thebrain_first: 'exempt'declarative opt-out and surfaces near-miss declarations (brain-first,BrainFirst, quoted values, unknown values) as a typedbrain_first_typofield so doctor can emit a paste-ready hint rather than fail silently. Single canonical form: snake_casebrain_first: exempt, lowercase, unquoted.src/core/skill-manifest.ts— parser forskill-manifest.jsonrecords. Used by skillpack installer to detect drift between the shipped bundle and the user's local edits, so updates merge instead of overwriting.isGbrainManagedSkillsDir(dir)(W4) is the one marker for "gbrain installed this skills folder":skills.lock.json, a valid on-diskmanifest.json, or theSKILLPACK_MANAGED_BEGINblock in a resolver file there or at the workspace root; doctor's resolver_health and skill_currency report a walk-up folder without it as info (test/skill-manifest-managed-dir.test.ts).src/core/skill-trigger-index.ts— Shared loader that unions per-skill SKILL.md frontmattertriggers:with curated RESOLVER.md / AGENTS.md rows fromskillsDirAND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on(skillPath, trigger.trim().toLowerCase()). Three consumers fold through this primitive —checkResolvable,runRoutingEvalCli,mounts-cache.composeResolvers— so fixing frontmatter reaches all of them. ExportsloadSkillTriggerIndex(skillsDir): SkillTriggerEntry[],entriesToResolverContent(entries): string(synthesizes a markdown-table resolver string forrunRoutingEval's string-content API),findPrimaryResolverPath(skillsDir): string | null, theFRONTMATTER_SECTIONconstant, and_resetWarnedSkillsForTests. Skip rules: non-directory entries (a symlink dirent is followed viastatSync—readdirSyncdirents report the link's OWN type without following, so skill dirs symlinked in from a shared store, e.g.~/.agents/skills/<name>, still load),_*/.*prefixes,conventions/+migrations/subdirs, skills with noSKILL.md(deprecatedinstall/graceful-skipped), notriggers:array, or malformed YAML (warn-once + skip). ReusesparseSkillFrontmatterfromsrc/core/skill-frontmatter.ts, including block and wrapped flow-sequence arrays. Pinned bytest/skill-trigger-index.test.ts(18 hermetic cases). CI gatebun run check:resolver(=bun src/cli.ts check-resolvable --strict --skills-dir skills/) wired intobun run verify.src/core/skillopt/+src/commands/skillopt.ts+skills/skill-optimizer/— self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904).gbrain skillopt <skill>treatsSKILL.mdas trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (tryAcquireDbLock('skillopt:<name>', 60min)), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts usegateway.toolLoopdirectly with no-op persistence callbacks (zerosubagent_messagespollution) + a read-only tool allowlist derived fromBRAIN_TOOL_ALLOWLISTminusput_page/submit_job/file_upload. Default is one gated one-shot rewrite (optimizerMode);--loopruns two reflect calls per step (deprecated, removed on or after 2026-12-03:loop-deprecation.tsemits theskillopt_loop_deprecatedcoaching notice once per CLI run,run_skilloptcall and job that runs the loop;test/skillopt/loop-deprecation.serial.test.ts); rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel +--bootstrap-reviewed); D_sel floor (>=5 with--splitoverride); audit JSONL viaaudit-writer.ts. Added toALL_PHASESafterpatterns(default OFF; opt-in viagbrain config set cycle.skillopt.enabled true); cycle phase wrapper atsrc/core/skillopt/cycle-phase.tswalks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added toPROTECTED_JOB_NAMES. Surface: dream-cycle phase wrapper;--allbatch mode (src/core/skillopt/batch.ts:runBatchAll);--target-modelsfleet (runFleetparallel per-model receipts underskillopt/fleet/<slug>/); MCP oprun_skillopt(admin scope + per-skillskillopt.allowed_skillsallowlist, NOT localOnly, validatesskill_namekebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minionskillopthandler +--backgroundwithallowProtectedSubmit: true; write-flavored optimization viasrc/core/skillopt/write-capture.ts:buildWriteCaptureRegistry(virtualput_page/submit_job/file_uploadcaptured in-memory;--write-captureflag; its read tools and the rollout registry inrollout.tsdrop""/nulloptional arguments and validate against the op schema before the handler, like MCP dispatch, and throw a failed read asasAgentToolError(src/mcp/dispatch.ts) so the model reads the same code, message, suggestion and runnablefixa read-scope HTTP MCP caller gets, with a fix naming only tools the rollout offers); held-out real-user test set viasrc/core/skillopt/held-out.ts(capture infra at~/.gbrain/skillopt-captures/<skill>/<run>.jsonl,--held-out <path>flag,runHeldOutGatecandidate >= baseline). Hermetic via DI seams (opts.chatFnfor optimizer + judge;opts.toolLoopFnfor rollouts; nomock.module).--bootstrap-from-skill→runBootstrapFromSkillinsrc/core/skillopt/bootstrap-benchmark.ts: readsSKILL.mddirectly (norouting-eval.jsonl), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed tobootstrap_empty).--bootstrap-tasks N(default 15, capped 50);maxTokensscalesmin(8000, max(4000, N*220)). The stderr REVIEW line prints the literalgbrain skillopt <name> --bootstrap-reviewed --split 1:1:1— load-bearing because the default4:1:5split makes a 15-task starter'sD_sel = floor(15/10) = 1, below the>=5floor, so a 15-task benchmark needs--split 1:1:1. Both bootstrap generators shareassertBenchmarkAbsent+readSkillBodyOrThrow;--bootstrap-from-skillis mutually exclusive with--bootstrap-from-routing/--benchmark/--all/--target-models/--resume. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired:--held-out <path>is parsed and threaded through every caller (CLI main +--backgroundheld_out_path+ batch/fleetheldOutPath+ therun_skilloptheld_out_pathparam), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate.assertBundledMutationHeldOutin bundled-skill-gate.ts: bundled +--allow-mutate-bundledrequires a NON-EMPTY held-out (MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE= 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel throughrunSkillOpt); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting).receipt.baseline_sel_scorepopulated + a real final-test eval (test_score+baseline_test_score) scoring best + baseline onsplit.test; sharedscoreSkillOnTasksprimitive (validate-gate.ts) backs baseline/final-test/held-out scoring.--no-mutatewrites proposed.md viawriteProposedin version-store.ts.maxRuntimeMinENFORCED (wall-clock deadline between steps →skillopt_runtime_exceeded→ outcome aborted). Two eval-internal ablation opts onSkillOptOpts(NOT on CLI):reflectMode('both'/'failure-only') anddisableValidationGate(greedy-accept), recorded inRunReceipt+ auditrun_startfor replayability;optimizerModeis a product setting, required onSkillOptOpts('one-shot-rewrite'default,'reflect'=--loop;optimizer_modeon therun_skilloptop and job data) and recorded in the receipt;ROLLOUT_SUCCESS_THRESHOLD = 0.5named constant for the partition; one-shot fence-strip is anchored (^```...```$) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical idclaude-haiku-4-5is insrc/core/anthropic-pricing.ts(aBudgetTracker-capped run on Haiku would otherwise throwno_pricingon the FIRSTchat()of every rollout);runValidationGate(validate-gate.ts) scans settled results forisMustAbortError(error)(fromworker-pool.ts;BUDGET_EXHAUSTEDis inMUST_ABORT_ERROR_TAGS) and re-throws so the caller aborts loudly instead of recording a hollowselScore:0— ordinary non-abort rollout errors still fail-open toscore:0(judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-outclaude-clichild — or every rollout carrying ajudge_error) throwsskillopt_all_rollouts_failed/skillopt_all_judge_errors(constants exported from validate-gate.ts) so a dead provider ends the runerroredwith the first provider message asabort_detailinstead of a plausibleno_improvementat 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reasonno_edits_proposed[: <first reflect error>]+ one stderr line, distinct from the apply-rejectedno_edits_applied, and does not touch the rejected buffer.GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG=1(empty config dir) logs the child out on every platform, macOS included — docs/comment make no keychain-survives claim (pinned bytest/skillopt/deadline-and-hermetic.test.ts). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial),test/skillopt/bootstrap-from-skill.test.ts(20 cases),test/skillopt/rollout.test.ts,test/skillopt/validate-gate-abort.test.ts(7 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the siblinggbrain-evalsrepo.src/core/skillopt/{reflect,output-cap,run-outcome,remediation,checkpoint,models-plan,job,bootstrap-run,must-abort,preflight}.ts— skillopt run honesty and model provenance (user docs:docs/guides/skillopt.md"Optimizer output" + "Model provenance"). Output caps (output-cap.ts): one optimizer cap for every reflect call (patch + rewrite modes) and the default one-shot rewrite, precedence--reflect-max-tokens/ MCP+jobreflect_max_tokens(remote callers clamped to 256-32000) >skillopt.reflect_max_tokens(invalid warns once, valid honored exactly) >defaultMaxOutputTokens(optimizer)(32000 thinking, 4096 otherwise);skilloptOutputCap(model, siteCap)gives the judge (200) and bootstrap sitesmax(siteCap, 8192)on thinking models only — gatewaychat()semantics are untouched. Reply classification (reflect.ts): at most one error per call, in precedencereflect_<mode>_truncated(length stop; partial edits dropped) >_empty_reply>_no_parseable_edits>_invalid_edits; a fenced or bare{"edits": []}is a deliberate, usable empty; partial invalid drops sum intoreflect_invalid_edits_dropped; the skill body is sent whole when it fitsresolveChatContextTokens(optimizer)minus output cap and bounded prompt overhead at 3 chars/token (unknown window → 120,000 chars), else truncated with an in-prompt disclosure +skill_body_truncated; prompt + cap over the window refuses the call (_context_too_small), provider length errors map to_context_overflow; the one-shot rewrite refuses onone_shot_rewrite_output_cap_too_small/_body_truncatedand never promotes a_truncatedreply. The judge recordsjudge_error: llm_truncatedand bootstrap rows skip astruncatedon a length stop. Must-abort (must-abort.ts): budget exhaustion, AI spend-policy refusals, runtime deadline and SIGINT rethrow (the validation gate uses the same predicate) at every optimizer/judge/held-out/bootstrap site, so the run endsabortedwith its real reason. Outcome (run-outcome.ts):acceptedif any candidate was accepted (even after an early stop),erroredwithabort_detail: optimizer_output_unusable: <first error>when no optimizer reply in the whole run was usable, elseno_improvement; 2 consecutive fully-unusable steps (any class) stop the loop (stop_reason: early_stop_unusable_output);buildResumeCommandrebuilds the exact resume command from the stored run spec plus the run's mode, cost cap, runtime cap,--models-strictand--force(only when the run used it; the dirty-tree gate admits a resume whose SKILL.md equals the checkpoint's best text); output-cap failures (fromabort_detail, or the trailing reflect error of an early stop) double the reflect cap, contract failures put a quoted'<other-model>'in place of the optimizer model. An early-stopped run keeps its checkpoint and resume command even when it resolvesno_improvement; a resume re-runs the trailing fully-unusable steps (rewindCursor) and restarts the early-stop streak, a kept checkpoint banks the final evaluation's spend and the rewound cursor is persisted before any save, the cycle's skillopt phase GCs kept checkpoints older than 7 days, and a legacy checkpoint whose best text moved past its baseline counts as already accepted. CLI exit map: accepted 0, no_improvement 1, aborted/errored 2. Remediation (remediation.ts):SKILLOPT_REMEDIATION_CODES→{code, fix, docs}receipt entries whosedocsanchors into the guide's error-code table (pinned bytest/skillopt/error-code-docs.test.ts); errors deduped, max 20 x 300 chars. Checkpoint/resume (checkpoint.ts): stores anext_epoch/next_stepcursor (legacy checkpoints converted), the early-stop counter, the reflect tally, ledger rows and cost on completed steps and handled aborts (an abort saves the step-start tally, since resume re-runs that step), and a run spec;--resumerefuses a changed benchmark/held-out/split or a no-mutate → mutate widening, and allows optimizer model, reflect cap and cost cap overrides; the receipt merges prior segments intomodels_used(models_used_scope: full_run, orsince_resumefor legacy checkpoints) plusprior_segments_cost_usd. Models plan (models-plan.ts):resolveSkillOptModelsis the ONE role resolution (optimizer→tier deep, target→subagent, judge→reasoning; flag > config chain) used by the CLI, therun_skilloptop, the cycle phase and the job handler (four-path golden test);buildModelsPlanadds per-task judge overrides (benchmark + held-out; the default judge is inactive when no reachable LLM-judged task lacks its ownjudge.model), gateway expansion/chat with retained sources, the embedding model of the column search actually reads (file plane /GBRAIN_EMBEDDING_MODEL, never DB rows) and the reranker when enabled; the stderr banner prints before any spend andmodels_planlands on the receipt +run_startaudit. Strict mode (--models-strict/skillopt.models_strict; unrecognized values warn and count as on) aborts before spend when any active touchpoint came frommodels_default,tier_default,fallback,unknownor a capability substitution, listing a copy-paste fix per touchpoint (an unreadableskillopt.models_strictcounts as on; an explicitembedding_columns.embeddingoverride counts as configuration); it applies to batch, fleet, both bootstrap modes and background jobs. Echoed strings passsanitizeEcho(control chars stripped, 200-char cap). Jobs (job.ts): job data records the model flags and strict setting; the handler re-resolves sources and re-runs the strict check at execution time, legacy jobs resolve asunknown. Bootstrap (bootstrap-run.ts): both bootstrap modes resolve the optimizer via the plan, print its banner row, honor strict and--dry-run, and run under a--max-cost-usdtracker. Preflight (preflight.ts): prices each role's per-call reservation with the tracker'sreservationCostUsdat effective caps and aborts pre-spend withreservation_exceeds_capnaming the role; the heuristic expected-cost estimate is reported separately. The cycle phase forwardsabort_reason/abort_detail/run_id/remediation, recordsskipped_budget(no calls; retried only after the admission fingerprint — optimizer/target/judge models, reflect cap, per-skill cap,pricing.overrides, gbrain version, benchmark content (unreadable benchmark re-admits) — changes) and gateserroredretries 24h viacycle.skillopt.last_error.<skill>without bankinglast_run.src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-resident-locate,nag-state}.ts— brain-resident skillpacks.manifest-v1.tsgains optionalbrain_resident+schema_pack(additive).runInitBrainPackscaffolds a pack beside brain content (brain_resident:true, exactgbrain_min_version, 5-section machine-parseable README);applyWritePlanis factored out ofinit-scaffold.tsfor the shared refuse-overwrite loop. Topology A:src/commands/sources.tsrunAddprintsbrain-pack-advisoryto stderr afteropsAddSource, fail-open;nag-state.ts(~/.gbrain/skillpack-nag-state.json) keys declines by(source-repo brain_id, source_id, pack_name)with puredecideNagAction(first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B:brain-resident-locate.loadResidentPacksForServer(source-scoped viasourceScopeOpts) backs thelist_brain_skillpackop;getResidentSkillDetailbacksget_skillsource_id;scaffold_specis the git source, never a server FS path. Tests:test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts+ the brain-resident cases intest/skillpack-manifest-v1.test.ts.src/core/skillpack/{manifest-v1,tarball,state,remote-source,trust-prompt,bootstrap-display,scaffold-third-party,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit}.ts+examples/skillpack-reference/+docs/skillpack-anatomy.md+scripts/build-skillpack-anatomy.ts— third-party skillpack ecosystem.gbrain skillpack scaffold <owner/repo|https-url|./tgz|./local-dir>resolves the spec viaclassifySpec, fetches through SSRF-hardenedgit-remote.ts(git) or extracts the tarball into~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/, validatesskillpack.json(api_versiongbrain-skillpack-v1), checksgbrain_min_version, surfaces a TOFU first-install identity-confirm prompt (author + source + pinned commit + tarball SHA + tier; prompted through interaction.readLine; with no human at the terminal the CLI asks throughrequireConsent(effectpersistent_install, preapprovals never apply):--trustor--yesis the user's approval, otherwise nothing is written and it exits 3 with the consent payload), records the pin in machine-owned~/.gbrain/skillpack-state.json(schemagbrain-skillpack-state-v2, which adds per-skills-root install bases and pins and reads a v1 file as v2 with none; atomic unique temp file + rename; read-modify-write callers go throughupdateStateunder the state lock,isAlreadyTrustedskips re-prompt on author+pin match), runs throughenumerateScaffoldEntries→copyArtifacts(one-time additive, refuses to overwrite), then DISPLAYSrunbooks/bootstrap.mdWITHOUT executing (deliberately does not auto-execute). Registry catalog atgarrytan/gbrain-skillpack-registrysplit intoregistry.json(PR-able,gbrain-registry-v1) +endorsements.json(maintainer-only overlay,gbrain-endorsements-v1);effectiveTiermerges.registry-client.tsfetches both viaIf-None-Matchetag with 1h soft-TTL + stale-fallback (originsfresh_fetch | cache_warm | cache_soft_stale | cache_hard_stale); hard-fail only on no-cache + no-network. CLI:gbrain skillpack {search,info,registry,doctor,init,pack,endorse}. Doctor walksSKILLPACK_RUBRIC_V1(10 binary dimensions: 5 required CORE — manifest_valid, skills_have_skill_md, routing_evals_present ≥5 intents, skills_have_unique_triggers MECE, changelog_present_and_current — and 5 quality BADGES — unit_tests_present, e2e_tests_present, llm_eval_present ≥3 cases, bootstrap_runbook_present, license_present); tier eligibility:endorsedneeds all 10,communityneeds core + ≥3 badges,experimentalneeds core only,blockedwhen any core fails.--quick5s structural sweep;/.gbrain/audit/skillpack-YYYY-Www.jsonl--fix --yesauto-scaffoldsauto_fixable: truedimensions and refuses to overwrite files whose mtime is newer thanskillpack.json.gbrain skillpack init <name>lands 11 files (skillpack.json, SKILL.md, routing-eval.jsonl, test/example.test.ts, e2e/example.e2e.test.ts, evals/example.judge.json, runbooks/{bootstrap,uninstall,upgrade-template}.md, CHANGELOG, README, LICENSE); freshly-init'd scores 10/10;--minimalskips test/e2e/evals.gbrain skillpack packpacks a deterministic tarball via GNU tar (--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner+GZIP=-n+TZ=UTC); refuses ontier_eligibility === 'blocked'. Extract caps (5000 files / 100MB total / 1MB per file / 255-char paths / 100:1 compression ratio); rejects symlinks/hardlinks/devices/FIFOs.gbrain skillpack endorse <name> [--tier ...] [--push] [--dry-run]runs in a clone of the registry repo: validates the pack inregistry.json, mutatesendorsements.jsonvia pureapplyEndorsement, stable-key-orders the write, commitsendorse: <name> -> <tier>, optionally pushes. JSONL audit at `(ISO-week rotated, honorsGBRAIN_AUDIT_DIR).examples/skillpack-reference/is a 10/10 reference pack pinned bytest/e2e/skillpack-third-party.test.ts.docs/skillpack-anatomy.mdauto-generated viascripts/build-skillpack-anatomy.ts(--checkfor CI drift). CLI dispatch insrc/commands/skillpack.tsdisambiguates third-party (contains/,://,.tgz) from bundled-skill kebab; kebab routes bundled-first, registry-fallback. Tests:test/skillpack-{manifest-v1,tarball,state,remote-source,trust-prompt,registry-schema,registry-client,rubric,doctor,init-scaffold,pack-publish,endorse,audit,scaffold-third-party}.test.ts+test/e2e/skillpack-third-party.test.ts. Spec atdocs/designs/SKILLPACK_REGISTRY_V1_SPEC.md`.src/core/skillpack/{personas,bridge-state,harness-bridge}.ts+src/commands/skillpack/{shared,scaffold,reference,harness}.ts— the harness skill bridge.src/commands/skillpack.tsis a peeled FAÇADE (dispatch + HELP_TOP + the install/uninstall removal errors; module-size ratchet); per-subcommand handlers live insrc/commands/skillpack/and the flag registry scans the dir via the façade'sfacadeExpansionentry — spell foreign CLI flags dash-less in these modules' comments/strings (prose-bleed class).scaffold --harness <claude-code|openclaw|codex|opencode>installs a persona-curated set into the harness's native skills dir: personas live inskills/plugin-lanes.json#personas(personas.tsis the SINGLE validation implementation —scripts/generate-plugin-tree.tsimports it; membership ⊆ the plugin lane set, so lane-excluded slugs are refused with their recorded reason); slugs path-resolve viabundle.ts'suniverse:'manifest'(the 8 lane additions are all absent from openclaw.plugin.json#skills). Safety: frontmatter fail-loud gate pre-write (a frontmatterless SKILL.md bricks Codex sessions), target-side confinement inassertTargetsConfined(deepest-existing-ancestor realpath — copy.ts confines SOURCES only), refuse-overwrite, and written-only ownership inbridge-state.ts(~/.gbrain/skillpack-bridge-state.json, schemagbrain-skillpack-bridge-v1, fail-open load, install-time sha256 per written file — never touchesskillpack-state.json, whose loader drops unknown keys).--stubrenders cold-pull pointers (frontmatter verbatim +<!-- gbrain-skill-stub v1 -->marker; ships the shared-dep closure AND sibling aux files —get_skillserves only the SKILL.md body) behind a three-check preflight insrc/commands/skillpack/harness.ts(publish gate dual-plane, per-slug servability viaverifySlugsServable, best-effort local surface warn — the module deliberately does NOT importsrc/mcp/surface.ts, whose comments would bleed serve flags into the allowlist;get_skill ∉ STARTER_OPSis pinned by a contract test).reference --harnessis a stub-aware three-way lens (local_editvsupstream_driftvsunknown— no install-time hash, never auto-applied — via the hash ledger; marker fallback survives state loss both directions) +--apply-clean-hunks(refuses stub files);remove --harnessdeletes ledger-owned files only;skillpack statusrenders an installed-bridges section fromcollectBridgesStatus. openclaw delegates torunScaffold({skillSlugs}); codex/opencode require an explicit dest until observation runs. Claude-code dirs come fromhost-specs.ts(claudeUserSkillsDir/claudeProjectSkillsDir, HOME-env-first). Tests:test/skillpack-{personas,bridge-state,harness-bridge,reference-harness,scaffold-harness}.test.ts. Doc: the harness-bridge section ofdocs/guides/skillpacks-as-scaffolding.md. #5912:ownedBridgeSlugs(entry)(harness-bridge.ts) is the one accessor for an install's skill slugs without the reservedSHARED_DEP_LEDGER_KEY, used by the no-slug reference lens, bridge status and remove; the scaffold "Update lens" / remove hints repeat the--dest,--scope projectand--workspacethe user passed.src/core/skillpack/{safe-update,update-journal,file-lock}.ts+src/commands/skillpack/update.ts— the safe-update lane:gbrain skillpack reference <name>|--all --update-untouched(routed fromreference.ts),skillpack pin|unpin <name>andskillpack restore <id>.classifySkillcompares each file of a skill's closure (its bundle dir plus missing shared dependencies; paired sources outside the skills root are reported, never written) with the install's recorded base instate.tsrootsfirst, then with the released-version history:unchanged,absent,untouched,historical(needs--accept-historical),local_edits,no_history. A skill updates whole or not at all; skip reasons arepinned,history_unverified,unsafe_target,local_edits,no_history,historical_only.runSkillpackUpdatetakes the workspace writer lock then the state lock (file-lock.ts, O_EXCL with a release token, mtime-stale reclaim), stages and validates the closure inside the skills root, writes the journal before any change (update-journal.ts:~/.gbrain/skillpack-backups/<id>/, kept 30 days or the last 10), backs up and rehashes each file right before its rename, then runs conformance, trigger and resolver checks (defaultValidator); a failure rolls back only files whose hash still equals what the run wrote.runSkillpackRestorerestores applied files whose hash still equals the post-update hash and is idempotent.recordScaffoldBasesrecords bases on scaffold, sync and harness installs; harness destinations are recorded, not updated. Never prompts (--dry-runpreviews); exit 0 nothing failed, 1 with--fail-on-skippedwhen a skill was skipped, 2 on a failure with the files touched and the restore command. Doctor:src/commands/doctor/checks/skillpack-update.ts(skillpack_update_incomplete,skillpack_backups), filesystem only. Error codesskillpack_*inerror-registry.ts. Tests:test/skillpack-safe-update.test.ts. Doc: "Updating installed skills" indocs/guides/skillpacks-as-scaffolding.md.src/core/skills-integrity.ts— Tamper-evidence manifest for the bundledskills/tree; NOT a signature system. Pure functions overnode:cryptosha256:computeSkillsManifest(dir)(recursive, sorted '/'-relative paths, excludes the manifest itself, skips symlinks),renderSkillsManifest(dir)(2-space JSON + trailing newline, deterministic),verifySkillsManifest(dir, manifest)→{modified, missing, extra}. Committed manifest lives atskills/skills.lock.json(SKILLS_MANIFEST_FILENAME); regenerate viabun run scripts/generate-skills-manifest.ts, which first appends the lock's hashes toskills/skills.lock.history.json(gbrain-skills-lock-history-v1, append-only: every released sha256 per file, the record--update-untouchedreads throughloadVerifiedSkillsLockHistory; the lock records the history's own hash).scripts/check-skills-lock-history.ts(bun run check:skills-lock-history, inbun run verify) fails when the history misses a current hash or drops an entry HEAD or the merge-base had. Consumers: the warn-onlyskills_manifest_integritydoctor check insrc/commands/doctor/skill-checks.ts(ok/skip when no manifest is present — user workspaces and compiled-binary installs are not drift) and the CI freshness guardscripts/check-skills-manifest-fresh.sh(bun run check:skills-manifest, inbun run verify). Pinned bytest/skills-integrity.test.ts.
The skill resolver entries continue in Skills (continued).