Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
43.9 KB
Raw Blame

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 of docs/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 match docs/GBRAIN_RECOMMENDED_SCHEMA.md in 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 (no null placeholders), 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.ts executes 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), owner audience on the host and downstream only on a thin client (host-only skills answer skill_not_found). The embedded module is generated (bun run scripts/generate-bundled-skills.ts, --check fails when stale) and holds only membership, audience and asset lists; description and triggers are read from the embedded SKILL.md at runtime. spring-index.ts renders one line per skill from frontmatter triggers: under SKILL_INDEX_BUDGET_BYTES (6144), trimming triggers before ever dropping a skill and refusing (SkillIndexTooLarge) rather than truncating. skills-block.ts writes 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 one Bash(<launcher> bundled-skill:*) allow rule on Claude Code only when absent and removes it only when it added it, and backs setup --skills-index-only; every sync and removal runs under the instruction-ledger lock of brain-first.ts (outcome reason ledger_locked when it cannot be taken), and a Codex opt-out (flag, env or declined instructions) also strips the index recorded in the sibling AGENTS.md/AGENTS.override.md of the same CODEX_HOME (paired outcome, shown by skillsOutcomeShown); setup, connect --install, harness connect --install and bootstrap harness (harness-skills-index.ts) share it, and a requested index that cannot be written exits non-zero. doctor harness_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-resolvable and skill_currency read past the block through skillsIndexedIn. check-skills-embedded.sh compiles a binary and proves it serves every bundled file byte-identical to skills/ (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, honors GBRAIN_AUDIT_DIR via shared resolveAuditDir()). 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 future skill_brain_first_trend doctor 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): SkillBrainFirstResult walks the compliance ladder for every SKILL.md: (1) absent external-lookup pattern → no_external; (2) brain_first: exempt frontmatter → exempt_frontmatter; (3) canonical > **Convention:** see [conventions/brain-first.md](../...) callout → compliant_callout; (4) explicit ## Phase 1: Brain heading → compliant_phase; (5) first gbrain search/query/get_page reference precedes first external pattern in the BODY (frontmatter stripped) → compliant_position; (6) else missing_brain_first warn. External pattern set: word-boundary regex over web_search, web_fetch, exa, perplexity, happenstance, crustdata, captain_api, firecrawl. Position scan is BODY-ONLY so a tools: [web_search] frontmatter declaration doesn't false-flag the skill. The 40-name FORMERLY_HARDCODED_EXEMPT list is preserved so doctor can emit a "this used to be auto-exempt, declare brain_first: exempt if 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 and scripts/skills-commit-gate.sh). extractInvocations reads every gbrain ... invocation in shell fences and inline code (placeholders kept as one token, <!-- skill-drift-ok: reason --> skips a line or the line after it); analyzeSkillDrift runs each through the injected CliSurface, which is the dispatcher's own code (CLI_ONLY, cliOps/cliAliases, ROUTERS subcommand inventories, parseGlobalFlags, validateCommandFlags; a router subcommand of an op command checks against CLI_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-only scripts/skill-drift-undeclared-subcommands.txt (SKILL_DRIFT_UNDECLARED_SUBCOMMANDS for a new one, SKILL_DRIFT_UNDECLARED_STALE for a line no skill needs); an operation's positional arguments are never subcommands. Operation-shaped frontmatter tools: entries (snake_case or mcp:) must be real operations (web_fetch/web_search are host tools). Size: a SKILL.md over 16384 bytes needs a skills/skill-budgets.tsv row 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.txt is shrink-only. --sizes <files> prints the Skill-size: lines the commit gate shows. Pinned by test/skill-drift.test.ts and the test/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, doctor skill_health, a gbrain maintain line, skillpack-check's skill_health field). computeSkillHealth checks one skills folder: bytes against the bundle's skills/skill-budgets.tsv row (else the 16384-byte cap), growth past 110% of last_diet, description bytes, frontmatter triggers:, and analyzeSkillDrift over every markdown file in the skill with the live cliSurface(). Each finding has code, observed, expected, fix and verify. Scope: a folder with manifest.json or skills.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. parseSkillBudgets and the caps are shared with scripts/check-skill-health.ts. Pinned by test/skill-health.test.ts (including 100 skills under 500 ms).

  • src/core/skill-catalog.ts — legacy host-repo fallback for MCP list_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; with query (#6471) it ranks the section-filtered entries by scoreSkillMatch (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 at limit (default 10, max 100) and sets match: { score, matched_on } per entry; without query the output is byte-identical to the unranked build. The list_skills op refuses query with invalid_params on the schema-version-2 and active shared-catalog routes before any catalog read (ops/skills-catalog.ts); query is advertised on the full MCP surface only (fullSurfaceOnly) so the starter list keeps its size budget. Pinned by test/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 over gbrain 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 require mcp.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 — assertSkillNameShape rejects separators/../null/space before any FS access; the client name is a manifest LOOKUP KEY (via loadOrDeriveManifest), never a raw path segment; confineManifestPath does realpath + relative-containment + SKILL.md-regular-file check on EVERY entry (defeats poisoned manifest.json path, symlink/.. escape). (3) frontmatter allowlist — GetSkillResult.frontmatter projects a safe subset; private writes_to + sources dropped. (4) prose-only + 256KB cap (MAX_SKILL_MD_BYTES, env GBRAIN_MAX_SKILL_MD_BYTES), size-checked twice (statSync + UTF-8 byte length). (5) no install_path serve for remote — remote callers use autoDetectSkillsDir (no install-path tier) so a hosted gbrain with no agent repo returns storage_error; local callers use autoDetectSkillsDirReadOnly. (6) MCP rate-limiter caps call rate. Config reads honor BOTH planes: readMcpPublishSkills / readMcpSkillsDir prefer the DB plane (engine.getConfig) over the file plane (ctx.config.mcp). Tool-honesty: resolveSkillTools shares list/detail semantics: declared tools: narrow the caller's effective inventory via crossReferenceTools; valid mapping frontmatter that omits tools inherits availableBrainTools(ctx) without granting new permissions. Explicit tools: [] stays empty; invalid tools values, malformed YAML, and missing frontmatter never receive the inherited inventory. The operation handlers resolve current DB/file publication gates through disabledOpsForPublishGates before building either response; unpublished operations are excluded from declared and inherited tools and both instruction envelopes. opAllowedForBoundClient also 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's tools remains the declared list (empty when omitted), while usable_tools carries the effective inventory. Pinned by test/skill-catalog-optional-tools.test.ts. buildSkillCatalog's instructions envelope (SKILL_CATALOG_INSTRUCTIONS) carries the "these are prose, follow-then-call-tools" protocol. These fallback skills are host-filesystem repo-global — sourceScopeOpts(ctx) / ctx.brainId deliberately do NOT apply. buildSkillCatalog is resilient (one malformed/escaping skill is skipped, never throws). Config keys in src/core/config.ts: GBrainConfig.mcp?: { publish_skills?, skills_dir? } + KNOWN_CONFIG_KEYS entries mcp.publish_skills/mcp.publish_skills_prompted/mcp.skills_dir + mcp. prefix in KNOWN_CONFIG_KEY_PREFIXES. src/commands/init.ts writes config.mcp = { publish_skills: true, ... } for new installs (existing config wins on re-init). src/commands/upgrade.ts:runPostUpgrade adds a one-time consent prompt (gated by mcp.publish_skills_prompted; existing installs stay OFF until owner opts in). The legacy catalog entrypoints in src/core/ops/skills-catalog.ts (spread into the operations.ts façade) are: list_skills with optional section filter + cliHints:{name:'skills'}; get_skill taking name (+ source_id for 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 the operations array). Descriptions in src/core/operations-descriptions.ts (LIST_SKILLS_DESCRIPTION, GET_SKILL_DESCRIPTION, SKILL_CATALOG_INSTRUCTIONS, SKILL_CLIENT_GUIDANCE), pinned by test/operations-descriptions.test.ts. CLI: gbrain skills / gbrain skill <name>. Pinned by test/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) over test/fixtures/skill-catalog/.

  • src/core/skill-fix-gates.ts — shared safety primitives for dry-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.ts re-exports them.

  • src/core/skill-frontmatter.ts — shared content-based SKILL.md frontmatter parser. Array fields (writes_to, tools, triggers) use js-yaml with 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 the brain_first: 'exempt' declarative opt-out and surfaces near-miss declarations (brain-first, BrainFirst, quoted values, unknown values) as a typed brain_first_typo field so doctor can emit a paste-ready hint rather than fail silently. Single canonical form: snake_case brain_first: exempt, lowercase, unquoted.

  • src/core/skill-manifest.ts — parser for skill-manifest.json records. 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-disk manifest.json, or the SKILLPACK_MANAGED_BEGIN block 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 frontmatter triggers: with curated RESOLVER.md / AGENTS.md rows from skillsDir AND 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. Exports loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[], entriesToResolverContent(entries): string (synthesizes a markdown-table resolver string for runRoutingEval's string-content API), findPrimaryResolverPath(skillsDir): string | null, the FRONTMATTER_SECTION constant, and _resetWarnedSkillsForTests. Skip rules: non-directory entries (a symlink dirent is followed via statSync — readdirSync dirents 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 no SKILL.md (deprecated install/ graceful-skipped), no triggers: array, or malformed YAML (warn-once + skip). Reuses parseSkillFrontmatter from src/core/skill-frontmatter.ts, including block and wrapped flow-sequence arrays. Pinned by test/skill-trigger-index.test.ts (18 hermetic cases). CI gate bun run check:resolver (= bun src/cli.ts check-resolvable --strict --skills-dir skills/) wired into bun 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> treats SKILL.md as 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 use gateway.toolLoop directly with no-op persistence callbacks (zero subagent_messages pollution) + a read-only tool allowlist derived from BRAIN_TOOL_ALLOWLIST minus put_page/submit_job/file_upload. Default is one gated one-shot rewrite (optimizerMode); --loop runs two reflect calls per step (deprecated, removed on or after 2026-12-03: loop-deprecation.ts emits the skillopt_loop_deprecated coaching notice once per CLI run, run_skillopt call 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 --split override); audit JSONL via audit-writer.ts. Added to ALL_PHASES after patterns (default OFF; opt-in via gbrain config set cycle.skillopt.enabled true); cycle phase wrapper at src/core/skillopt/cycle-phase.ts walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to PROTECTED_JOB_NAMES. Surface: dream-cycle phase wrapper; --all batch mode (src/core/skillopt/batch.ts:runBatchAll); --target-models fleet (runFleet parallel per-model receipts under skillopt/fleet/<slug>/); MCP op run_skillopt (admin scope + per-skill skillopt.allowed_skills allowlist, NOT localOnly, validates skill_name kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion skillopt handler + --background with allowProtectedSubmit: true; write-flavored optimization via src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry (virtual put_page/submit_job/file_upload captured in-memory; --write-capture flag; its read tools and the rollout registry in rollout.ts drop ""/null optional arguments and validate against the op schema before the handler, like MCP dispatch, and throw a failed read as asAgentToolError (src/mcp/dispatch.ts) so the model reads the same code, message, suggestion and runnable fix a read-scope HTTP MCP caller gets, with a fix naming only tools the rollout offers); held-out real-user test set via src/core/skillopt/held-out.ts (capture infra at ~/.gbrain/skillopt-captures/<skill>/<run>.jsonl, --held-out <path> flag, runHeldOutGate candidate >= baseline). Hermetic via DI seams (opts.chatFn for optimizer + judge; opts.toolLoopFn for rollouts; no mock.module). --bootstrap-from-skill → runBootstrapFromSkill in src/core/skillopt/bootstrap-benchmark.ts: reads SKILL.md directly (no routing-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 to bootstrap_empty). --bootstrap-tasks N (default 15, capped 50); maxTokens scales min(8000, max(4000, N*220)). The stderr REVIEW line prints the literal gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1 — load-bearing because the default 4:1:5 split makes a 15-task starter's D_sel = floor(15/10) = 1, below the >=5 floor, so a 15-task benchmark needs --split 1:1:1. Both bootstrap generators share assertBenchmarkAbsent + readSkillBodyOrThrow; --bootstrap-from-skill is 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 + --background held_out_path + batch/fleet heldOutPath + the run_skillopt held_out_path param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. assertBundledMutationHeldOut in bundled-skill-gate.ts: bundled + --allow-mutate-bundled requires 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 through runSkillOpt); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). receipt.baseline_sel_score populated + a real final-test eval (test_score + baseline_test_score) scoring best + baseline on split.test; shared scoreSkillOnTasks primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. --no-mutate writes proposed.md via writeProposed in version-store.ts. maxRuntimeMin ENFORCED (wall-clock deadline between steps → skillopt_runtime_exceeded → outcome aborted). Two eval-internal ablation opts on SkillOptOpts (NOT on CLI): reflectMode ('both'/'failure-only') and disableValidationGate (greedy-accept), recorded in RunReceipt + audit run_start for replayability; optimizerMode is a product setting, required on SkillOptOpts ('one-shot-rewrite' default, 'reflect' = --loop; optimizer_mode on the run_skillopt op and job data) and recorded in the receipt; ROLLOUT_SUCCESS_THRESHOLD = 0.5 named 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 id claude-haiku-4-5 is in src/core/anthropic-pricing.ts (a BudgetTracker-capped run on Haiku would otherwise throw no_pricing on the FIRST chat() of every rollout); runValidationGate (validate-gate.ts) scans settled results for isMustAbortError(error) (from worker-pool.ts; BUDGET_EXHAUSTED is in MUST_ABORT_ERROR_TAGS) and re-throws so the caller aborts loudly instead of recording a hollow selScore:0 — ordinary non-abort rollout errors still fail-open to score:0 (judge-hiccup posture preserved), but a 100%-failed gate (every task errored — e.g. a logged-out claude-cli child — or every rollout carrying a judge_error) throws skillopt_all_rollouts_failed / skillopt_all_judge_errors (constants exported from validate-gate.ts) so a dead provider ends the run errored with the first provider message as abort_detail instead of a plausible no_improvement at 0.000; the orchestrator's zero-candidate step (reflect produced/parsed no edits) logs audit reason no_edits_proposed[: <first reflect error>] + one stderr line, distinct from the apply-rejected no_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 by test/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 sibling gbrain-evals repo.

  • 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+job reflect_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 sites max(siteCap, 8192) on thinking models only — gateway chat() semantics are untouched. Reply classification (reflect.ts): at most one error per call, in precedence reflect_<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 into reflect_invalid_edits_dropped; the skill body is sent whole when it fits resolveChatContextTokens(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 on one_shot_rewrite_output_cap_too_small / _body_truncated and never promotes a _truncated reply. The judge records judge_error: llm_truncated and bootstrap rows skip as truncated on 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 ends aborted with its real reason. Outcome (run-outcome.ts): accepted if any candidate was accepted (even after an early stop), errored with abort_detail: optimizer_output_unusable: <first error> when no optimizer reply in the whole run was usable, else no_improvement; 2 consecutive fully-unusable steps (any class) stop the loop (stop_reason: early_stop_unusable_output); buildResumeCommand rebuilds the exact resume command from the stored run spec plus the run's mode, cost cap, runtime cap, --models-strict and --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 (from abort_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 resolves no_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 whose docs anchors into the guide's error-code table (pinned by test/skillopt/error-code-docs.test.ts); errors deduped, max 20 x 300 chars. Checkpoint/resume (checkpoint.ts): stores a next_epoch/next_step cursor (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; --resume refuses 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 into models_used (models_used_scope: full_run, or since_resume for legacy checkpoints) plus prior_segments_cost_usd. Models plan (models-plan.ts): resolveSkillOptModels is the ONE role resolution (optimizer→tier deep, target→subagent, judge→reasoning; flag > config chain) used by the CLI, the run_skillopt op, the cycle phase and the job handler (four-path golden test); buildModelsPlan adds per-task judge overrides (benchmark + held-out; the default judge is inactive when no reachable LLM-judged task lacks its own judge.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 and models_plan lands on the receipt + run_start audit. Strict mode (--models-strict / skillopt.models_strict; unrecognized values warn and count as on) aborts before spend when any active touchpoint came from models_default, tier_default, fallback, unknown or a capability substitution, listing a copy-paste fix per touchpoint (an unreadable skillopt.models_strict counts as on; an explicit embedding_columns.embedding override counts as configuration); it applies to batch, fleet, both bootstrap modes and background jobs. Echoed strings pass sanitizeEcho (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 as unknown. 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-usd tracker. Preflight (preflight.ts): prices each role's per-call reservation with the tracker's reservationCostUsd at effective caps and aborts pre-spend with reservation_exceeds_cap naming the role; the heuristic expected-cost estimate is reported separately. The cycle phase forwards abort_reason/abort_detail/run_id/remediation, records skipped_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 gates errored retries 24h via cycle.skillopt.last_error.<skill> without banking last_run.

  • src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-resident-locate,nag-state}.ts — brain-resident skillpacks. manifest-v1.ts gains optional brain_resident + schema_pack (additive). runInitBrainPack scaffolds a pack beside brain content (brain_resident:true, exact gbrain_min_version, 5-section machine-parseable README); applyWritePlan is factored out of init-scaffold.ts for the shared refuse-overwrite loop. Topology A: src/commands/sources.ts runAdd prints brain-pack-advisory to stderr after opsAddSource, fail-open; nag-state.ts (~/.gbrain/skillpack-nag-state.json) keys declines by (source-repo brain_id, source_id, pack_name) with pure decideNagAction (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: brain-resident-locate.loadResidentPacksForServer (source-scoped via sourceScopeOpts) backs the list_brain_skillpack op; getResidentSkillDetail backs get_skill source_id; scaffold_spec is 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 in test/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 via classifySpec, fetches through SSRF-hardened git-remote.ts (git) or extracts the tarball into ~/.gbrain/skillpack-cache/<host>/<owner>/<repo>/<sha>/, validates skillpack.json (api_version gbrain-skillpack-v1), checks gbrain_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 through requireConsent (effect persistent_install, preapprovals never apply): --trust or --yes is 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 (schema gbrain-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 through updateState under the state lock, isAlreadyTrusted skips re-prompt on author+pin match), runs through enumerateScaffoldEntries → copyArtifacts (one-time additive, refuses to overwrite), then DISPLAYS runbooks/bootstrap.md WITHOUT executing (deliberately does not auto-execute). Registry catalog at garrytan/gbrain-skillpack-registry split into registry.json (PR-able, gbrain-registry-v1) + endorsements.json (maintainer-only overlay, gbrain-endorsements-v1); effectiveTier merges. registry-client.ts fetches both via If-None-Match etag with 1h soft-TTL + stale-fallback (origins fresh_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 walks SKILLPACK_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: endorsed needs all 10, community needs core + ≥3 badges, experimental needs core only, blocked when any core fails. --quick 5s structural sweep; --fix --yes auto-scaffolds auto_fixable: true dimensions and refuses to overwrite files whose mtime is newer than skillpack.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; --minimal skips test/e2e/evals. gbrain skillpack pack packs a deterministic tarball via GNU tar (--sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner + GZIP=-n + TZ=UTC); refuses on tier_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 in registry.json, mutates endorsements.json via pure applyEndorsement, stable-key-orders the write, commits endorse: <name> -> <tier>, optionally pushes. JSONL audit at `/.gbrain/audit/skillpack-YYYY-Www.jsonl(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 at docs/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.ts is a peeled FAÇADE (dispatch + HELP_TOP + the install/uninstall removal errors; module-size ratchet); per-subcommand handlers live in src/commands/skillpack/ and the flag registry scans the dir via the façade's facadeExpansion entry — 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 in skills/plugin-lanes.json#personas (personas.ts is the SINGLE validation implementation — scripts/generate-plugin-tree.ts imports it; membership ⊆ the plugin lane set, so lane-excluded slugs are refused with their recorded reason); slugs path-resolve via bundle.ts's universe:'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 in assertTargetsConfined (deepest-existing-ancestor realpath — copy.ts confines SOURCES only), refuse-overwrite, and written-only ownership in bridge-state.ts (~/.gbrain/skillpack-bridge-state.json, schema gbrain-skillpack-bridge-v1, fail-open load, install-time sha256 per written file — never touches skillpack-state.json, whose loader drops unknown keys). --stub renders cold-pull pointers (frontmatter verbatim + <!-- gbrain-skill-stub v1 --> marker; ships the shared-dep closure AND sibling aux files — get_skill serves only the SKILL.md body) behind a three-check preflight in src/commands/skillpack/harness.ts (publish gate dual-plane, per-slug servability via verifySlugsServable, best-effort local surface warn — the module deliberately does NOT import src/mcp/surface.ts, whose comments would bleed serve flags into the allowlist; get_skill ∉ STARTER_OPS is pinned by a contract test). reference --harness is a stub-aware three-way lens (local_edit vs upstream_drift vs unknown — 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 --harness deletes ledger-owned files only; skillpack status renders an installed-bridges section from collectBridgesStatus. openclaw delegates to runScaffold({skillSlugs}); codex/opencode require an explicit dest until observation runs. Claude-code dirs come from host-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 of docs/guides/skillpacks-as-scaffolding.md. #5912: ownedBridgeSlugs(entry) (harness-bridge.ts) is the one accessor for an install's skill slugs without the reserved SHARED_DEP_LEDGER_KEY, used by the no-slug reference lens, bridge status and remove; the scaffold "Update lens" / remove hints repeat the --dest, --scope project and --workspace the 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 from reference.ts), skillpack pin|unpin <name> and skillpack restore <id>. classifySkill compares 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 in state.ts roots first, 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 are pinned, history_unverified, unsafe_target, local_edits, no_history, historical_only. runSkillpackUpdate takes 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. runSkillpackRestore restores applied files whose hash still equals the post-update hash and is idempotent. recordScaffoldBases records bases on scaffold, sync and harness installs; harness destinations are recorded, not updated. Never prompts (--dry-run previews); exit 0 nothing failed, 1 with --fail-on-skipped when 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 codes skillpack_* in error-registry.ts. Tests: test/skillpack-safe-update.test.ts. Doc: "Updating installed skills" in docs/guides/skillpacks-as-scaffolding.md.

  • src/core/skills-integrity.ts — Tamper-evidence manifest for the bundled skills/ tree; NOT a signature system. Pure functions over node:crypto sha256: 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 at skills/skills.lock.json (SKILLS_MANIFEST_FILENAME); regenerate via bun run scripts/generate-skills-manifest.ts, which first appends the lock's hashes to skills/skills.lock.history.json (gbrain-skills-lock-history-v1, append-only: every released sha256 per file, the record --update-untouched reads through loadVerifiedSkillsLockHistory; the lock records the history's own hash). scripts/check-skills-lock-history.ts (bun run check:skills-lock-history, in bun run verify) fails when the history misses a current hash or drops an entry HEAD or the merge-base had. Consumers: the warn-only skills_manifest_integrity doctor check in src/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 guard scripts/check-skills-manifest-fresh.sh (bun run check:skills-manifest, in bun run verify). Pinned by test/skills-integrity.test.ts.

The skill resolver entries continue in Skills (continued).