Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Add the OpenClaw skill-resolver plugin, skill pins and doctor miss rate
garrytane91f7d57b169
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 89ee34952a..375bfaea56 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,14 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++### Added++- `gbrain setup openclaw --skill-loading resolve|shadow|off`: a separate OpenClaw plugin, `gbrain-skill-resolver`, that puts up to 3 relevant skills in front of the model on each real user turn, ranked inside the gateway's Node process in a worker thread with a 50 ms deadline, so a busy gateway never waits on gbrain. It leaves OpenClaw's own skill list alone. `shadow` ranks and logs what it would have suggested without injecting anything; `--live-fraction`, `--pins-route` and `--owner-sender` stage a rollout. Switching modes or pins rewrites only gbrain's state file, so no OpenClaw command runs and the gateway does not reload. A partial install is never reported as done: it exits 3 with `skill_resolver_plugin_not_installed` and the commands still to run. Off by default.+- `gbrain skills pin add|remove|list --catalog <c>`: operator-chosen always-on skills, shown as a pinned block and never suggested twice. gbrain ships none; pins must name a skill in the catalog.+- `gbrain doctor --only skill_resolver` reports the OpenClaw plugin, its library, each agent's catalog and pins, and over the last 24 hours the outcomes, how often a suggested skill was opened and the deadline-miss rate; it warns when more than 5% of at least 20 turns missed the deadline.+## [0.60.633.0] - 2026-11-09### Addeddiff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex f7714f548d..ced406aa4b 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -59,7 +59,7 @@ link it here; never raise the cap.| [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/ops/sources.ts`, except `src/core/persistence/` || [Core Services (2/3, continued)](key-files/core-services-2-continued.md) | `page-state/`, `page-{body,window}/`, `progressive-batch/` || [Commit notifier](key-files/commit-notifier.md) | `src/core/notifier/` |-| [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` through `src/core/verbs/usage-log.ts` |+| [Core Services (3/3)](key-files/core-services-3.md) | `src/core/think/index.ts` to `verbs/usage-log.ts` || [Core Utilities (1/2)](key-files/core-utilities-1.md) | `archive-crawler-config.ts` through `remediation-checkpoint.ts`; [`cycle.ts`](key-files/core-cycle-primitive.md) || [Core Utilities (2/2)](key-files/core-utilities-2.md) | `src/core/repair/` through `src/core/utils.ts` || [Engines (1/2)](key-files/engines-1.md) | `src/core/connection-manager.ts` through `pglite-repair.ts` |@@ -75,7 +75,7 @@ link it here; never raise the cap.| [Runtime](key-files/runtime.md) | `src/core/abort-check.ts` through `src/core/zombie-reap.ts` || [Security](key-files/security.md) | `src/core/destructive-guard.ts` through `src/core/write-gate-scan.ts`; [purge](key-files/memory-purge.md) || [Shared brain skills](key-files/shared-skills.md) | Canonical catalog, enrollment, migration, publication and harness integration |-| [Skills](key-files/skills.md) | `src/core/audit-skill-brain-first.ts` through `src/core/skills-integrity.ts` |+| [Skills](key-files/skills.md) | `audit-skill-brain-first.ts` to `skills-integrity.ts`; [resolver](key-files/skill-resolver.md) || [Tooling And Tests](key-files/tooling-and-tests.md) | `.github/workflows/test.yml` through `test/remote-privacy-sweep.test.ts` || [CI Health And Test Guards](key-files/ci-health-and-test-guards.md) | `nightly-watch.yml` through `check-image-decoders-embedded.sh`, contributor audit, fix-wave gate || [BrainBench (sibling repo)](key-files/brainbench.md) | Cross-file contract |diff --git a/docs/architecture/key-files/skill-resolver.md b/docs/architecture/key-files/skill-resolver.mdindex 34e833e04d..94027731f3 100644--- a/docs/architecture/key-files/skill-resolver.md+++ b/docs/architecture/key-files/skill-resolver.md@@ -25,6 +25,9 @@ Contract schemas: `docs/schemas/skill-resolver.v1.*.json`. Every module under- `src/core/skill-description.ts` — `oneLineDescription` (frontmatter description, block scalars folded, else the first body paragraph), shared by `skill-catalog.ts`, `bundled.ts` and the bundled source.- `src/core/skills/resolver/hook-lane.ts` + `hook-worker.ts` — the hook lane (`GBRAIN_HOOK_LANE=skill-resolver`, dispatched first in `src/commands/hook.ts` after the `GBRAIN_HOOKS=0` check): async config/stdin/carrier reads on the main thread, ranking in a worker (source: `hook-worker.ts` beside it; compiled binary: the second build entrypoint at `WORKER_SRC_PATH`, so every `bun build --compile` that ships a binary lists it), a 50 ms deadline that exits the process with no output and no commit, the commit (`commitSessionAsync`) on the main thread after delivery, the payload budget (`skills.resolver.lane_payload_chars`, dropped whole as `payload_dropped`), the one-owner rule (first carrier entry whose home has the lane on), the SessionStart compaction reset, the Claude Code project catalog (`claude-code-project-<root hash>`, built by a detached `skills index build`, stamp-limited to once a minute) and `skill-index/logs/lane.jsonl`. Test seams: `GBRAIN_TEST_SKILL_LANE_STALL`, `GBRAIN_TEST_SKILL_LANE_DEADLINE_MS`. Pinned by `test/skill-resolver-hook-lane.test.ts`.- `src/core/setup/skill-resolver-{lane,hook,config,setup}.ts` — `setup <claude-code|codex> --skill-loading resolve|off` and `--remove`: the lane identity leaf (marker `skill-resolver-v1`, which every other lane's ownership and yield test excludes), the Claude Code entries and the Codex group plus its `config.toml` trust, the file-plane keys (`skills.resolver.*`, engine-free in `gbrain config`; an unreadable file is never rewritten), and the build-then-write order (≥1 skill or `skill_resolver_setup_incomplete`). Pinned by `test/setup-skill-resolver.test.ts`.+- `src/core/setup/openclaw-skill-plugin.ts` + `openclaw-skill-plugin-code.ts` — `setup openclaw --skill-loading resolve|shadow|off`: the separate `gbrain-skill-resolver` OpenClaw plugin. Builds one `openclaw-<agent>` catalog per agent, writes the content-addressed library (`~/.gbrain/lib/<sha256>.mjs`), the 0600 state file `openclaw-skill-resolver.json` (per agent: mode, catalog, top_k 3, floor `description`, live_fraction, pins route, pinned block, owner senders; `skills.resolver.per_harness.openclaw` then the global keys), the generated loader and worker (Node worker thread, 50 ms deadline, resolve then commit/discard, library uid/mode/sha checks, stuck-worker restart, daily `skill-index/logs/openclaw-<date>.jsonl`), and runs the openclaw CLI only to install, enable, allow and inspect; a mode or pin change rewrites only the state. A partial install is `skill_resolver_plugin_not_installed` (exit 3). Pinned by `test/openclaw-skill-plugin.test.ts`.+- `src/core/setup/skill-pins.ts` — operator pins (`skills.resolver.pins.<catalog>` in config.json, 64 per catalog, 100-character lines, 600-token block, unknown names left out); `gbrain skills pin add|remove|list` in `src/commands/skill-resolver.ts`.+- `src/commands/doctor/checks/skill-resolver-openclaw.ts` — the OpenClaw part of doctor `skill_resolver`: plugin registration, library hash, per-agent catalog freshness and pins, and 24 hours of plugin logs (outcomes, error codes, reads of suggested skills, the deadline-miss rate; warns above 5% over at least 20 turns).- `src/commands/doctor/checks/skill-resolver.ts` — doctor `skill_resolver` (emitted by the `harness_wiring` entry, whose details carry the same view): hook state, each catalog's content-tier freshness, recent lane outcomes and error codes; silent when nothing of the resolver exists.- `src/commands/skill-resolver.ts` — the CLI (`src/cli/commands/skill-resolver.ts` dispatches; `src/cli/command-route.ts` routes only `skills index` and `skills resolve` here, so plain `gbrain skills` stays `list_skills`). Exit 0, 1 (runtime error), 0 with `--fail-open`, 2 (usage); commits a session turn only after stdout is written. Pinned by `test/skill-resolver-cli.test.ts` and `test/skill-resolver-guide.test.ts`.- `scripts/bench-skill-resolver.ts` — the latency bars (cold turn p95: 10 ms at 1,000 skills, 40 ms at 7,500), enforced by `.github/workflows/skill-resolver-bench.yml` on a 2-vCPU runner.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex e963974813..03bd3d9db4 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -4658,6 +4658,26 @@ More: [docs/guides/skill-resolver.md#skill_resolver_config_invalid](../../docs/gMore: [docs/guides/skill-resolver.md#skill_resolver_config_unreadable](../../docs/guides/skill-resolver.md#skill_resolver_config_unreadable)+### skill_resolver_host_load_cut++<a id="skill_resolver_host_load_cut"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| OpenClaw lists fewer skills than the agent's skill directories hold, so some suggestions name skills OpenClaw dropped at load (skills.limits.maxCandidatesPerRoot) and skills_read cannot open them. | The request itself was wrong or no longer matches the brain; nothing was changed. | Raise skills.limits.maxCandidatesPerRoot in openclaw.json, or split the skill root. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_host_load_cut](../../docs/guides/skill-resolver.md#skill_resolver_host_load_cut)++### skill_resolver_host_not_local++<a id="skill_resolver_host_not_local"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver plugin runs inside the gateway and needs this gbrain home, library and bin on the same machine, but this machine has no openclaw and no OpenClaw state directory. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run gbrain setup openclaw --skill-loading resolve on the OpenClaw host itself. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_host_not_local](../../docs/guides/skill-resolver.md#skill_resolver_host_not_local)+### skill_resolver_internal<a id="skill_resolver_internal"></a>@@ -4668,6 +4688,66 @@ More: [docs/guides/skill-resolver.md#skill_resolver_config_unreadable](../../docMore: [docs/guides/skill-resolver.md#skill_resolver_internal](../../docs/guides/skill-resolver.md#skill_resolver_internal)+### skill_resolver_library_mismatch++<a id="skill_resolver_library_mismatch"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver library file is outside the gbrain lib directory, not owned by the gateway user, writable by others, or does not hash to the recorded sha256, so the plugin refused to load it. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run gbrain setup openclaw --skills-index-only to rewrite the library; check who else writes the gbrain home. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_library_mismatch](../../docs/guides/skill-resolver.md#skill_resolver_library_mismatch)++### skill_resolver_library_missing++<a id="skill_resolver_library_missing"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver plugin found no library file for the sha256 its state names, so turns proceed without suggestions. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run gbrain setup openclaw --skills-index-only to rebuild the library and state. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_library_missing](../../docs/guides/skill-resolver.md#skill_resolver_library_missing)++### skill_resolver_library_skew++<a id="skill_resolver_library_skew"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The installed gbrain CLI is a different version from the library the OpenClaw plugin runs, and a refresh did not bring them in step, so the plugin keeps the last good library and stops retrying for a day. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run gbrain setup openclaw --skills-index-only and read its error. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_library_skew](../../docs/guides/skill-resolver.md#skill_resolver_library_skew)++### skill_resolver_pin_unknown++<a id="skill_resolver_pin_unknown"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A pinned skill is not in the catalog it is pinned to, so it is left out of the pinned block (an unchecked name never reaches the model). | The request itself was wrong or no longer matches the brain; nothing was changed. | Check the name with gbrain skills pin list --catalog <c>, then remove or correct the pin. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_pin_unknown](../../docs/guides/skill-resolver.md#skill_resolver_pin_unknown)++### skill_resolver_plugin_not_installed++<a id="skill_resolver_plugin_not_installed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain setup openclaw wrote the skill-resolver plugin, but OpenClaw has not installed or loaded it: no openclaw on PATH, an openclaw command failed, or plugins inspect does not show it loaded. | A partial install injects nothing, so setup never reports it as success; the files and the state are kept so the remaining commands finish it. | Run the remaining openclaw commands the message names on the OpenClaw host, restart the gateway, then gbrain doctor --only skill_resolver. | user | `repeat the read that failed` | 3 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_plugin_not_installed](../../docs/guides/skill-resolver.md#skill_resolver_plugin_not_installed)++### skill_resolver_selftest_failed++<a id="skill_resolver_selftest_failed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver plugin is installed, but one turn through it under Node did not resolve (the library would not load or the worker did not answer). | The request itself was wrong or no longer matches the brain; nothing was changed. | Read the code in the message (a library or worker code), fix it, then run gbrain setup openclaw --skill-loading resolve again. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_selftest_failed](../../docs/guides/skill-resolver.md#skill_resolver_selftest_failed)+### skill_resolver_setup_incomplete<a id="skill_resolver_setup_incomplete"></a>@@ -4678,6 +4758,46 @@ More: [docs/guides/skill-resolver.md#skill_resolver_internal](../../docs/guides/More: [docs/guides/skill-resolver.md#skill_resolver_setup_incomplete](../../docs/guides/skill-resolver.md#skill_resolver_setup_incomplete)+### skill_resolver_state_missing++<a id="skill_resolver_state_missing"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver state file has no entry for this agent, so the self-test had nothing to run. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run gbrain setup openclaw --skill-loading resolve --agent <id>. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_state_missing](../../docs/guides/skill-resolver.md#skill_resolver_state_missing)++### skill_resolver_worker_crash++<a id="skill_resolver_worker_crash"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver worker thread could not start or crashed; turns proceed without suggestions and it restarts with backoff. | The server failed; this is not a caller mistake. | Run gbrain doctor --only skill_resolver; report it if it repeats. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/skill-resolver.md#skill_resolver_worker_crash](../../docs/guides/skill-resolver.md#skill_resolver_worker_crash)++### skill_resolver_worker_stuck++<a id="skill_resolver_worker_stuck"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver worker missed the turn deadline three times in a row, so it was restarted with backoff. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Check the deadline-miss rate with gbrain doctor --only skill_resolver; a loaded host misses more often. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/skill-resolver.md#skill_resolver_worker_stuck](../../docs/guides/skill-resolver.md#skill_resolver_worker_stuck)++### skill_resolver_worker_unavailable++<a id="skill_resolver_worker_unavailable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The OpenClaw skill-resolver worker is restarting after a crash or a stall, so this turn proceeded without suggestions. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Nothing to do if it is rare; gbrain doctor --only skill_resolver shows the rate. | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/skill-resolver.md#skill_resolver_worker_unavailable](../../docs/guides/skill-resolver.md#skill_resolver_worker_unavailable)+### skill_retention_capacity<a id="skill_retention_capacity"></a>diff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex 85d112c029..1bc0c2d57c 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -215,7 +215,7 @@ gbrain. MCP `get_skill` is unchanged.| | ||---|---|-| Select | `--skill-loading off\|spring` on `gbrain setup <harness>` (`resolve` on `setup claude-code\|codex` turns on the per-turn skill resolver instead: [skill-resolver guide](skill-resolver.md#hook-lane-claude-code-and-codex)), `gbrain connect --install`, `gbrain connect --harness … --install` and `gbrain bootstrap harness`; or `GBRAIN_SKILL_LOADING`. Flag, then env, then the recorded choice, then `off`. |+| Select | `--skill-loading off\|spring` on `gbrain setup <harness>` (`resolve` on `setup claude-code\|codex` turns on the per-turn skill resolver instead: [skill-resolver guide](skill-resolver.md#hook-lane-claude-code-and-codex); on `setup openclaw`, `resolve\|shadow` installs the [skill-resolver plugin](skill-resolver.md#openclaw-plugin)), `gbrain connect --install`, `gbrain connect --harness … --install` and `gbrain bootstrap harness`; or `GBRAIN_SKILL_LOADING`. Flag, then env, then the recorded choice, then `off`. || Default | `off`: no index is written, and `off` removes one an earlier run wrote. || Which skills | Host installs (`setup`, `bootstrap harness`) list all bundled skills; hosted and thin-client connections leave out the host-maintenance ones. || Opt out | `--skill-loading off`; `--no-instructions` removes both blocks; `--remove` takes both out and deletes a file only gbrain created once nothing else is in it. On Codex, `--skill-loading off`, `--no-instructions` and `GBRAIN_SKILL_LOADING=off` also strip an index gbrain recorded in the other global instruction file of the same `CODEX_HOME` (`AGENTS.md` or `AGENTS.override.md`) and print it as a second skills line (`paired` in `--json`, in `--dry-run` too), so the index cannot return when the override file goes. |diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.mdindex be7d310e12..517defb0e5 100644--- a/docs/guides/skill-resolver.md+++ b/docs/guides/skill-resolver.md@@ -9,8 +9,8 @@ model.- **Off by default.** Nothing changes until you build a catalog and wire aharness to call `gbrain skills resolve`, or turn on the hook lane with- `gbrain setup <claude-code|codex> --skill-loading resolve`. Setup writes- nothing for it otherwise.+ `gbrain setup <claude-code|codex> --skill-loading resolve` (OpenClaw: the+ plugin below). Setup writes nothing for it otherwise.- **Local and deterministic.** Word matching (BM25F) over the catalog's names,descriptions, triggers, routing rows and the first 4 KB of each body. Nonetwork, no model, no clock, no randomness on the turn path.@@ -114,6 +114,84 @@ Compiled binaries carry the lane's worker as a second entrypoint(`bun build --compile src/cli.ts src/core/skills/resolver/hook-worker.ts`); abinary built without it delivers nothing and logs `skill_resolver_internal`.+## OpenClaw plugin++OpenClaw runs its turns inside one long-lived gateway, so a per-turn CLI call+is too slow there. `gbrain setup openclaw --skill-loading resolve --gbrain-bin <abs path>`+installs a separate plugin, `gbrain-skill-resolver`, that ranks inside the+gateway's Node process instead:++1. It builds one catalog per agent, `openclaw-<agent>`, from the skill+ directories OpenClaw loads for that agent, and writes the Node library to+ `~/.gbrain/lib/<sha256>.mjs`.+2. It writes the plugin to `<openclaw state dir>/gbrain/gbrain-skill-resolver`+ and its state to `~/.gbrain/openclaw-skill-resolver.json` (mode 0600: per+ agent the mode, catalog, top_k, floor, pinned block and rollout knobs).+3. It runs `openclaw plugins install --link`, `plugins enable` and+ `config set ...hooks.allowConversationAccess true`, then+ `plugins inspect` and one self-test turn under Node. Anything short of a+ loaded plugin exits 3 with `skill_resolver_plugin_not_installed` and the+ commands still to run; it never reports a partial install as done.++The plugin never adds to or edits OpenClaw's own skill list. On each real user+turn (`before_prompt_build`; inter-session and other internal turns are+skipped) it puts up to 3 suggestions with at least a description match in+`appendContext`, and the pinned block in `appendSystemContext`. Ranking runs+in a worker thread with a 50 ms deadline: a miss injects nothing, commits+nothing and is logged as `timeout`; three misses in a row restart the worker.+A retried turn (same message id) gets the same block and commits once. It+loads the library only from `~/.gbrain/lib`, owned by the gateway's user, not+writable by others and matching the recorded sha256.++Flipping modes or knobs only rewrites the state file, which the plugin reads+on its next turn, so no OpenClaw command runs and the gateway does not reload:++- `--skill-loading shadow`: rank and log what would have been suggested+ (`would_suggest`), inject nothing. Use it to measure before going live.+- `--agent <id>` (repeatable) or `--all-agents`: which agents; otherwise+ the agents already on, else `main`.+- `--live-fraction <0-1>`: the share of sessions that see suggestions; the+ rest are logged as the control arm.+- `--pins-route system|first_turn`: pins every turn in the system context+ (default), or in the turn context on a session's first turn and after+ compaction.+- `--owner-sender <id>` (repeatable): only turns from these senders get+ suggestions; others get the pins only.+- `--skill-loading off`: uninstalls the plugin and removes its files and+ state. Pins stay in config.json.++`skills.resolver.per_harness.openclaw.{top_k,min_match}` overrides the+defaults (3 and `description`); the global `skills.resolver.top_k` and+`min_match` apply when it is unset.++Each turn appends one line (agent, outcome, duration, error code, arm,+suggested ids; never turn text) to+`skill-index/logs/openclaw-<date>.jsonl`, and a `read` line when the model+opens a skill, marked with whether it was suggested. `gbrain doctor --only+skill_resolver` reports the plugin, the library, each agent's catalog and pins+and, over the last 24 hours, the turns, outcomes, how many reads were of+suggested skills and the deadline-miss rate. Above 5% over at least 20 turns+it warns with `skill_resolve_timeout`; keep a rollout in shadow until the rate+is under that on the real host.++## Pinned skills++Pins are the operator's always-on skills for one catalog. gbrain ships none,+and a catalog with no pins gets no pinned block.++```bash+gbrain skills pin add deploy-example --catalog openclaw-main --line "Before any production deploy"+gbrain skills pin list --catalog openclaw-main+gbrain skills pin remove deploy-example --catalog openclaw-main+```++A pin must name a skill in that catalog (`skill_resolver_pin_unknown`+otherwise), its line is at most 100 characters with no `<` or `>`, a catalog+holds at most 64 pins, and the rendered block is capped at 600 tokens (pins+past it are listed as cut). A pinned skill is never also suggested. Pins live+in config.json under `skills.resolver.pins.<catalog>`, so turning the resolver+off keeps them; an OpenClaw agent uses a change from its next turn.+## The contract (schema_version 1)The JSON Schemas are checked in under `docs/schemas/`:@@ -353,3 +431,74 @@ No message: stdin was a terminal or empty, or neither `--text` norThe turn input is not a valid JSON object for the turn-input schema (anunknown field, `top_k` outside 1-8, a bad session id). Exit 2.++### skill_resolver_plugin_not_installed++`gbrain setup openclaw` wrote the plugin and its state, but OpenClaw has not+loaded it: no `openclaw` on PATH, an `openclaw` command failed (named in the+message), or `plugins inspect` does not show it loaded. Exit 3. Run the+commands the message lists on the OpenClaw host, restart the gateway, then+`gbrain doctor --only skill_resolver`.++### skill_resolver_host_not_local++The plugin runs inside the gateway and needs this gbrain home, library and+binary on the same machine, but this machine has neither `openclaw` nor an+OpenClaw state directory. Run setup on the OpenClaw host.++### skill_resolver_selftest_failed++The plugin is installed, but one turn through it under Node did not resolve.+The message carries the library or worker code; fix that and run setup again.++### skill_resolver_pin_unknown++A pin names a skill that is not in its catalog. `pin add` refuses and writes+nothing; an existing pin whose skill disappeared is left out of the block.+Check the id with `gbrain skills pin list --catalog <c>`.++### skill_resolver_library_missing++No `~/.gbrain/lib/<sha256>.mjs` for the sha256 the plugin state names, so+turns proceed without suggestions. Run `gbrain setup openclaw --skills-index-only`.++### skill_resolver_library_mismatch++The library file is outside `~/.gbrain/lib`, not owned by the gateway's user,+writable by group or others, or does not hash to the recorded sha256, so the+plugin refused it. Run `gbrain setup openclaw --skills-index-only` and check+what else writes the gbrain home.++### skill_resolver_library_skew++The installed gbrain is a different version from the library the plugin runs+and a refresh did not fix it; the plugin keeps the last good library and stops+retrying for a day. Run `gbrain setup openclaw --skills-index-only` and read+its error.++### skill_resolver_worker_crash++The plugin's worker thread could not start or crashed. Turns proceed without+suggestions and it restarts with backoff. Report it if it repeats.++### skill_resolver_worker_stuck++The worker missed the deadline three turns in a row and was restarted. A+loaded host misses more often; `gbrain doctor --only skill_resolver` shows the+miss rate.++### skill_resolver_worker_unavailable++The worker is restarting after a crash or a stall, so this turn got no+suggestions. Nothing to do when it is rare.++### skill_resolver_state_missing++The plugin state has no entry for this agent, so the self-test had nothing to+run. Run `gbrain setup openclaw --skill-loading resolve --agent <id>`.++### skill_resolver_host_load_cut++OpenClaw lists fewer skills than the agent's skill directories hold (it caps+each root with `skills.limits.maxCandidatesPerRoot`), so a suggestion can name+a skill `skills_read` cannot open. Raise that limit or split the root.diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsvindex f73c671661..eb754cadf4 100644--- a/scripts/core-world-reads-baseline.tsv+++ b/scripts/core-world-reads-baseline.tsv@@ -1184,3 +1184,7 @@ src/core/skills/resolver/hook-lane.ts fs_import 1 GBRA-377 PR B skill-resolver hsrc/core/skills/resolver/hook-lane.ts process_env 2 GBRA-377 PR B skill-resolver hook lane: runs in the hook process with no brain or engine, reading config.json, harness settings and the skill index; env carries GBRAIN_HOME and its test seams; it spawns the detached catalog build; stayssrc/core/skills/resolver/hook-lane.ts spawn_import 1 GBRA-377 PR B skill-resolver hook lane: runs in the hook process with no brain or engine, reading config.json, harness settings and the skill index; env carries GBRAIN_HOME and its test seams; it spawns the detached catalog build; stayssrc/core/skills/resolver/hook-lane.ts process_global 1 GBRA-377 PR B skill-resolver hook lane: at its 50 ms deadline the hook process exits at once without waiting on the abandoned worker (the lane is the whole process); stays+src/core/setup/openclaw-skill-plugin.ts fs_import 1 GBRA-435 OpenClaw skill-resolver plugin: setup writes the plugin files, its state and the library under GBRAIN_HOME and reads openclaw.json directly (no brain or engine is opened); stays+src/core/setup/openclaw-skill-plugin.ts process_env 3 GBRA-435 OpenClaw skill-resolver plugin: PATH to find openclaw and node, and the env handed to the openclaw child and the self-test; stays+src/core/setup/openclaw-skill-plugin.ts spawn_import 1 GBRA-435 OpenClaw skill-resolver plugin: setup runs the openclaw CLI (install, enable, allow, inspect) and the Node self-test; stays+src/core/setup/skill-pins.ts fs_import 1 GBRA-435 skill pins: reads a catalog's receipt under GBRAIN_HOME/skill-index to check pin names (no brain or engine is opened); staysdiff --git a/src/cli/command-route.ts b/src/cli/command-route.tsindex 87e771f3ab..c4303a2617 100644--- a/src/cli/command-route.ts+++ b/src/cli/command-route.ts@@ -6,12 +6,12 @@* command. The `ask` alias stays inline in main.ts, where the dispatch-shape* analyzer reads it.*- * GBRA-377: `skills index ...`, `skills resolve ...` and `skills library` route to the+ * GBRA-377: `skills index ...`, `skills resolve ...`, `skills library` and `skills pin` route to the* engine-free skill resolver (`skill-resolver`) before help, prewarming or* any engine work; plain `skills` stays the `list_skills` listing.*/export function routeCommand(command: string, subArgs: string[]): { command: string; subArgs: string[] } {- if (command === 'skills' && (subArgs[0] === 'index' || subArgs[0] === 'resolve' || subArgs[0] === 'library')) return { command: 'skill-resolver', subArgs };+ if (command === 'skills' && (subArgs[0] === 'index' || subArgs[0] === 'resolve' || subArgs[0] === 'library' || subArgs[0] === 'pin')) return { command: 'skill-resolver', subArgs };if (command !== 'search') return { command, subArgs };const at = subArgs.indexOf('--exact');const end = subArgs.indexOf('--');diff --git a/src/commands/doctor/checks/skill-resolver-openclaw.ts b/src/commands/doctor/checks/skill-resolver-openclaw.tsnew file mode 100644index 0000000000..6f914040e2--- /dev/null+++ b/src/commands/doctor/checks/skill-resolver-openclaw.ts@@ -0,0 +1,96 @@+/**+ * The OpenClaw half of doctor's `skill_resolver` check: the+ * gbrain-skill-resolver plugin (src/core/setup/openclaw-skill-plugin.ts).+ * Per agent it reports the mode, the catalog's freshness and the pinned+ * count; for the plugin, whether its files exist, OpenClaw's config loads it,+ * and the library the state names is present with that sha256; and from the+ * last 24 hours of its daily logs, the turns, outcomes, error codes, the+ * deadline-miss rate and how often a suggested skill was then read.+ *+ * Read-only. Null when nothing of the plugin exists.+ */+import { createHash } from 'node:crypto';+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { catalogStatus } from '../../../core/skills/resolver/build.ts';+import { logsDir } from '../../../core/skills/resolver/paths.ts';+import { openclawSkillLibDir, openclawSkillPluginDir, openclawSkillPluginRegistered, readOpenclawSkillState } from '../../../core/setup/openclaw-skill-plugin.ts';++const LOG_WINDOW_MS = 24 * 3600 * 1000;+const LOG_READ_CAP = 4 * 1024 * 1024;+/** A deadline-miss rate above this blocks go-live (the plan's bar) and warns here. */+export const OPENCLAW_MISS_RATE_WARN = 0.05;++export interface OpenclawSkillView {+ plugin: 'installed' | 'files_only' | 'absent';+ library: 'ok' | 'missing' | 'mismatch' | 'none';+ gbrain_version: string | null;+ agents: Array<{ id: string; mode: string; catalog: string; fresh: boolean | null; stale_reason: string | null; skills: number; pins: number }>;+ recent: { turns: number; outcomes: Record<string, number>; errors: Record<string, number>; deadline_misses: number; miss_rate: number | null; reads: number; reads_of_suggested: number };+}++function recentOpenclaw(home: string, now: number): OpenclawSkillView['recent'] {+ const recent: OpenclawSkillView['recent'] = { turns: 0, outcomes: {}, errors: {}, deadline_misses: 0, miss_rate: null, reads: 0, reads_of_suggested: 0 };+ const dir = logsDir(home);+ let files: string[] = [];+ try { files = readdirSync(dir).filter((f) => /^openclaw-\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().slice(-2); } catch { return recent; }+ let resolved = 0;+ for (const f of files) {+ let text = '';+ try {+ const p = join(dir, f);+ text = readFileSync(p, 'utf8');+ if (statSync(p).size > LOG_READ_CAP) text = text.slice(-LOG_READ_CAP);+ } catch { continue; }+ for (const line of text.split('\n')) {+ if (!line) continue;+ let j: { at?: unknown; outcome?: unknown; code?: unknown; suggested?: unknown };+ try { j = JSON.parse(line); } catch { continue; }+ if (typeof j.outcome !== 'string' || typeof j.at !== 'string' || now - Date.parse(j.at) > LOG_WINDOW_MS) continue;+ if (j.outcome === 'read') { recent.reads++; if (j.suggested === true) recent.reads_of_suggested++; continue; }+ if (['rebuilt', 'compaction'].includes(j.outcome)) continue;+ recent.turns++;+ recent.outcomes[j.outcome] = (recent.outcomes[j.outcome] ?? 0) + 1;+ if (typeof j.code === 'string') recent.errors[j.code] = (recent.errors[j.code] ?? 0) + 1;+ if (j.outcome === 'timeout') recent.deadline_misses++;+ if (!j.outcome.startsWith('skipped_') && j.outcome !== 'retry') resolved++;+ }+ }+ recent.miss_rate = resolved ? recent.deadline_misses / resolved : null;+ return recent;+}++export async function openclawSkillView(home: string, now = Date.now()): Promise<OpenclawSkillView | null> {+ const state = readOpenclawSkillState(home);+ const dir = openclawSkillPluginDir();+ const files = existsSync(join(dir, 'index.js'));+ if (!state && !files) return null;+ let library: OpenclawSkillView['library'] = 'none';+ if (state) {+ const p = join(openclawSkillLibDir(home), `${state.library_sha256}.mjs`);+ try { library = createHash('sha256').update(readFileSync(p)).digest('hex') === state.library_sha256 ? 'ok' : 'mismatch'; } catch { library = 'missing'; }+ }+ const agents: OpenclawSkillView['agents'] = [];+ for (const [id, a] of Object.entries(state?.agents ?? {})) {+ const s = existsSync(join(home, 'skill-index', a.catalog, 'receipt.json')) ? await catalogStatus(a.catalog, { home }) : null;+ agents.push({ id, mode: a.mode, catalog: a.catalog, fresh: s ? s.fresh : null, stale_reason: s?.stale_reason ?? (s ? null : 'missing'), skills: s?.receipt?.skill_count ?? 0, pins: a.pinned_ids.length });+ }+ return { plugin: files ? (openclawSkillPluginRegistered(dir) ? 'installed' : 'files_only') : 'absent', library, gbrain_version: state?.gbrain_version ?? null, agents, recent: recentOpenclaw(home, now) };+}++/** One line for doctor's message, and the problem to warn about (null when healthy). */+export function describeOpenclawSkill(v: OpenclawSkillView): { line: string; problem: { code: string; what: string } | null } {+ const on = v.agents.filter((a) => a.mode !== 'off');+ const agents = v.agents.map((a) => `${a.id} ${a.mode}, ${a.skills} skills, ${a.fresh === null ? 'no catalog' : a.fresh ? 'fresh' : `stale (${a.stale_reason})`}, ${a.pins} pinned`).join('; ');+ const r = v.recent;+ const miss = r.miss_rate === null ? '' : `, deadline misses ${(r.miss_rate * 100).toFixed(1)}%`;+ const reads = r.reads ? `, ${r.reads_of_suggested}/${r.reads} skill reads were suggested` : '';+ const errs = Object.entries(r.errors).map(([c, n]) => `${c} x${n}`).join(', ');+ const line = `openclaw plugin ${v.plugin}, library ${v.library}; ${agents || 'no agent'}${r.turns ? `; last 24h ${r.turns} turns${miss}${reads}${errs ? `, ${errs}` : ''}` : ''}`;+ let problem: { code: string; what: string } | null = null;+ if (on.length && v.plugin !== 'installed') problem = { code: 'skill_resolver_plugin_not_installed', what: v.plugin === 'absent' ? 'the plugin files are missing' : "OpenClaw's config does not load, enable and allow the plugin" };+ else if (on.length && v.library !== 'ok') problem = { code: v.library === 'mismatch' ? 'skill_resolver_library_mismatch' : 'skill_resolver_library_missing', what: `the library the state names is ${v.library}` };+ else if (on.some((a) => a.fresh === null)) problem = { code: 'skill_index_missing', what: 'an agent has no catalog' };+ else if (r.miss_rate !== null && r.miss_rate > OPENCLAW_MISS_RATE_WARN && r.turns >= 20) problem = { code: 'skill_resolve_timeout', what: `${(r.miss_rate * 100).toFixed(1)}% of turns missed the 50 ms deadline and got no suggestions` };+ return { line, problem };+}diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.tsindex 7707dc7ed9..a8b6933d61 100644--- a/src/commands/doctor/checks/skill-resolver.ts+++ b/src/commands/doctor/checks/skill-resolver.ts@@ -20,6 +20,7 @@ import { logsDir } from '../../../core/skills/resolver/paths.ts';import { LANE_LOG_FILE, projectCatalogPrefix, userCatalogName, type LaneHarness } from '../../../core/skills/resolver/hook-lane.ts';import { readResolverConfig, resolverHarnesses } from '../../../core/setup/skill-resolver-config.ts';import { inspectSkillResolverHook } from '../../../core/setup/skill-resolver-hook.ts';+import { describeOpenclawSkill, openclawSkillView, type OpenclawSkillView } from './skill-resolver-openclaw.ts';const name = 'skill_resolver';const HARNESSES: LaneHarness[] = ['claude-code', 'codex'];@@ -33,6 +34,8 @@ export interface SkillResolverView {config: 'ok' | 'absent' | 'unreadable';harnesses: SkillResolverHarnessView[];recent: { turns: number; outcomes: Record<string, number>; errors: Record<string, number> };+ /** The OpenClaw plugin (gbrain setup openclaw --skill-loading resolve|shadow), when any of it exists. */+ openclaw?: OpenclawSkillView;}function recentLane(home: string): SkillResolverView['recent'] | null {@@ -77,8 +80,9 @@ export async function skillResolverView(home = configDir()): Promise<SkillResolv}harnesses.push({ harness, on: on.includes(harness), hook, catalogs: views });}- if (harnesses.length === 0 && !recent && !(cfg.state === 'ok' && on.length)) return null;- return { config: cfg.state, harnesses, recent: recent ?? { turns: 0, outcomes: {}, errors: {} } };+ const openclaw = await openclawSkillView(home);+ if (harnesses.length === 0 && !recent && !(cfg.state === 'ok' && on.length) && !openclaw) return null;+ return { config: cfg.state, harnesses, recent: recent ?? { turns: 0, outcomes: {}, errors: {} }, ...(openclaw ? { openclaw } : {}) };}const setupArgv = (harness: string) => ['gbrain', 'setup', harness, '--skill-loading', 'resolve'];@@ -92,7 +96,8 @@ export function describeSkillResolver(v: SkillResolverView): string {return `${h.harness} ${h.on ? 'on' : 'off'}, hook ${h.hook}, ${user?.skills ?? 0} skills, ${fresh}`;});const errs = Object.entries(v.recent.errors).map(([c, n]) => `${c} x${n}`).join(', ');- return `Skill resolver: ${parts.join('; ') || 'no harness on'}${v.recent.turns ? `; last ${v.recent.turns} turns${errs ? ` with ${errs}` : ' without errors'}` : ''}.`;+ const oc = v.openclaw ? `; ${describeOpenclawSkill(v.openclaw).line}` : '';+ return `Skill resolver: ${parts.join('; ') || (v.openclaw ? 'no hook harness on' : 'no harness on')}${v.recent.turns ? `; last ${v.recent.turns} turns${errs ? ` with ${errs}` : ' without errors'}` : ''}${oc}.`;}export function skillResolverCheck(v: SkillResolverView | null): Check | null {@@ -111,5 +116,11 @@ export function skillResolverCheck(v: SkillResolverView | null): Check | null {fix: { argv: setupArgv(broken.harness), consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(name),why: `Rebuilds the ${broken.harness} user catalog and rewrites only the skill-resolver hook entry; --skill-loading off removes it instead.` } };}+ const oc = v.openclaw ? describeOpenclawSkill(v.openclaw).problem : null;+ if (oc) {+ return { name, status: 'warn', message: `${describeSkillResolver(v)} OpenClaw: ${oc.what}.`, details: { ...details, code: oc.code },+ fix: { argv: ['gbrain', 'setup', 'openclaw', '--skills-index-only'], consent: [], actor: 'agent', requires_exclusive: false, verify: doctorVerify(name), docs: `docs/guides/skill-resolver.md#${oc.code}`,+ why: 'Rebuilds the OpenClaw catalogs, the library and the plugin state without running any OpenClaw command; gbrain setup openclaw --skill-loading resolve reinstalls the plugin itself.' } };+ }return { name, status: 'ok', message: describeSkillResolver(v), details };}diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex d09cde155d..7fda09c60c 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -26,6 +26,7 @@ import { realpathSync } from 'node:fs';import { basename, dirname, join, resolve } from 'node:path';import { removeHermesTurnHook, syncHermesTurnHook } from '../core/setup/hermes-turn-hook.ts';import { removeOpenclawTurnPlugin, syncOpenclawTurnPlugin } from '../core/setup/openclaw-turn-plugin.ts';+import { describeOpenclawSkill, readOpenclawSkillState, removeOpenclawSkillPlugin, syncOpenclawSkillPlugin, type OpenclawSkillResult } from '../core/setup/openclaw-skill-plugin.ts';import { hasTurnRuleHook, isTurnRuleHarness, removeTurnRuleHook, syncTurnRuleHook, type TurnHookOutcome, type TurnRuleHarness } from '../core/setup/turn-hook.ts';import { inspectTurnHook, TURN_HOOK_NATIVE_INSPECT, turnHookFix, verifyTurnHook, type TurnHookVerdict } from '../core/setup/turn-hook-check.ts';import { opError, OperationError } from '../core/ops/contract.ts';@@ -36,6 +37,7 @@ import { hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../corimport { writeJsonDocument } from '../core/cli-force-exit.ts';import { configDir, gbrainPath, isThinClient, loadConfig, type GBrainConfig } from '../core/config.ts';import { resolveGbrainBin } from '../core/gbrain-bin.ts';+import { exitCodeForCode } from '../core/error-catalogue.ts';import { isRegistrationSurface, isValidName, REGISTRATION_SURFACE, registrationAdvertise, stdioServeArgv } from '../core/mcp-registration.ts';import { hookLauncherPath } from '../core/setup/hook-launcher.ts';import { readResolverConfig, resolverHarnesses } from '../core/setup/skill-resolver-config.ts';@@ -228,11 +230,15 @@ interface SetupFlags {skillsIndexOnly: boolean;workspace?: string;skillLoading?: SkillLoading;- /** --skill-loading resolve turns the skill-resolver lane on (skill-resolver-setup.ts); off or spring turns it off; unset leaves it as it is. */- skillResolver?: 'on' | 'off';+ /** --skill-loading resolve turns the skill-resolver lane on (skill-resolver-setup.ts); off or spring turns it off; unset leaves it as it is. OpenClaw also takes shadow. */+ skillResolver?: 'on' | 'shadow' | 'off';+ /** OpenClaw: the agents --skill-loading applies to (--agent <id>, repeatable, or --all-agents); unset means the agents already on, else main. */+ agents?: string[] | 'all';+ /** OpenClaw rollout knobs written to the plugin's state (hot, no reload): --live-fraction, --pins-route, --owner-sender. */+ openclawTuning?: { live_fraction?: number; pins_route?: 'system' | 'first_turn'; owner_sender_ids?: string[] };}-const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading']);+const VALUE_FLAGS = new Set(['--surface', '--scope', '--name', '--source', '--gbrain-bin', '--workspace', '--skill-loading', '--agent', '--live-fraction', '--pins-route', '--owner-sender']);function parseFlags(args: string[]): SetupFlags | string {const value = (flag: string): string | undefined => {@@ -254,15 +260,29 @@ function parseFlags(args: string[]): SetupFlags | string {const workspace = value('--workspace');if (workspace !== undefined && !workspace.startsWith('/') && !workspace.startsWith('~')) return '--workspace needs an absolute path';const flagLoading = value('--skill-loading');- if (flagLoading !== undefined && flagLoading !== 'resolve' && !isSkillLoading(flagLoading)) return `unknown --skill-loading '${flagLoading}'; pass off, spring or resolve`;+ if (flagLoading !== undefined && flagLoading !== 'resolve' && flagLoading !== 'shadow' && !isSkillLoading(flagLoading)) return `unknown --skill-loading '${flagLoading}'; pass off, spring, resolve or (openclaw) shadow`;const envLoading = process.env[SKILL_LOADING_ENV]?.trim();if (flagLoading === undefined && envLoading && envLoading !== 'resolve' && !isSkillLoading(envLoading)) return new InvalidSkillLoadingEnv(envLoading).message;- const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex';- if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code and Codex only (claude-code, codex); other harnesses call gbrain skills resolve from their own adapter (docs/guides/skill-resolver.md)';+ const openclaw = positionals[0] === 'openclaw';+ const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex' || openclaw;+ if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code, Codex and OpenClaw (claude-code, codex, openclaw); other harnesses call gbrain skills resolve from their own adapter (docs/guides/skill-resolver.md)';+ if (flagLoading === 'shadow' && !openclaw) return '--skill-loading shadow is for openclaw only (it resolves and logs each turn without showing the model anything)';+ const agentFlags = args.flatMap((a, i) => (a === '--agent' ? [args[i + 1] ?? ''] : []));+ if (agentFlags.some((a) => !/^[\w.@:-]{1,128}$/.test(a))) return '--agent needs an OpenClaw agent id';+ if ((agentFlags.length || args.includes('--all-agents')) && !openclaw) return '--agent and --all-agents are for openclaw only';+ if (agentFlags.length && args.includes('--all-agents')) return 'pass --agent or --all-agents, not both';+ const liveFraction = value('--live-fraction');+ const pinsRoute = value('--pins-route');+ const owners = args.flatMap((a, i) => (a === '--owner-sender' ? [args[i + 1] ?? ''] : []));+ if ((liveFraction !== undefined || pinsRoute !== undefined || owners.length) && !openclaw) return '--live-fraction, --pins-route and --owner-sender are for openclaw only';+ if (liveFraction !== undefined && !(/^(0(\.\d+)?|1(\.0+)?)$/.test(liveFraction))) return '--live-fraction must be a number from 0 to 1 (the share of sessions that see suggestions; the rest are logged as control)';+ if (pinsRoute !== undefined && pinsRoute !== 'system' && pinsRoute !== 'first_turn') return '--pins-route must be system (appendSystemContext, every turn) or first_turn (appendContext on a session\'s first turn and after compaction)';+ if (owners.some((o) => !/^[\x21-\x7e]{1,128}$/.test(o))) return '--owner-sender needs a sender id';+ const openclawTuning = { ...(liveFraction !== undefined ? { live_fraction: Number(liveFraction) } : {}), ...(pinsRoute ? { pins_route: pinsRoute as 'system' | 'first_turn' } : {}), ...(owners.length ? { owner_sender_ids: owners } : {}) };const chosenLoading = flagLoading ?? (envLoading || undefined);- const skillResolver = !resolverHarness || chosenLoading === undefined ? undefined : chosenLoading === 'resolve' ? 'on' as const : 'off' as const;+ const skillResolver = !resolverHarness || chosenLoading === undefined ? undefined : chosenLoading === 'resolve' ? 'on' as const : chosenLoading === 'shadow' ? 'shadow' as const : 'off' as const;// resolve replaces the spring index: the skills block is decided as off, explicitly, so GBRAIN_SKILL_LOADING=resolve is never read as a block mode.- const skillLoading = skillResolver === 'on' ? 'off' : flagLoading;+ const skillLoading = skillResolver === 'on' || skillResolver === 'shadow' ? 'off' : flagLoading;return {harness: positionals[0],dryRun: args.includes('--dry-run'),@@ -282,6 +302,8 @@ function parseFlags(args: string[]): SetupFlags | string {workspace,skillLoading: skillLoading as SkillLoading | undefined,...(skillResolver ? { skillResolver } : {}),+ ...(agentFlags.length ? { agents: agentFlags } : args.includes('--all-agents') ? { agents: 'all' as const } : {}),+ ...(Object.keys(openclawTuning).length ? { openclawTuning } : {}),};}@@ -828,6 +850,34 @@ function resolverRefusal(r: ResolverSetupResult): OperationError {fix: { argv: rerun, consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews every write the resolver setup would make and names the directories it scans; changes nothing.' } });}+/**+ * The OpenClaw skill-resolver plugin for this run: --skill-loading resolve+ * (live) or shadow turns it on for --agent/--all-agents (else the agents+ * already on, else main), off turns those agents off (the plugin leaves when+ * none is on), and with no choice an existing plugin is refreshed. It is+ * independent of the brain-first block. Null when there is nothing to do.+ */+async function openclawSkillFor(flags: SetupFlags, refreshOnly = false): Promise<OpenclawSkillResult | null> {+ const home = configDir();+ const agents = flags.agents ?? null;+ if (flags.skillResolver === 'off' || (flags.remove && flags.skillResolver === undefined)) {+ return removeOpenclawSkillPlugin({ home, agents: Array.isArray(agents) ? agents : null, dryRun: flags.dryRun });+ }+ if (flags.skillResolver === undefined && !readOpenclawSkillState(home)) return null;+ return syncOpenclawSkillPlugin({ mode: flags.skillResolver === 'on' ? 'live' : flags.skillResolver === 'shadow' ? 'shadow' : null, agents, home,+ gbrainBin: flags.gbrainBin ?? resolveGbrainBin() ?? '', gbrainHomeEnv: process.env.GBRAIN_HOME?.trim() || null, dryRun: flags.dryRun, refreshOnly, tuning: flags.openclawTuning });+}++function openclawSkillRefusal(r: OpenclawSkillResult): OperationError {+ const e = r.error!;+ const detail = [e.recovery, ...(e.commands ?? []).map((c) => `still to run: ${c}`)].filter(Boolean).join('\n');+ return opError(e.code, e.message, e.commands?.length ? `Run on the OpenClaw host: ${e.commands.join(' && ')}; then gbrain doctor --only skill_resolver.` : 'Fix the cause named above, then preview with gbrain setup openclaw --skill-loading resolve --dry-run.', {+ docs: `docs/guides/skill-resolver.md#${e.code}`, ...(detail ? { detail } : {}),+ fix: e.argv ? { argv: e.argv, consent: ['persistent_install'], actor: 'user', requires_exclusive: false, why: 'Finishes the OpenClaw install setup could not complete; gbrain doctor --only skill_resolver confirms it.' }+ : { argv: ['gbrain', 'setup', 'openclaw', '--skill-loading', 'resolve', '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews every write the OpenClaw resolver setup would make; changes nothing.' },+ });+}+const instructionsChanged = (o: BrainFirstOutcome | SkillsBlockOutcome | null): boolean => !!o && (o.action === 'write' || o.action === 'remove');const resolverChanged = (r: ResolverSetupResult | null): boolean => !!r && (!!r.error || r.steps.some((s) => s.action === 'write' || s.action === 'remove'));@@ -894,20 +944,23 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>// A 'print' outcome installed nothing and already names the step that does, so it is reported, not verified.const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && !flags.noHooks && process.env.GBRAIN_HOOKS !== '0' && turnHook && turnHook.action !== 'print' && turnHook.action !== 'remove' ? verifyTurnHook(harness, { projectDir }) : null;const resolver = harness === 'claude-code' || harness === 'codex' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;+ const skillPlugin = harness === 'openclaw' ? await openclawSkillFor(flags) : null;const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) || resolver?.error ? 1 : 0;if (out.json) {- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, ...(resolver ? { skill_resolver: resolver } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));- return code;+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, ...(resolver ? { skill_resolver: resolver } : {}), ...(skillPlugin ? { skill_resolver: skillPlugin } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));+ return skillPlugin?.error ? exitCodeForCode(skillPlugin.error.code) : code;}if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));if (turnHook) say(out, ` ${(flags.dryRun && (turnHook.action === 'write' || turnHook.action === 'remove') ? `would ${turnHook.action}` : turnHook.action).padEnd(8)} ${'turn hook'.padEnd(7)} ${turnHook.detail}${'snippet' in turnHook && turnHook.snippet ? `:\n${turnHook.snippet.replace(/^/gm, ' ')}` : ''}${'commands' in turnHook && turnHook.commands ? `:\n${turnHook.commands.map((c) => ` ${c}`).join('\n')}` : ''}${'next' in turnHook && turnHook.next ? `; wire it with: ${turnHook.next}` : ''}`);else if (!off && placed) say(out, ` note ${'turn hook'.padEnd(7)} ${adapter.label} has no per-turn hook gbrain can install; the rule reaches it through ${target.path} only.`);if (skills && skillsOutcomeShown(skills)) say(out, describeSkillsBlockOutcome(skills, flags.dryRun));if (resolver) for (const line of describeResolverSetup(resolver, flags.dryRun)) say(out, line);+ if (skillPlugin) for (const line of describeOpenclawSkill(skillPlugin, flags.dryRun)) say(out, line);if (check?.ok) say(out, ` verify ${'turn hook'.padEnd(7)} ${check.message}`);if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');if (resolver?.error) return refuse(resolverRefusal(resolver), out);+ if (skillPlugin?.error) return refuse(openclawSkillRefusal(skillPlugin), out);if (check && !check.ok) return refuse(turnHookNotLoaded(harness, check, rerun), out);return code;}@@ -920,15 +973,18 @@ async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number>}const outcomes = refreshSkillsIndexes(harness, { mode: flags.skillLoading, launcher: flags.gbrainBin, dryRun: flags.dryRun });const resolver = harness === 'claude-code' || harness === 'codex' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;+ const skillPlugin = harness === 'openclaw' ? await openclawSkillFor(flags, true) : null;const code = outcomes.some((o) => o.action === 'preserve') || resolver?.error ? 1 : 0;if (out.json) {- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, skills_index_only: true, skills: outcomes, ...(resolver ? { skill_resolver: resolver } : {}) }, null, 2)}\n`, (t) => process.stdout.write(t));- return code;+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, skills_index_only: true, skills: outcomes, ...(resolver ? { skill_resolver: resolver } : {}), ...(skillPlugin ? { skill_resolver: skillPlugin } : {}) }, null, 2)}\n`, (t) => process.stdout.write(t));+ return skillPlugin?.error ? exitCodeForCode(skillPlugin.error.code) : code;}- if (outcomes.length === 0 && !resolver) say(out, `No skills index is recorded for ${harness}. Add one with: gbrain setup ${harness} --skill-loading spring`);+ if (outcomes.length === 0 && !resolver && !skillPlugin) say(out, `No skills index is recorded for ${harness}. Add one with: gbrain setup ${harness} --skill-loading spring`);for (const o of outcomes) say(out, describeSkillsBlockOutcome(o, flags.dryRun));if (resolver) for (const line of describeResolverSetup(resolver, flags.dryRun)) say(out, line);+ if (skillPlugin) for (const line of describeOpenclawSkill(skillPlugin, flags.dryRun)) say(out, line);if (resolver?.error) return refuse(resolverRefusal(resolver), out);+ if (skillPlugin?.error) return refuse(openclawSkillRefusal(skillPlugin), out);return code;}diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.tsindex 68266c7477..147fc31cf5 100644--- a/src/commands/skill-resolver.ts+++ b/src/commands/skill-resolver.ts@@ -22,6 +22,10 @@ import {buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex, resolveSkills, resolverHome, sessionStatus,ResolverError, HARNESSES, errorTurnOutput, GBRAIN_VERSION, type BuildInput, type TurnInput,} from '../core/skills/resolver/index.ts';+import { validCatalogName } from '../core/skills/resolver/paths.ts';+import { readResolverConfig } from '../core/setup/skill-resolver-config.ts';+import { catalogSkillIds, pinProblem, PINS_MAX, readPins, renderPinnedBlock, writePins } from '../core/setup/skill-pins.ts';+import { refreshOpenclawPins } from '../core/setup/openclaw-skill-plugin.ts';const HELP_INDEX = `Usage: gbrain skills index <build|status|remove> [options]@@ -72,6 +76,24 @@ and no brain connection is needed.Guide: docs/guides/skill-resolver.md`;+const HELP_PIN = `Usage: gbrain skills pin <add|remove|list> --catalog <name> [options]++The operator's always-on skills for one catalog: rendered as a pinned block the harness+shows on every turn, and never suggested twice. gbrain ships no pins; a catalog with+none gets no pinned block. Pins live in config.json (skills.resolver.pins.<catalog>),+so turning the resolver off keeps them.++ gbrain skills pin add <skill-id> --catalog <name> [--line "<when to use it, 100 chars>"] [--json]+ gbrain skills pin remove <skill-id> --catalog <name> [--json]+ gbrain skills pin list --catalog <name> [--json]++ --catalog <name> the catalog the skill must be in (openclaw-<agent>, claude-code-user, ...)+ --line <text> one trigger-first line shown beside the id (no < or >)++An OpenClaw agent picks up a pin change on its next turn, with no reload.+Guide: docs/guides/skill-resolver.md#pinned-skills+`;+const HELP_LIBRARY = `Usage: gbrain skills library [--out <file.mjs>] [--json]Write the skill resolver library, built from this gbrain's own source, as one@@ -281,10 +303,55 @@ async function runLibrary(args: string[]): Promise<void> {}}+async function runPin(args: string[]): Promise<void> {+ const sub = args[0];+ if (sub !== 'add' && sub !== 'remove' && sub !== 'list') {+ if (sub === undefined || sub === 'help' || sub === '--help' || sub === '-h') { process.stdout.write(HELP_PIN); return; }+ usage(`Unknown subcommand "skills pin ${sub}".`, 'Use gbrain skills pin add, remove or list.');+ }+ const p = parseFlags(args.slice(1), ['--catalog', '--line'], ['--json'], HELP_PIN);+ const json = p.bools.has('--json');+ const catalog = one(p, '--catalog');+ if (!catalog || !validCatalogName(catalog)) usage('--catalog <name> is required (a-z, 0-9, _ and -).', 'Pass the catalog the pin belongs to, e.g. --catalog openclaw-main.');+ const home = resolverHome();+ const read = readResolverConfig(home);+ if (read.state === 'unreadable') exitCliError(opError('skill_resolver_config_unreadable', `${read.path} cannot be read (${read.why}); nothing was written.`, 'Fix or move the config file, then retry.', { docs: 'docs/guides/skill-resolver.md#skill_resolver_config_unreadable' }), CMD, { json });+ let pins = readPins(read, catalog);+ if (sub !== 'list') {+ const name = p.positionals[0];+ if (!name || p.positionals.length > 1) usage(`gbrain skills pin ${sub} takes one skill id.`, `Example: gbrain skills pin ${sub} <skill-id> --catalog ${catalog}`);+ const line = one(p, '--line');+ if (sub === 'add') {+ const problem = pinProblem({ name, ...(line !== undefined ? { line } : {}) });+ if (problem) usage(problem, 'Fix the value and retry.');+ const known = catalogSkillIds(home, catalog);+ if (!known) runtimeFailure(new ResolverError('skill_index_missing', `The catalog "${catalog}" has not been built, so the pin cannot be checked; nothing was written.`, { suggestion: `Build it first (gbrain setup <harness> --skill-loading resolve, or gbrain skills index build --catalog ${catalog} ...).` }), json);+ if (!known.has(name)) exitCliError(opError('skill_resolver_pin_unknown', `"${name}" is not a skill in ${catalog}; nothing was written.`, `Check the id with gbrain skills index status --catalog ${catalog}, then retry.`, { docs: 'docs/guides/skill-resolver.md#skill_resolver_pin_unknown' }), CMD, { json });+ const others = pins.filter((x) => x.name !== name);+ if (others.length >= PINS_MAX) usage(`${catalog} already has ${PINS_MAX} pins.`, 'Remove one first.');+ pins = [...others, { name, ...(line !== undefined ? { line } : {}) }];+ } else {+ if (line !== undefined) usage('--line is for pin add.', 'Drop --line.');+ pins = pins.filter((x) => x.name !== name);+ }+ writePins(read, catalog, pins);+ }+ const rendered = renderPinnedBlock(pins, { harness: catalog.startsWith('openclaw-') ? 'openclaw' : undefined, known: catalogSkillIds(home, catalog) });+ const agents = sub === 'list' ? [] : refreshOpenclawPins(home);+ const doc = { catalog, pins, rendered: rendered.ids, unknown: rendered.unknown, cut: rendered.cut, block_tokens: rendered.tokens, ...(agents.length ? { openclaw_agents_updated: agents } : {}) };+ if (json) { await write(`${JSON.stringify(doc)}\n`); return; }+ await write([+ pins.length ? `${catalog}: ${pins.length} pin(s)` : `${catalog}: no pins`,+ ...pins.map((x) => ` ${x.name}${x.line ? ` — ${x.line}` : ''}${rendered.unknown.includes(x.name) ? ' (not in the catalog: left out, skill_resolver_pin_unknown)' : rendered.cut.includes(x.name) ? ' (over the token cap: left out)' : ''}`),+ agents.length ? `OpenClaw agent(s) ${agents.join(', ')} use the new pins from their next turn.` : '',+ ].filter(Boolean).join('\n') + '\n');+}+export async function runSkillResolver(args: string[]): Promise<void> {const [sub, ...rest] = args;if (sub === 'index') return runIndex(rest);if (sub === 'resolve') return runResolve(rest);if (sub === 'library') return runLibrary(rest);- process.stdout.write(`${HELP_RESOLVE}\n${HELP_INDEX}\n${HELP_LIBRARY}`);+ if (sub === 'pin') return runPin(rest);+ process.stdout.write(`${HELP_RESOLVE}\n${HELP_INDEX}\n${HELP_PIN}\n${HELP_LIBRARY}`);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 2894ef13e8..111a706c04 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--agent', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--base', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--bundled', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-json', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--input-type', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--list-out', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-assume-unchanged', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-optional-locks', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-skip-worktree', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--reset-session', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--routing', '--rules', '--run', '--runtime', '--sample', '--save', '--scan-secrets', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -81,11 +81,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--abandon', '--absolute-git-dir', '--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--approval-out', '--approved', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--attest-sources', '--audit', '--auto', '--auto-additive', '--background', '--base', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--check-downgrade', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--decisions', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--list-out', '--local', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remote', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--scan-secrets', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--squash', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--uninstall', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--agent', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--approval-out', '--approved', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--base', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--bundled', '--by-mention', '--cached', '--catalog', '--catch-up', '--channel', '--check', '--check-downgrade', '--check-only', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--decisions', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-catalog', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--force-schema', '--format', '--fresh', '--from-index', '--from-json', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--input-json', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-assume-unchanged', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-skip-worktree', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--routing', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skill-loading', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--text', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--no-walk', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--untracked-files', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -123,8 +123,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--snooze', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--attest-actor', '--attest-ops', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],- 'skill-resolver': ['--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--from-json', '--harness', '--help', '--input-json', '--json', '--load-hint', '--names-only', '--out', '--previous', '--reset-session', '--routing', '--scope', '--session', '--shadow', '--shadow-log', '--source', '--text', '--top-k'],+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],+ 'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--names-only', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--skill-loading', '--source', '--text', '--top-k'],'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],@@ -134,7 +134,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--absolute-git-dir', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--check-only', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--config', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-bare-repository', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remote', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--untracked-files', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex bf077a3753..1520a51686 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -741,6 +741,18 @@ export const CODES = {skill_resolver_config_invalid: { class: 'caller', summary: 'A skill resolver setting is out of range (skills.resolver.session_token_budget must be 0 or 100-50000) or GBRAIN_HOME is not an absolute path.', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_invalid', suggestion: 'Fix the value in config.json under skills.resolver (default budget 2000), or GBRAIN_HOME.' },skill_resolver_config_unreadable: { class: 'caller', summary: 'config.json exists but cannot be read or parsed, so the skill resolver lane stays silent and setup writes none of its keys (the file is never rewritten).', docs: 'docs/guides/skill-resolver.md#skill_resolver_config_unreadable', suggestion: 'Fix or move <gbrain home>/config.json (it must be a JSON object), then run gbrain doctor --only skill_resolver.', fix: { argv: ['gbrain', 'doctor', '--only', 'skill_resolver', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolver lane state and the config problem; changes nothing.' } },skill_resolver_setup_incomplete: { class: 'caller', summary: 'gbrain setup --skill-loading resolve found no skill to index (or could not build the catalog or wire the hook), so it wrote no config keys and no hook.', docs: 'docs/guides/skill-resolver.md#skill_resolver_setup_incomplete', suggestion: 'Add a skill to one of the scanned directories (the message names them), then run setup again.' },+ skill_resolver_plugin_not_installed: { class: 'caller', exit: 3, actor: 'user', summary: 'gbrain setup openclaw wrote the skill-resolver plugin, but OpenClaw has not installed or loaded it: no openclaw on PATH, an openclaw command failed, or plugins inspect does not show it loaded.', why: 'A partial install injects nothing, so setup never reports it as success; the files and the state are kept so the remaining commands finish it.', docs: 'docs/guides/skill-resolver.md#skill_resolver_plugin_not_installed', suggestion: 'Run the remaining openclaw commands the message names on the OpenClaw host, restart the gateway, then gbrain doctor --only skill_resolver.' },+ skill_resolver_host_not_local: { class: 'caller', summary: 'The OpenClaw skill-resolver plugin runs inside the gateway and needs this gbrain home, library and bin on the same machine, but this machine has no openclaw and no OpenClaw state directory.', docs: 'docs/guides/skill-resolver.md#skill_resolver_host_not_local', suggestion: 'Run gbrain setup openclaw --skill-loading resolve on the OpenClaw host itself.' },+ skill_resolver_selftest_failed: { class: 'caller', summary: 'The OpenClaw skill-resolver plugin is installed, but one turn through it under Node did not resolve (the library would not load or the worker did not answer).', docs: 'docs/guides/skill-resolver.md#skill_resolver_selftest_failed', suggestion: 'Read the code in the message (a library or worker code), fix it, then run gbrain setup openclaw --skill-loading resolve again.' },+ skill_resolver_pin_unknown: { class: 'caller', summary: 'A pinned skill is not in the catalog it is pinned to, so it is left out of the pinned block (an unchecked name never reaches the model).', docs: 'docs/guides/skill-resolver.md#skill_resolver_pin_unknown', suggestion: 'Check the name with gbrain skills pin list --catalog <c>, then remove or correct the pin.' },+ skill_resolver_library_missing: { class: 'caller', summary: 'The OpenClaw skill-resolver plugin found no library file for the sha256 its state names, so turns proceed without suggestions.', docs: 'docs/guides/skill-resolver.md#skill_resolver_library_missing', suggestion: 'Run gbrain setup openclaw --skills-index-only to rebuild the library and state.' },+ skill_resolver_library_mismatch: { class: 'caller', summary: 'The OpenClaw skill-resolver library file is outside the gbrain lib directory, not owned by the gateway user, writable by others, or does not hash to the recorded sha256, so the plugin refused to load it.', docs: 'docs/guides/skill-resolver.md#skill_resolver_library_mismatch', suggestion: 'Run gbrain setup openclaw --skills-index-only to rewrite the library; check who else writes the gbrain home.' },+ skill_resolver_library_skew: { class: 'caller', summary: 'The installed gbrain CLI is a different version from the library the OpenClaw plugin runs, and a refresh did not bring them in step, so the plugin keeps the last good library and stops retrying for a day.', docs: 'docs/guides/skill-resolver.md#skill_resolver_library_skew', suggestion: 'Run gbrain setup openclaw --skills-index-only and read its error.' },+ skill_resolver_worker_crash: { class: 'server', summary: 'The OpenClaw skill-resolver worker thread could not start or crashed; turns proceed without suggestions and it restarts with backoff.', docs: 'docs/guides/skill-resolver.md#skill_resolver_worker_crash', suggestion: 'Run gbrain doctor --only skill_resolver; report it if it repeats.' },+ skill_resolver_worker_stuck: { class: 'retryable', summary: 'The OpenClaw skill-resolver worker missed the turn deadline three times in a row, so it was restarted with backoff.', docs: 'docs/guides/skill-resolver.md#skill_resolver_worker_stuck', suggestion: 'Check the deadline-miss rate with gbrain doctor --only skill_resolver; a loaded host misses more often.' },+ skill_resolver_worker_unavailable: { class: 'retryable', summary: 'The OpenClaw skill-resolver worker is restarting after a crash or a stall, so this turn proceeded without suggestions.', docs: 'docs/guides/skill-resolver.md#skill_resolver_worker_unavailable', suggestion: 'Nothing to do if it is rare; gbrain doctor --only skill_resolver shows the rate.' },+ skill_resolver_state_missing: { class: 'caller', summary: 'The OpenClaw skill-resolver state file has no entry for this agent, so the self-test had nothing to run.', docs: 'docs/guides/skill-resolver.md#skill_resolver_state_missing', suggestion: 'Run gbrain setup openclaw --skill-loading resolve --agent <id>.' },+ skill_resolver_host_load_cut: { class: 'caller', summary: 'OpenClaw lists fewer skills than the agent\'s skill directories hold, so some suggestions name skills OpenClaw dropped at load (skills.limits.maxCandidatesPerRoot) and skills_read cannot open them.', docs: 'docs/guides/skill-resolver.md#skill_resolver_host_load_cut', suggestion: 'Raise skills.limits.maxCandidatesPerRoot in openclaw.json, or split the skill root.' },skill_resolver_internal: { class: 'server', summary: 'The skill resolver failed unexpectedly; a scrubbed trace (no turn text) was written under skill-index/logs/.', docs: 'docs/guides/skill-resolver.md#skill_resolver_internal', suggestion: 'Run gbrain skills index status and report the trace if it repeats.', fix: { argv: ['gbrain', 'skills', 'index', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows each catalog and its last build error; changes nothing.' } },skill_source_invalid: { class: 'caller', exit: 2, summary: 'The --from-json catalog or --routing file is not valid (not JSON, a malformed entry, over 10,000 skills or 8 MB, or a routing file over 1 MB), so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_invalid', suggestion: 'Pass a JSON array of {id, name, description, triggers?, routing?, body?, path?, eligible?} objects.' },skill_source_unreadable: { class: 'caller', summary: 'A --dir or --routing path (or, for `gbrain skills library`, gbrain\'s own source in a compiled binary) does not exist or cannot be read, so nothing was built.', docs: 'docs/guides/skill-resolver.md#skill_source_unreadable', suggestion: 'Pass an existing directory (or file) you can read; for the Node library from a compiled binary, download the release asset.' },diff --git a/src/core/setup/openclaw-skill-plugin-code.ts b/src/core/setup/openclaw-skill-plugin-code.tsnew file mode 100644index 0000000000..483fba1484--- /dev/null+++ b/src/core/setup/openclaw-skill-plugin-code.ts@@ -0,0 +1,417 @@+/**+ * openclaw-skill-plugin-code.ts — the two files of the generated OpenClaw+ * plugin `gbrain-skill-resolver` (written by openclaw-skill-plugin.ts):+ * index.js, the loader the gateway imports, and worker.js, the worker thread+ * that runs the resolver library. Plain ES modules with no dependencies: the+ * gateway runs them under its own Node. Only paths and the gbrain bin are+ * baked in, never mode, pins or a library path, so they change only when gbrain+ * changes the plugin code itself.+ */++export const OPENCLAW_SKILL_PLUGIN_CODE_VERSION = 1;++export interface LoaderConstants { home: string; libDir: string; statePath: string; logDir: string; gbrainBin: string; gbrainHomeEnv: string | null }++const WORKER_JS = String.raw`// Managed by gbrain setup openclaw (gbrain-skill-resolver worker thread); a re-run rewrites this file.+// Runs every synchronous resolver step off the gateway's event loop. It loads the gbrain library only+// by content address: the file must sit in the baked library directory, belong to this user, be+// writable by nobody else and hash to the sha256 the state names; the checked bytes are what run.+import { parentPort, workerData } from 'node:worker_threads';+import { createHash } from 'node:crypto';+import { readFileSync, realpathSync, statSync } from 'node:fs';+import { join, sep } from 'node:path';++const { home, libDir, sha } = workerData;+const pending = new Map();+const lastBuild = new Map();+let building = null;++function refuse(code) { const e = new Error(code); e.code = code; return e; }++async function loadLibrary() {+ if (!/^[0-9a-f]{64}$/.test(String(sha))) throw refuse('skill_resolver_library_missing');+ let real;+ try { real = realpathSync(join(libDir, sha + '.mjs')); } catch { throw refuse('skill_resolver_library_missing'); }+ if (!real.startsWith(realpathSync(libDir) + sep)) throw refuse('skill_resolver_library_mismatch');+ const st = statSync(real);+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) throw refuse('skill_resolver_library_mismatch');+ if (st.mode & 0o022) throw refuse('skill_resolver_library_mismatch');+ const bytes = readFileSync(real);+ if (createHash('sha256').update(bytes).digest('hex') !== sha) throw refuse('skill_resolver_library_mismatch');+ return import('data:text/javascript;base64,' + bytes.toString('base64'));+}++const ready = loadLibrary().then((lib) => ({ lib }), (e) => ({ code: e && e.code ? e.code : 'skill_resolver_library_mismatch' }));++function rebuild(lib, catalog, dirs) {+ if (building || !Array.isArray(dirs) || dirs.length === 0) return;+ if (Date.now() - (lastBuild.get(catalog) || 0) < 60_000) return;+ lastBuild.set(catalog, Date.now());+ building = Promise.resolve().then(() => lib.buildSkillIndex({ catalog, dirs, harness: 'openclaw' }, { home }))+ .then(() => parentPort.postMessage({ type: 'rebuilt', catalog }), (e) => parentPort.postMessage({ type: 'rebuilt', catalog, code: (e && e.code) || 'skill_resolver_internal' }))+ .finally(() => { building = null; });+}++parentPort.on('message', async (m) => {+ const loaded = await ready;+ if (m.type === 'warm') { parentPort.postMessage({ type: 'warm', version: loaded.lib ? loaded.lib.GBRAIN_VERSION : null, code: loaded.code || null }); return; }+ if (m.type === 'discard') { pending.delete(m.id); return; }+ if (m.type === 'commit') {+ const p = pending.get(m.id);+ pending.delete(m.id);+ if (p && loaded.lib) loaded.lib.commitSessionAsync(home, p.key, p.delta).catch(() => {});+ return;+ }+ if (m.type === 'rebuild') { if (loaded.lib) rebuild(loaded.lib, m.catalog, m.dirs); return; }+ if (m.type !== 'resolve') return;+ if (!loaded.lib) { parentPort.postMessage({ id: m.id, code: loaded.code }); return; }+ const lib = loaded.lib;+ const now = Date.now();+ for (const [id, p] of pending) if (now - p.at > 30_000) pending.delete(id);+ const input = { ...m.input };+ const features = Array.isArray(lib.RESOLVER_FEATURES) ? lib.RESOLVER_FEATURES : [];+ if (m.floor && features.includes('min_match_strength')) input.min_match_strength = m.floor;+ try {+ const r = await lib.resolveSkills(input, { home, catalogs: [m.catalog], failOpen: true, deadlineMs: m.deadlineMs, env: {} });+ const out = input.shadow ? (r.shadowOutput || r.output) : r.output;+ if (r.pending) pending.set(m.id, { key: r.pending.key, delta: r.pending.delta, at: now });+ const code = out.error ? out.error.code : null;+ parentPort.postMessage({ id: m.id, block: out.block, names: out.suggestions.map((s) => s.name), strengths: out.suggestions.map((s) => s.match_strength),+ no_skill_reason: out.no_skill_reason, budget_exhausted: out.budget_exhausted, deduped: out.deduped.length, code, version: out.gbrain_version });+ if (out.meta && out.meta.index_stale || code === 'skill_index_missing' || code === 'skill_index_incompatible') rebuild(lib, m.catalog, m.dirs);+ } catch (e) {+ parentPort.postMessage({ id: m.id, code: (e && e.code) || 'skill_resolver_internal' });+ }+});+`;++const LOADER_JS = String.raw`// Managed by gbrain setup openclaw; a re-run rewrites this file. Remove: gbrain setup openclaw --skill-loading off+// gbrain-skill-resolver: after each user message, up to a few installed skills that fit it (appendContext),+// plus the operator's pinned skills (appendSystemContext). Mode, pins and agents come from a data-only+// state file gbrain writes, re-read when it changes, so a mode or pin change never reloads this plugin.+// Every failure path lets the turn proceed unchanged; no handler waits more than DEADLINE_MS.+import { Worker } from 'node:worker_threads';+import { createHash } from 'node:crypto';+import { execFile } from 'node:child_process';+import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';+import { appendFile } from 'node:fs/promises';+import { join } from 'node:path';++const HOME = __HOME__;+const LIB_DIR = __LIB_DIR__;+const STATE_PATH = __STATE__;+const LOG_DIR = __LOG_DIR__;+const GBRAIN_BIN = __BIN__;+const GBRAIN_HOME_ENV = __GBRAIN_HOME_ENV__;+const PLUGIN_VERSION = __PLUGIN_VERSION__;+const ID = 'gbrain-skill-resolver';+const DEADLINE_MS = 50;+const STUCK_AFTER = 3;+const KEEP_DAYS = 14;+const MEMO_MAX = 1000;+const SESSIONS_MAX = 5000;+const WORKER_URL = new URL('./worker.js', import.meta.url);++let state = null;+let stateMtime = -1;+let worker = null;+let workerSha = null;+let timeouts = 0;+let backoffMs = 1000;+let backoffUntil = 0;+let seq = 0;+let skewCheckedAt = 0;+let skewOpenUntil = 0;+let refreshing = false;+const waiters = new Map();+const memo = new Map();+const recent = new Map();+const resetNext = new Set();+const seenSessions = new Map();++function readState() {+ let mtime;+ try { mtime = statSync(STATE_PATH).mtimeMs; } catch { state = null; stateMtime = -1; return null; }+ if (mtime !== stateMtime) {+ stateMtime = mtime;+ try {+ const s = JSON.parse(readFileSync(STATE_PATH, 'utf8'));+ if (s && s.v === 1 && s.agents && typeof s.agents === 'object') state = s;+ } catch { /* a damaged file keeps the last good state */ }+ }+ return state;+}++function day(t) { return new Date(t).toISOString().slice(0, 10); }++function log(line) {+ try {+ const at = Date.now();+ appendFile(join(LOG_DIR, 'openclaw-' + day(at) + '.jsonl'), JSON.stringify({ at: new Date(at).toISOString(), ...line }) + '\n', { mode: 0o600 }).catch(() => {});+ } catch { /* logging never fails a turn */ }+}++function pruneLogs() {+ try {+ mkdirSync(LOG_DIR, { recursive: true, mode: 0o700 });+ const cutoff = day(Date.now() - KEEP_DAYS * 86_400_000);+ for (const f of readdirSync(LOG_DIR)) {+ const m = /^openclaw-(\d{4}-\d{2}-\d{2})\.jsonl$/.exec(f);+ if (m && m[1] < cutoff) unlinkSync(join(LOG_DIR, f));+ }+ } catch { /* best effort */ }+}++function backoff() {+ backoffUntil = Date.now() + backoffMs;+ backoffMs = Math.min(backoffMs * 2, 60_000);+}++function dropWorker() {+ const w = worker;+ worker = null;+ workerSha = null;+ for (const [, done] of waiters) done(null);+ waiters.clear();+ if (w) w.terminate().catch(() => {});+}++function ensureWorker(s) {+ if (worker && workerSha === s.library_sha256) return worker;+ if (Date.now() < backoffUntil) return null;+ if (worker) dropWorker();+ let w;+ try {+ w = new Worker(WORKER_URL, { execArgv: [], env: {}, workerData: { home: HOME, libDir: LIB_DIR, sha: s.library_sha256 } });+ } catch {+ log({ outcome: 'error', code: 'skill_resolver_worker_crash' });+ backoff();+ return null;+ }+ w.unref();+ w.on('message', (m) => {+ if (m && m.type === 'warm') { if (m.code) log({ outcome: 'error', code: m.code }); return; }+ if (m && m.type === 'rebuilt') { log({ outcome: 'rebuilt', catalog: m.catalog, code: m.code || null }); return; }+ const done = m && waiters.get(m.id);+ if (done) { waiters.delete(m.id); done(m); } else if (m && m.id !== undefined) w.postMessage({ type: 'discard', id: m.id });+ });+ w.on('error', () => { if (worker === w) { log({ outcome: 'error', code: 'skill_resolver_worker_crash' }); dropWorker(); backoff(); } });+ w.on('exit', () => { if (worker === w) { worker = null; workerSha = null; } });+ worker = w;+ workerSha = s.library_sha256;+ w.postMessage({ type: 'warm' });+ return w;+}++function textOf(content) {+ if (typeof content === 'string') return content;+ if (Array.isArray(content)) return content.map((p) => (p && p.type === 'text' && typeof p.text === 'string' ? p.text : '')).join('\n').trim();+ return '';+}++function turnText(event) {+ if (event && typeof event.currentUserMessage === 'string') return event.currentUserMessage.trim();+ const msgs = event && Array.isArray(event.messages) ? event.messages : [];+ for (let i = msgs.length - 1; i >= 0; i--) if (msgs[i] && msgs[i].role === 'user') return textOf(msgs[i].content).trim();+ return '';+}++function sessionOf(event, ctx, agentId) {+ const k = (ctx && (ctx.sessionKey || ctx.sessionId)) || (event && (event.sessionKey || event.sessionId));+ return typeof k === 'string' && k ? k.slice(0, 256) : 'agent:' + agentId;+}++function senderOf(event, ctx) {+ const v = (ctx && (ctx.senderId || (ctx.sender && ctx.sender.id))) || (event && (event.senderId || (event.sender && event.sender.id)));+ return v === undefined || v === null ? null : String(v);+}++function remember(map, key, value, max) {+ map.delete(key);+ map.set(key, value);+ if (map.size > max) map.delete(map.keys().next().value);+}++function bucket(sessionKey) {+ return parseInt(createHash('sha256').update(sessionKey).digest('hex').slice(0, 8), 16) / 0x100000000;+}++function armFor(a, sessionKey) {+ if (a.mode === 'shadow') return 'shadow';+ const f = typeof a.live_fraction === 'number' ? a.live_fraction : 1;+ return bucket(sessionKey) < f ? 'live' : 'control';+}++function ask(w, msg) {+ const id = ++seq;+ return new Promise((resolve) => {+ const t = setTimeout(() => { waiters.delete(id); resolve({ id, late: true }); }, DEADLINE_MS);+ waiters.set(id, (m) => { clearTimeout(t); resolve(m ? { ...m, id } : { id, late: true }); });+ w.postMessage({ ...msg, id });+ });+}++function checkSkew(s) {+ const now = Date.now();+ if (refreshing || now < skewOpenUntil || now - skewCheckedAt < 3_600_000) return;+ skewCheckedAt = now;+ const env = { ...process.env, ...(GBRAIN_HOME_ENV ? { GBRAIN_HOME: GBRAIN_HOME_ENV } : {}) };+ execFile(GBRAIN_BIN, ['--version'], { timeout: 10_000, env }, (err, stdout) => {+ const v = !err && /\d+\.\d+\.\d+(?:\.\d+)?/.exec(String(stdout));+ if (!v || v[0] === s.gbrain_version) return;+ refreshing = true;+ execFile(GBRAIN_BIN, ['setup', 'openclaw', '--skills-index-only'], { timeout: 300_000, env }, () => {+ refreshing = false;+ const after = readState();+ if (!after || after.gbrain_version !== v[0]) { skewOpenUntil = Date.now() + 86_400_000; log({ outcome: 'error', code: 'skill_resolver_library_skew', cli: v[0], library: after ? after.gbrain_version : null }); }+ });+ });+}++async function resolveTurn(event, ctx, opts) {+ const s = readState();+ if (!s) return undefined;+ const agentId = String((ctx && ctx.agentId) || (event && event.agentId) || 'main');+ const a = s.agents[agentId];+ if (!a || a.mode === 'off' || (a.mode !== 'live' && a.mode !== 'shadow')) return undefined;+ checkSkew(s);+ const t0 = Date.now();+ const sessionKey = sessionOf(event, ctx, agentId);+ const arm = armFor(a, sessionKey);+ const result = {};+ const pinsOn = a.mode === 'live' && typeof a.pinned_block === 'string' && a.pinned_block !== '';+ if (pinsOn && a.pins_route !== 'first_turn') result.appendSystemContext = a.pinned_block;+ const firstTurn = !seenSessions.has(sessionKey) || resetNext.has(sessionKey);+ remember(seenSessions, sessionKey, 1, SESSIONS_MAX);+ const pinsFirst = pinsOn && a.pins_route === 'first_turn' && firstTurn ? a.pinned_block : '';+ const finish = (line, block) => {+ const ctxText = [pinsFirst, block || ''].filter(Boolean).join('\n\n');+ if (ctxText) result.appendContext = ctxText;+ log({ agent: agentId, arm, ms: Date.now() - t0, pins: pinsOn ? (a.pinned_ids || []).length : 0, ...line });+ return Object.keys(result).length ? result : undefined;+ };+ const text = turnText(event);+ if (!text) return finish({ outcome: 'skipped_empty' });+ const prov = (ctx && ctx.inputProvenance && ctx.inputProvenance.kind) || (event && event.inputProvenance && event.inputProvenance.kind);+ if (prov && prov !== 'external_user') return finish({ outcome: 'skipped_provenance', provenance: String(prov).slice(0, 40) });+ const trigger = (ctx && ctx.trigger) || (event && event.trigger);+ if (trigger === 'heartbeat' || trigger === 'cron') return finish({ outcome: 'skipped_provenance', provenance: trigger });+ if (Array.isArray(a.owner_sender_ids) && a.owner_sender_ids.length) {+ const sender = senderOf(event, ctx);+ if (sender !== null && !a.owner_sender_ids.includes(sender)) return finish({ outcome: 'skipped_sender' });+ }+ const turnId = (event && (event.currentUserMessageId || event.messageId)) || createHash('sha256').update(text).digest('hex').slice(0, 16);+ const memoKey = agentId + '\0' + sessionKey + '\0' + turnId;+ if (memo.has(memoKey)) return finish({ outcome: 'retry' }, memo.get(memoKey));+ const w = ensureWorker(s);+ if (!w) return finish({ outcome: 'error', code: 'skill_resolver_worker_unavailable' });+ const reset = resetNext.delete(sessionKey);+ const input = { message: text, session_id: sessionKey, harness: 'openclaw', top_k: Number.isInteger(a.top_k) ? a.top_k : 3, exclude: Array.isArray(a.pinned_ids) ? a.pinned_ids.slice(0, 64) : [], shadow: arm !== 'live', ...(reset ? { reset_session: true } : {}) };+ const reply = await ask(w, { type: 'resolve', input, catalog: a.catalog, deadlineMs: DEADLINE_MS - 5, floor: a.min_match || null, dirs: a.skill_dirs || [] });+ if (reply.late) {+ if (reset) resetNext.add(sessionKey);+ timeouts += 1;+ if (timeouts >= STUCK_AFTER) { log({ outcome: 'error', code: 'skill_resolver_worker_stuck' }); timeouts = 0; dropWorker(); backoff(); }+ return finish({ outcome: 'timeout', code: 'skill_resolve_timeout' });+ }+ timeouts = 0;+ backoffMs = 1000;+ if (reply.code && !reply.block) return finish({ outcome: 'error', code: reply.code });+ const names = Array.isArray(reply.names) ? reply.names : [];+ remember(recent, agentId + '\0' + sessionKey, { names: new Set(names), arm }, SESSIONS_MAX);+ const outcome = names.length ? 'suggested' : reply.no_skill_reason || (reply.budget_exhausted ? 'budget' : reply.deduped ? 'deduped' : 'no_match');+ const deliver = arm === 'live' && reply.block ? reply.block : '';+ let active = true;+ try { if (ctx && typeof ctx.assertActive === 'function') ctx.assertActive(); } catch { active = false; }+ if (active && !opts.selfTest) w.postMessage({ type: 'commit', id: reply.id }); else w.postMessage({ type: 'discard', id: reply.id });+ if (deliver) remember(memo, memoKey, deliver, MEMO_MAX);+ return finish({ outcome: arm === 'live' || !names.length ? outcome : 'would_suggest', suggested: names, strengths: reply.strengths, code: reply.code || null }, deliver);+}++function onToolCall(event, ctx) {+ try {+ const name = String((event && (event.toolName || event.name || (event.tool && event.tool.name))) || '');+ if (name !== 'skills_read' && name !== 'skill_view') return;+ const params = (event && (event.params || event.input || event.args || event.arguments)) || {};+ const skill = typeof params.name === 'string' ? params.name.slice(0, 256) : null;+ if (!skill) return;+ const s = state;+ const agentId = String((ctx && ctx.agentId) || (event && event.agentId) || 'main');+ const a = s && s.agents[agentId];+ if (!a || a.mode === 'off') return;+ const sessionKey = sessionOf(event, ctx, agentId);+ const r = recent.get(agentId + '\0' + sessionKey);+ log({ agent: agentId, outcome: 'read', skill, suggested: !!(r && r.names.has(skill)), pinned: Array.isArray(a.pinned_ids) && a.pinned_ids.includes(skill), arm: r ? r.arm : armFor(a, sessionKey) });+ } catch { /* observing never fails a turn */ }+}++function onCompaction(event, ctx) {+ try {+ const s = state;+ const agentId = String((ctx && ctx.agentId) || (event && event.agentId) || 'main');+ resetNext.add(sessionOf(event, ctx, agentId));+ if (s && s.agents[agentId]) log({ agent: agentId, outcome: 'compaction' });+ } catch { /* best effort */ }+}++function onSkillChanged() {+ try {+ const s = readState();+ if (!s) return;+ const w = ensureWorker(s);+ if (!w) return;+ for (const a of Object.values(s.agents)) if (a && a.mode !== 'off' && a.catalog) w.postMessage({ type: 'rebuild', catalog: a.catalog, dirs: a.skill_dirs || [] });+ } catch { /* best effort */ }+}++export default {+ id: ID,+ name: 'GBrain skill resolver',+ description: 'Suggests the installed skills that fit each user message, plus the operator\'s pinned skills (managed by gbrain setup openclaw).',+ version: PLUGIN_VERSION,+ register(api) {+ pruneLogs();+ const daily = setInterval(pruneLogs, 86_400_000);+ if (daily.unref) daily.unref();+ const on = (event, fn) => { try { api.on(event, fn); } catch { /* an older host without this event */ } };+ on('before_prompt_build', async (event, ctx) => { try { return await resolveTurn(event, ctx, {}); } catch { return undefined; } });+ on('after_tool_call', onToolCall);+ on('after_compaction', onCompaction);+ on('skill_changed', onSkillChanged);+ const s = readState();+ if (s) ensureWorker(s);+ },+ async selfTest(agentId, message) {+ const s = readState();+ if (!s || !s.agents[agentId]) return { ok: false, code: 'skill_resolver_state_missing' };+ const w = ensureWorker(s);+ if (!w) return { ok: false, code: 'skill_resolver_worker_unavailable' };+ const warm = await new Promise((resolve) => {+ const t = setTimeout(() => resolve({ code: 'skill_resolve_timeout' }), 10_000);+ const onMsg = (m) => { if (m && m.type === 'warm') { clearTimeout(t); w.off('message', onMsg); resolve(m); } };+ w.on('message', onMsg);+ w.postMessage({ type: 'warm' });+ });+ if (warm.code) { dropWorker(); return { ok: false, code: warm.code }; }+ const a = s.agents[agentId];+ const t0 = Date.now();+ const reply = await ask(w, { type: 'resolve', input: { message, harness: 'openclaw', top_k: Number.isInteger(a.top_k) ? a.top_k : 3, shadow: true }, catalog: a.catalog, deadlineMs: DEADLINE_MS - 5, floor: a.min_match || null, dirs: [] });+ dropWorker();+ if (reply.late) return { ok: false, code: 'skill_resolve_timeout', ms: Date.now() - t0 };+ if (reply.code && !reply.block) return { ok: false, code: reply.code, ms: Date.now() - t0 };+ return { ok: true, ms: Date.now() - t0, version: warm.version, suggested: reply.names || [] };+ },+};+`;++export function openclawSkillWorkerJs(): string {+ return WORKER_JS;+}++export function openclawSkillLoaderJs(c: LoaderConstants): string {+ const values: Record<string, string> = {+ __HOME__: JSON.stringify(c.home), __LIB_DIR__: JSON.stringify(c.libDir), __STATE__: JSON.stringify(c.statePath), __LOG_DIR__: JSON.stringify(c.logDir),+ __BIN__: JSON.stringify(c.gbrainBin), __GBRAIN_HOME_ENV__: JSON.stringify(c.gbrainHomeEnv), __PLUGIN_VERSION__: JSON.stringify(String(OPENCLAW_SKILL_PLUGIN_CODE_VERSION)),+ };+ return LOADER_JS.replace(/__(HOME|LIB_DIR|STATE|LOG_DIR|BIN|GBRAIN_HOME_ENV|PLUGIN_VERSION)__/g, (m) => values[m]!);+}diff --git a/src/core/setup/openclaw-skill-plugin.ts b/src/core/setup/openclaw-skill-plugin.tsnew file mode 100644index 0000000000..12629ee9dd--- /dev/null+++ b/src/core/setup/openclaw-skill-plugin.ts@@ -0,0 +1,421 @@+/**+ * openclaw-skill-plugin.ts — `gbrain setup openclaw --skill-loading+ * resolve|shadow|off`: the generated OpenClaw plugin `gbrain-skill-resolver`,+ * a sibling of the brain-first `gbrain-turn-rule` plugin (a resolver bug can+ * never take the rule down with it).+ *+ * What setup writes:+ * - the Node library, content-addressed at <gbrain home>/lib/<sha256>.mjs+ * (built from this gbrain's own source, mode 0644);+ * - one catalog per agent, `openclaw-<agent>`, over the agent's skill+ * directories (<workspace>/skills and <OpenClaw state dir>/skills);+ * - a data-only state file, <gbrain home>/openclaw-skill-resolver.json+ * (mode 0600): per agent its mode, catalog, top_k, floor, live fraction+ * and rendered pinned block, plus the library's sha256. It never names a+ * path to code: the library directory and the gbrain bin are baked into+ * the plugin's index.js;+ * - the plugin itself under <OpenClaw state dir>/gbrain/gbrain-skill-resolver.+ *+ * OpenClaw's CLI (install --link, enable, the conversation-access grant) runs+ * only when the plugin files changed or OpenClaw's config does not show the+ * plugin installed, enabled and allowed, so a mode flip, a pin change or a+ * bare refresh writes the state file and nothing else: no reload, no drained+ * admission. A failed or partial install is never reported as success: it+ * ends `skill_resolver_plugin_not_installed` with the commands still to run.+ */+import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, unlinkSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { pathToFileURL } from 'node:url';+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { bunSpawnSync } from '../spawn.ts';+import { VERSION } from '../../version.ts';+import { buildSkillIndex, catalogStatus } from '../skills/resolver/build.ts';+import { ResolverError } from '../skills/resolver/errors.ts';+import { logsDir, skillIndexRoot } from '../skills/resolver/paths.ts';+import { readDirSources } from '../skills/resolver/sources.ts';+import { openclawConfigPath, openclawStateDir, parseJson5ish, resolveOpenclawWorkspace } from './brain-first.ts';+import { openclawSkillLoaderJs, openclawSkillWorkerJs } from './openclaw-skill-plugin-code.ts';+import { pinnedBlockFor } from './skill-pins.ts';+import { readResolverConfig } from './skill-resolver-config.ts';++export const OPENCLAW_SKILL_PLUGIN_ID = 'gbrain-skill-resolver';+export const OPENCLAW_SKILL_STATE_FILE = 'openclaw-skill-resolver.json';+export const OPENCLAW_TOP_K_DEFAULT = 3;+export const OPENCLAW_FLOOR_DEFAULT = 'description';+export type OpenclawSkillMode = 'live' | 'shadow' | 'off';++export interface OpenclawSkillAgentState {+ mode: OpenclawSkillMode;+ catalog: string;+ skill_dirs: string[];+ top_k: number;+ min_match: string | null;+ live_fraction: number;+ pins_route: 'system' | 'first_turn';+ pinned_block: string;+ pinned_ids: string[];+ owner_sender_ids: string[];+}+export interface OpenclawSkillState { v: 1; gbrain_version: string; library_sha256: string; agents: Record<string, OpenclawSkillAgentState> }++export interface OpenclawSkillStep { step: 'library' | 'catalog' | 'state' | 'plugin' | 'install' | 'verify' | 'self-test'; action: 'write' | 'keep' | 'remove' | 'skip' | 'run'; detail: string }+export interface OpenclawSkillError { code: 'skill_resolver_plugin_not_installed' | 'skill_resolver_setup_incomplete' | 'skill_resolver_host_not_local' | 'skill_resolver_selftest_failed' | 'skill_source_unreadable'; message: string; commands?: string[]; argv?: string[]; recovery?: string }+export interface OpenclawSkillResult {+ mode: OpenclawSkillMode;+ steps: OpenclawSkillStep[];+ agents: Array<{ id: string; mode: OpenclawSkillMode; catalog: string; skills: number; pins: number; unknown_pins: string[] }>;+ notes: string[];+ error?: OpenclawSkillError;+}++type Run = (argv: string[]) => { ok: boolean; output: string };++export interface OpenclawSkillDeps {+ openclawBin?: string | null;+ nodeBin?: string | null;+ run?: Run;+}++export const openclawSkillPluginDir = (): string => join(openclawStateDir(), 'gbrain', OPENCLAW_SKILL_PLUGIN_ID);+export const openclawSkillStatePath = (home: string): string => join(home, OPENCLAW_SKILL_STATE_FILE);+export const openclawSkillLibDir = (home: string): string => join(home, 'lib');++function defaultRun(argv: string[]): { ok: boolean; output: string } {+ const r = bunSpawnSync(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env, timeout: 120_000 });+ return { ok: r.exitCode === 0, output: `${r.stdout.toString()}${r.stderr.toString()}`.trim() };+}++function which(name: string): string | null {+ try { return Bun.which(name, { PATH: process.env.PATH ?? '' }); } catch { return null; }+}++const shown = (argv: string[]) => argv.map((a) => (/^[\w./:=@-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');+const lastLine = (s: string) => s.trim().split('\n').at(-1) || 'no output';++/** `openclaw-<agent>`, folded to the catalog-name alphabet. */+export function openclawCatalogName(agentId: string): string {+ const slug = agentId.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[-_]+/, '').slice(0, 54) || 'main';+ return `openclaw-${slug}`;+}++interface RosterEntry { id: string; workspace?: string }++/** The agents openclaw.json defines (agents.list[] or agents.entries), each with its workspace when set. */+export function openclawRoster(): RosterEntry[] {+ try {+ const cfg = parseJson5ish(readFileSync(openclawConfigPath(), 'utf8')) as { agents?: { list?: unknown; entries?: unknown } } | undefined;+ const ws = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);+ if (Array.isArray(cfg?.agents?.list)) {+ return cfg!.agents!.list.flatMap((a): RosterEntry[] => (a && typeof (a as { id?: unknown }).id === 'string' ? [{ id: (a as { id: string }).id, workspace: ws((a as { workspace?: unknown }).workspace) }] : []));+ }+ if (cfg?.agents?.entries && typeof cfg.agents.entries === 'object') {+ return Object.entries(cfg.agents.entries as Record<string, { workspace?: unknown }>).map(([id, a]) => ({ id, workspace: ws(a?.workspace) }));+ }+ } catch { /* no readable config: the default agent only */ }+ return [];+}++/** The skill directories one agent loads: its workspace's skills/ and the state dir's shared skills/, whichever exist. */+export function openclawAgentSkillDirs(agentId: string, roster: RosterEntry[] = openclawRoster()): string[] {+ const entry = roster.find((r) => r.id === agentId);+ let workspace = entry?.workspace;+ if (!workspace && (roster.length <= 1 || agentId === 'main')) {+ const w = resolveOpenclawWorkspace();+ if (!('error' in w)) workspace = w.path;+ }+ const dirs = [workspace ? join(workspace.replace(/^~(?=\/|$)/, process.env.HOME ?? '~'), 'skills') : null, join(openclawStateDir(), 'skills')];+ return [...new Set(dirs.filter((d): d is string => !!d && existsSync(d)))];+}++export function readOpenclawSkillState(home: string): OpenclawSkillState | null {+ try {+ const s = JSON.parse(readFileSync(openclawSkillStatePath(home), 'utf8')) as OpenclawSkillState;+ return s && s.v === 1 && s.agents && typeof s.agents === 'object' ? s : null;+ } catch { return null; }+}++function pluginFiles(home: string, gbrainBin: string, gbrainHomeEnv: string | null): Record<string, string> {+ return {+ 'package.json': `${JSON.stringify({ name: OPENCLAW_SKILL_PLUGIN_ID, version: '1.0.0', private: true, type: 'module', openclaw: { extensions: ['./index.js'] } }, null, 2)}\n`,+ 'openclaw.plugin.json': `${JSON.stringify({ id: OPENCLAW_SKILL_PLUGIN_ID, name: 'GBrain skill resolver', description: 'Suggests the installed skills that fit each user message, plus the operator\'s pinned skills (managed by gbrain setup openclaw).', configSchema: { type: 'object', additionalProperties: false } }, null, 2)}\n`,+ 'index.js': openclawSkillLoaderJs({ home, libDir: openclawSkillLibDir(home), statePath: openclawSkillStatePath(home), logDir: logsDir(home), gbrainBin, gbrainHomeEnv }),+ 'worker.js': openclawSkillWorkerJs(),+ };+}++const installArgv = (bin: string, dir: string): string[][] => [+ [bin, 'plugins', 'install', '--link', dir, '--force', '--accept-capabilities'],+ [bin, 'plugins', 'enable', OPENCLAW_SKILL_PLUGIN_ID],+ [bin, 'config', 'set', `plugins.entries.${OPENCLAW_SKILL_PLUGIN_ID}.hooks.allowConversationAccess`, 'true'],+];++/** Whether OpenClaw's config already loads, enables and allows the plugin (so no CLI call is needed). */+export function openclawSkillPluginRegistered(dir = openclawSkillPluginDir()): boolean {+ try {+ const cfg = parseJson5ish(readFileSync(openclawConfigPath(), 'utf8')) as { plugins?: { load?: { paths?: unknown }; entries?: Record<string, { enabled?: unknown; hooks?: { allowConversationAccess?: unknown } }> } } | undefined;+ const entry = cfg?.plugins?.entries?.[OPENCLAW_SKILL_PLUGIN_ID];+ const paths = Array.isArray(cfg?.plugins?.load?.paths) ? cfg!.plugins!.load!.paths as unknown[] : [];+ return !!entry && entry.enabled !== false && entry.hooks?.allowConversationAccess === true && paths.includes(dir);+ } catch { return false; }+}++/** Build the library from this gbrain's source and keep it at <lib>/<sha256>.mjs, writable by its owner only. */+async function ensureLibrary(home: string, previous: string | null): Promise<{ sha256: string; wrote: boolean; path: string }> {+ const { buildResolverLibrary, LIBRARY_FILE } = await import('../../commands/skill-resolver-library.ts');+ const dir = openclawSkillLibDir(home);+ const built = await buildResolverLibrary(join(dir, LIBRARY_FILE));+ const target = join(dir, `${built.sha256}.mjs`);+ const wrote = !existsSync(target);+ if (wrote) copyFileSync(built.path, target);+ chmodSync(target, 0o644);+ for (const f of readdirSync(dir)) {+ if (/^[0-9a-f]{64}\.mjs$/.test(f) && f !== `${built.sha256}.mjs` && f !== `${previous}.mjs`) rmSync(join(dir, f), { force: true });+ }+ return { sha256: built.sha256, wrote, path: target };+}++function sampleMessage(dirs: string[]): string {+ try { return readDirSources(dirs).skills.find((s) => s.description)?.description ?? 'help'; } catch { return 'help'; }+}++/** Run one turn through the generated plugin under Node (the runtime the gateway uses), with this shell's NODE_OPTIONS. */+function selfTest(node: string, dir: string, agentId: string, message: string, run: Run): { ok: boolean; detail: string } {+ const script = `import(${JSON.stringify(pathToFileURL(join(dir, 'index.js')).href)}).then((m) => m.default.selfTest(${JSON.stringify(agentId)}, ${JSON.stringify(message)})).then((r) => { console.log(JSON.stringify(r)); process.exit(0); }, (e) => { console.log(JSON.stringify({ ok: false, code: String(e && e.code || e) })); process.exit(0); });`;+ const r = run([node, '--input-type', 'module', '-e', script]);+ let doc: { ok?: boolean; code?: string; ms?: number; suggested?: string[] } = {};+ try { doc = JSON.parse(lastLine(r.output)); } catch { /* reported below */ }+ if (r.ok && doc.ok) return { ok: true, detail: `one turn through the plugin under ${node}: ${doc.suggested?.length ?? 0} suggestion(s) in ${doc.ms ?? '?'} ms` };+ return { ok: false, detail: `the plugin's self-test under ${node} failed (${doc.code ?? lastLine(r.output)})` };+}++function hostCount(run: Run, bin: string, agentId: string): number | null {+ const r = run([bin, 'skills', 'list', '--json', '--agent', agentId]);+ if (!r.ok) return null;+ try {+ const j = JSON.parse(r.output) as unknown;+ const list = Array.isArray(j) ? j : Array.isArray((j as { skills?: unknown })?.skills) ? (j as { skills: unknown[] }).skills : null;+ return list ? list.length : null;+ } catch { return null; }+}++export interface OpenclawSkillSyncOptions {+ mode: 'live' | 'shadow' | null;+ agents: string[] | 'all' | null;+ home: string;+ gbrainBin: string;+ gbrainHomeEnv: string | null;+ dryRun: boolean;+ /** Library, catalogs and state only: never the plugin files or OpenClaw's CLI (setup --skills-index-only, the plugin's own skew refresh). */+ refreshOnly?: boolean;+ /** Rollout knobs from setup flags; unset ones keep the agent's prior value. */+ tuning?: { live_fraction?: number; pins_route?: 'system' | 'first_turn'; owner_sender_ids?: string[] };+ deps?: OpenclawSkillDeps;+}++/** skills.resolver.per_harness.openclaw.{top_k,min_match} from config.json, else the global keys, else the OpenClaw defaults. */+function openclawLaneConfig(home: string): { top_k: number; min_match: string | null } {+ const read = readResolverConfig(home);+ const r = read.state === 'ok' ? (read.doc.skills as { resolver?: Record<string, unknown> } | undefined)?.resolver ?? {} : {};+ const per = ((r.per_harness as Record<string, unknown> | undefined)?.openclaw ?? {}) as Record<string, unknown>;+ const k = per.top_k ?? r.top_k;+ const m = per.min_match ?? r.min_match;+ return {+ top_k: Number.isInteger(k) && (k as number) >= 1 && (k as number) <= 8 ? k as number : OPENCLAW_TOP_K_DEFAULT,+ min_match: m === 'none' ? null : typeof m === 'string' && ['named', 'name', 'triggers', 'routing', 'description', 'body'].includes(m) ? m : OPENCLAW_FLOOR_DEFAULT,+ };+}++/** Turn the plugin on (live or shadow) for some agents, or refresh what is on. Never throws for an expected failure. */+export async function syncOpenclawSkillPlugin(opts: OpenclawSkillSyncOptions): Promise<OpenclawSkillResult> {+ const { home, dryRun } = opts;+ const deps = opts.deps ?? {};+ const run = deps.run ?? defaultRun;+ const out: OpenclawSkillResult = { mode: opts.mode ?? 'live', steps: [], agents: [], notes: [] };+ const fail = (e: OpenclawSkillError) => ({ ...out, error: e });+ const bin = deps.openclawBin !== undefined ? deps.openclawBin : which('openclaw');+ if (!bin && !existsSync(openclawStateDir())) {+ return fail({ code: 'skill_resolver_host_not_local', message: `No openclaw on PATH and no OpenClaw state directory at ${openclawStateDir()}, so this is not the OpenClaw host. The plugin runs inside the gateway and needs this gbrain home, library and bin on the same machine.` });+ }+ if (!opts.gbrainBin.startsWith('/')) return fail({ code: 'skill_resolver_setup_incomplete', message: 'No absolute gbrain binary was found for the plugin (the gateway inherits no PATH); pass --gbrain-bin. Nothing was written.' });++ const prior = readOpenclawSkillState(home);+ const roster = openclawRoster();+ const on = prior ? Object.keys(prior.agents).filter((id) => prior.agents[id]!.mode !== 'off') : [];+ const ids = opts.agents === 'all' ? (roster.length ? roster.map((r) => r.id) : ['main'])+ : opts.agents ?? (on.length || !opts.mode ? on : prior && Object.keys(prior.agents).length ? Object.keys(prior.agents) : ['main']);+ if (ids.length === 0) return { ...out, notes: ['No agent has the skill resolver on; nothing to refresh.'] };++ const agents: Record<string, OpenclawSkillAgentState> = { ...(prior?.agents ?? {}) };+ const lane = openclawLaneConfig(home);+ const tune = opts.tuning ?? {};+ for (const id of ids) {+ const before = prior?.agents[id];+ const dirs = openclawAgentSkillDirs(id, roster);+ const catalog = openclawCatalogName(id);+ if (dirs.length === 0) { out.notes.push(`agent ${id}: no skill directory exists (looked for <workspace>/skills and ${join(openclawStateDir(), 'skills')}), so it was skipped`); continue; }+ let skills = 0;+ const status = existsSync(join(skillIndexRoot(home), catalog, 'receipt.json')) ? await catalogStatus(catalog, { home }) : null;+ const fresh = !!status?.fresh && JSON.stringify(status.receipt?.source.dirs ?? null) === JSON.stringify(dirs) && (status.receipt?.skill_count ?? 0) > 0;+ if (fresh) skills = status!.receipt!.skill_count;+ else if (dryRun) skills = readDirSources(dirs).skills.length;+ else {+ try { skills = (await buildSkillIndex({ catalog, dirs, harness: 'openclaw' }, { home })).catalog.skill_count; } catch (e) {+ out.notes.push(`agent ${id}: the catalog build failed (${e instanceof ResolverError ? e.code : (e as Error).message}), so it was skipped`);+ continue;+ }+ }+ if (skills < 1) { out.notes.push(`agent ${id}: no model-invocable skill in ${dirs.join(', ')}, so it was skipped`); continue; }+ out.steps.push({ step: 'catalog', action: fresh ? 'keep' : 'write', detail: `${catalog}: ${skills} skills from ${dirs.join(', ')}` });+ const pins = dryRun ? { block: '', ids: [], unknown: [] as string[] } : pinnedBlockFor(home, catalog, 'openclaw');+ agents[id] = {+ mode: opts.mode ?? before?.mode ?? 'live', catalog, skill_dirs: dirs,+ top_k: lane.top_k, min_match: lane.min_match,+ live_fraction: tune.live_fraction ?? before?.live_fraction ?? 1, pins_route: tune.pins_route ?? before?.pins_route ?? 'system',+ pinned_block: pins.block, pinned_ids: pins.ids, owner_sender_ids: tune.owner_sender_ids ?? before?.owner_sender_ids ?? [],+ };+ out.agents.push({ id, mode: agents[id]!.mode, catalog, skills, pins: pins.ids.length, unknown_pins: pins.unknown });+ if (pins.unknown.length) out.notes.push(`agent ${id}: pinned skill(s) not in ${catalog}, left out of the block: ${pins.unknown.join(', ')} (skill_resolver_pin_unknown)`);+ }+ if (out.agents.length === 0) return fail({ code: 'skill_resolver_setup_incomplete', message: `The skill resolver was not turned on for any agent: ${out.notes.join('; ')}. Nothing was written.` });++ const dir = openclawSkillPluginDir();+ const files = pluginFiles(home, opts.gbrainBin, opts.gbrainHomeEnv);+ const changed = Object.entries(files).some(([name, text]) => { try { return readFileSync(join(dir, name), 'utf8') !== text; } catch { return true; } });+ const registered = openclawSkillPluginRegistered(dir);+ if (dryRun) {+ out.steps.push({ step: 'library', action: 'write', detail: `the Node library at ${openclawSkillLibDir(home)}/<sha256>.mjs` });+ out.steps.push({ step: 'state', action: 'write', detail: openclawSkillStatePath(home) });+ if (!opts.refreshOnly) {+ out.steps.push({ step: 'plugin', action: changed ? 'write' : 'keep', detail: `${OPENCLAW_SKILL_PLUGIN_ID} at ${dir}` });+ out.steps.push({ step: 'install', action: changed || !registered ? 'run' : 'skip', detail: changed || !registered ? installArgv(bin ?? 'openclaw', dir).map(shown).join('; ') : 'already installed, enabled and allowed in OpenClaw' });+ }+ return out;+ }++ let lib: { sha256: string; wrote: boolean; path: string };+ try { lib = await ensureLibrary(home, prior?.library_sha256 ?? null); } catch (e) {+ return fail({ code: e instanceof ResolverError && e.code === 'skill_source_unreadable' ? 'skill_source_unreadable' : 'skill_resolver_setup_incomplete',+ message: `The skill resolver library could not be built (${(e as Error).message}). The catalogs were built; the state file and the plugin were not written.` });+ }+ out.steps.push({ step: 'library', action: lib.wrote ? 'write' : 'keep', detail: lib.path });+ const state: OpenclawSkillState = { v: 1, gbrain_version: VERSION, library_sha256: lib.sha256, agents };+ const stateText = `${JSON.stringify(state, null, 2)}\n`;+ const stateChanged = (() => { try { return readFileSync(openclawSkillStatePath(home), 'utf8') !== stateText; } catch { return true; } })();+ if (stateChanged) { mkdirSync(home, { recursive: true }); atomicWriteTextFile(openclawSkillStatePath(home), stateText, { freshMode: 0o600 }); chmodSync(openclawSkillStatePath(home), 0o600); }+ out.steps.push({ step: 'state', action: stateChanged ? 'write' : 'keep', detail: `${openclawSkillStatePath(home)} (${Object.entries(agents).map(([id, a]) => `${id} ${a.mode}`).join(', ')})` });+ if (opts.refreshOnly) return out;++ try {+ if (changed) {+ mkdirSync(dir, { recursive: true });+ for (const [name, text] of Object.entries(files)) atomicWriteTextFile(join(dir, name), text, { freshMode: 0o644 });+ }+ } catch (e) {+ return fail({ code: 'skill_resolver_plugin_not_installed', message: `The plugin could not be written to ${dir} (${(e as Error).message}).`, recovery: 'partial: the library, catalogs and state were written; the plugin files were not, and no OpenClaw command ran.' });+ }+ out.steps.push({ step: 'plugin', action: changed ? 'write' : 'keep', detail: `${OPENCLAW_SKILL_PLUGIN_ID} at ${dir}` });+ const commands = installArgv(bin ?? 'openclaw', dir);+ if (!changed && registered) out.steps.push({ step: 'install', action: 'skip', detail: 'already installed, enabled and allowed in OpenClaw; mode and pins are read from the state file, so nothing reloads' });+ else {+ if (!bin) return fail({ code: 'skill_resolver_plugin_not_installed', message: `The plugin was written to ${dir}, but there is no openclaw on PATH, so OpenClaw has not installed it.`, commands: commands.map(shown), argv: commands[0], recovery: `partial: files written, 0 of ${commands.length} commands ran; run them on the OpenClaw host, restart the gateway, then gbrain doctor --only skill_resolver` });+ for (const [i, argv] of commands.entries()) {+ const r = run(argv);+ if (!r.ok) return fail({ code: 'skill_resolver_plugin_not_installed', message: `\`${shown(argv)}\` failed (${lastLine(r.output)}).`, commands: commands.slice(i).map(shown), argv: argv, recovery: `partial: files written, ${i} of ${commands.length} commands ran; run the rest, restart the gateway, then gbrain doctor --only skill_resolver` });+ }+ out.steps.push({ step: 'install', action: 'run', detail: `installed, enabled and allowed with the openclaw CLI; restart the gateway once to load new plugin code` });+ const inspect = run([bin, 'plugins', 'inspect', OPENCLAW_SKILL_PLUGIN_ID, '--runtime', '--json']);+ const loaded = inspect.ok && inspect.output.includes('before_prompt_build') && /"status"\s*:\s*"loaded"|"imported"\s*:\s*true/.test(inspect.output) && !/"status"\s*:\s*"(?:error|disabled)"/.test(inspect.output);+ if (!loaded) return fail({ code: 'skill_resolver_plugin_not_installed', message: `\`openclaw plugins inspect ${OPENCLAW_SKILL_PLUGIN_ID} --runtime --json\` does not show the plugin loaded with before_prompt_build (${lastLine(inspect.output)}).`, commands: [shown([bin, 'plugins', 'inspect', OPENCLAW_SKILL_PLUGIN_ID, '--runtime', '--json'])], argv: [bin, 'plugins', 'inspect', OPENCLAW_SKILL_PLUGIN_ID, '--runtime', '--json'], recovery: `partial: files written, ${commands.length} of ${commands.length} commands ran, but OpenClaw does not load the plugin; check the inspect output, then gbrain doctor --only skill_resolver` });+ out.steps.push({ step: 'verify', action: 'run', detail: 'openclaw loads it with before_prompt_build' });+ }+ if (bin) {+ for (const a of out.agents) {+ const n = hostCount(run, bin, a.id);+ if (n !== null && n < a.skills) out.notes.push(`agent ${a.id}: OpenClaw lists ${n} skills but ${a.catalog} holds ${a.skills}; OpenClaw dropped some at load (skills.limits.maxCandidatesPerRoot), and skills_read cannot open those (skill_resolver_host_load_cut)`);+ }+ }+ const node = deps.nodeBin !== undefined ? deps.nodeBin : which('node');+ if (!node) out.notes.push('no node on PATH, so the plugin self-test did not run; the gateway runs it under its own Node');+ else {+ const first = out.agents[0]!;+ const t = selfTest(node, dir, first.id, sampleMessage(agents[first.id]!.skill_dirs), run);+ if (!t.ok) return fail({ code: 'skill_resolver_selftest_failed', message: `${t.detail}. The plugin is installed but would not resolve a turn.` });+ out.steps.push({ step: 'self-test', action: 'run', detail: t.detail });+ }+ return out;+}++/**+ * Re-render every OpenClaw agent's pinned block from config.json into the+ * state file (gbrain skills pin add|remove). The plugin re-reads the state on+ * its next turn, so nothing reloads and no OpenClaw command runs. Returns the+ * agents whose block changed.+ */+export function refreshOpenclawPins(home: string): string[] {+ const prior = readOpenclawSkillState(home);+ if (!prior) return [];+ const changed: string[] = [];+ const agents = { ...prior.agents };+ for (const [id, a] of Object.entries(agents)) {+ const pins = pinnedBlockFor(home, a.catalog, 'openclaw');+ if (pins.block === a.pinned_block && JSON.stringify(pins.ids) === JSON.stringify(a.pinned_ids)) continue;+ agents[id] = { ...a, pinned_block: pins.block, pinned_ids: pins.ids };+ changed.push(id);+ }+ if (changed.length) atomicWriteTextFile(openclawSkillStatePath(home), `${JSON.stringify({ ...prior, agents }, null, 2)}\n`, { freshMode: 0o600 });+ return changed;+}++/**+ * Turn the plugin off for some agents (their pins stay in config.json), or+ * for every agent: then uninstall it, delete its directory and the state+ * file. The directory stays until the uninstall succeeds (OpenClaw refuses a+ * config whose load path is missing). Null when nothing of it exists.+ */+export function removeOpenclawSkillPlugin(opts: { home: string; agents: string[] | null; dryRun: boolean; deps?: OpenclawSkillDeps }): OpenclawSkillResult | null {+ const dir = openclawSkillPluginDir();+ const prior = readOpenclawSkillState(opts.home);+ if (!prior && !existsSync(dir)) return null;+ const out: OpenclawSkillResult = { mode: 'off', steps: [], agents: [], notes: [] };+ const agents = { ...(prior?.agents ?? {}) };+ for (const id of opts.agents ?? Object.keys(agents)) {+ if (agents[id]) { agents[id] = { ...agents[id]!, mode: 'off' }; out.agents.push({ id, mode: 'off', catalog: agents[id]!.catalog, skills: 0, pins: 0, unknown_pins: [] }); }+ }+ const left = Object.values(agents).some((a) => a.mode !== 'off');+ if (left && prior) {+ if (!opts.dryRun) atomicWriteTextFile(openclawSkillStatePath(opts.home), `${JSON.stringify({ ...prior, agents }, null, 2)}\n`, { freshMode: 0o600 });+ out.steps.push({ step: 'state', action: 'write', detail: `${openclawSkillStatePath(opts.home)} (${(opts.agents ?? []).join(', ')} off; the plugin stays for the others)` });+ return out;+ }+ if (existsSync(dir)) {+ const deps = opts.deps ?? {};+ const bin = deps.openclawBin !== undefined ? deps.openclawBin : which('openclaw');+ const uninstall = [bin ?? 'openclaw', 'plugins', 'uninstall', OPENCLAW_SKILL_PLUGIN_ID, '--force'];+ if (opts.dryRun) out.steps.push({ step: 'install', action: 'remove', detail: `${shown(uninstall)}, then ${dir}` });+ else {+ const r = bin ? (deps.run ?? defaultRun)(uninstall) : { ok: false, output: 'no openclaw on PATH' };+ if (!r.ok) {+ if (prior) atomicWriteTextFile(openclawSkillStatePath(opts.home), `${JSON.stringify({ ...prior, agents }, null, 2)}\n`, { freshMode: 0o600 });+ return { ...out, error: { code: 'skill_resolver_plugin_not_installed', message: `Every agent is off (the plugin injects nothing now), but \`${shown(uninstall)}\` did not run (${lastLine(r.output)}), so ${dir} stays in place.`, commands: [shown(uninstall)], argv: uninstall, recovery: `partial: state set to off; run the command on the OpenClaw host, then delete ${dir}` } };+ }+ try {+ rmSync(dir, { recursive: true, force: true });+ if (readdirSync(dirname(dir)).length === 0) rmdirSync(dirname(dir));+ } catch { /* uninstalled; a leftover directory is no longer loaded */ }+ out.steps.push({ step: 'install', action: 'remove', detail: `${OPENCLAW_SKILL_PLUGIN_ID} uninstalled and ${dir} removed` });+ }+ }+ if (prior) {+ if (!opts.dryRun) { try { unlinkSync(openclawSkillStatePath(opts.home)); } catch { /* gone */ } }+ out.steps.push({ step: 'state', action: 'remove', detail: `${openclawSkillStatePath(opts.home)} (pins stay in config.json)` });+ }+ return out;+}++/** One human line per step, matching setup's step lines. */+export function describeOpenclawSkill(r: OpenclawSkillResult, dryRun: boolean): string[] {+ const lines = r.steps.map((s) => ` ${(dryRun && (s.action === 'write' || s.action === 'remove' || s.action === 'run') ? `would ${s.action}` : s.action).padEnd(8)} ${'resolver'.padEnd(7)} ${s.step}: ${s.detail}`);+ for (const a of r.agents) lines.push(`skill resolver (openclaw agent ${a.id}): ${a.mode}; ${a.skills} skills in ${a.catalog}; ${a.pins} pinned`);+ for (const n of r.notes) lines.push(` note ${'resolver'.padEnd(7)} ${n}`);+ return lines;+}diff --git a/src/core/setup/skill-pins.ts b/src/core/setup/skill-pins.tsnew file mode 100644index 0000000000..eed7f2b96c--- /dev/null+++ b/src/core/setup/skill-pins.ts@@ -0,0 +1,112 @@+/**+ * skill-pins.ts — the operator's always-on skills for one catalog+ * (`gbrain skills pin add|remove|list`), stored in the file plane at+ * config.json `skills.resolver.pins.<catalog>` so a `--skill-loading off`+ * (which removes the derived skill-index state) never deletes them.+ *+ * gbrain ships no pins: a catalog with none renders no pinned block. Each pin+ * is a skill id that must be in the catalog's index and an optional+ * trigger-first line (one line, at most 100 characters, no angle brackets).+ * Rendering drops any pin the catalog no longer holds and reports it, so an+ * unknown name never reaches the model, and cuts the block at whole lines to+ * PIN_BLOCK_TOKEN_CAP. The same pins always render the same bytes, which keeps+ * the host's prompt cache warm.+ */+import { existsSync, unlinkSync } from 'node:fs';+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';+import { estimateTokens, loadLine, quoted } from '../skills/resolver/block.ts';+import { IndexReader } from '../skills/resolver/index-format.ts';+import { catalogFile, validCatalogName } from '../skills/resolver/paths.ts';+import { readResolverConfig, type ResolverConfigRead } from './skill-resolver-config.ts';++export const PIN_LINE_MAX = 100;+export const PINS_MAX = 64;+export const PIN_BLOCK_TOKEN_CAP = 600;++export interface Pin { name: string; line?: string }+export interface PinnedBlock { block: string; tokens: number; ids: string[]; unknown: string[]; cut: string[] }++/** Why a pin is not valid as written, or null. */+export function pinProblem(pin: Pin): string | null {+ if (!pin.name || pin.name.length > 256 || /[\u0000-\u001f\u007f<>]/.test(pin.name)) return 'the skill name must be 1-256 visible characters with no < or >';+ if (pin.line !== undefined && (pin.line.length === 0 || pin.line.length > PIN_LINE_MAX || /[\u0000-\u001f\u007f<>]/.test(pin.line))) return `--line must be one line of 1-${PIN_LINE_MAX} characters with no < or >`;+ return null;+}++function section(doc: Record<string, unknown>): Record<string, unknown> {+ const s = (doc.skills as { resolver?: { pins?: unknown } } | undefined)?.resolver?.pins;+ return s && typeof s === 'object' && !Array.isArray(s) ? s as Record<string, unknown> : {};+}++/** The pins for one catalog, in the operator's order; malformed entries are skipped. */+export function readPins(read: ResolverConfigRead, catalog: string): Pin[] {+ if (read.state !== 'ok') return [];+ const raw = section(read.doc)[catalog];+ if (!Array.isArray(raw)) return [];+ return raw.flatMap((p): Pin[] => {+ if (!p || typeof p !== 'object') return [];+ const { name, line } = p as { name?: unknown; line?: unknown };+ if (typeof name !== 'string') return [];+ const pin: Pin = typeof line === 'string' ? { name, line } : { name };+ return pinProblem(pin) ? [] : [pin];+ });+}++/** Every catalog that has pins. */+export function pinnedCatalogs(read: ResolverConfigRead): string[] {+ return read.state === 'ok' ? Object.keys(section(read.doc)).filter(validCatalogName).sort() : [];+}++/** Replace one catalog's pins (an empty list removes the key, then any object it leaves empty). The caller checked the file is readable. */+export function writePins(read: Exclude<ResolverConfigRead, { state: 'unreadable' }>, catalog: string, pins: Pin[]): void {+ const doc = read.state === 'ok' ? structuredClone(read.doc) : {};+ const skills = (doc.skills && typeof doc.skills === 'object' && !Array.isArray(doc.skills) ? doc.skills : {}) as Record<string, unknown>;+ const resolver = (skills.resolver && typeof skills.resolver === 'object' && !Array.isArray(skills.resolver) ? skills.resolver : {}) as Record<string, unknown>;+ const all = section(doc);+ if (pins.length) all[catalog] = pins.map((p) => (p.line ? { name: p.name, line: p.line } : { name: p.name }));+ else delete all[catalog];+ if (Object.keys(all).length) resolver.pins = all; else delete resolver.pins;+ if (Object.keys(resolver).length) skills.resolver = resolver; else delete skills.resolver;+ if (Object.keys(skills).length) doc.skills = skills; else delete doc.skills;+ if (Object.keys(doc).length === 0) { if (existsSync(read.path)) unlinkSync(read.path); return; }+ atomicWriteTextFile(read.path, `${JSON.stringify(doc, null, 2)}\n`, { freshMode: 0o600 });+}++/** The skill ids a built catalog holds, or null when it has no readable index. */+export function catalogSkillIds(home: string, catalog: string): Set<string> | null {+ if (!validCatalogName(catalog)) return null;+ const path = catalogFile(home, catalog, 'index.bin');+ if (!existsSync(path)) return null;+ let ix: IndexReader | null = null;+ try {+ ix = IndexReader.open(path);+ const ids = new Set<string>();+ for (let d = 0; d < ix.n; d++) ids.add(ix.meta(d).id);+ return ids;+ } catch { return null; } finally { ix?.close(); }+}++/**+ * The pinned block for one harness. With `known` set, a pin the catalog does+ * not hold is left out and listed in `unknown`; with null (no index yet)+ * nothing renders, because an unchecked name must never reach the model.+ */+export function renderPinnedBlock(pins: readonly Pin[], opts: { harness?: string; known: Set<string> | null; cap?: number }): PinnedBlock {+ const cap = opts.cap ?? PIN_BLOCK_TOKEN_CAP;+ if (!opts.known) return { block: '', tokens: 0, ids: [], unknown: pins.map((p) => p.name), cut: [] };+ const valid = pins.filter((p) => opts.known!.has(p.name));+ const unknown = pins.filter((p) => !opts.known!.has(p.name)).map((p) => p.name);+ const lines = valid.map((p) => `- id: ${quoted(p.name)}${p.line ? ` when: ${quoted(p.line)}` : ''}`);+ const head = `Always-available skills, chosen by this agent's operator, whether or not a skill list shows them. ${loadLine(opts.harness)}`;+ for (let kept = lines.length; kept > 0; kept--) {+ const block = ['<pinned_skills>', head, ...lines.slice(0, kept), '</pinned_skills>'].join('\n');+ const tokens = estimateTokens(block);+ if (tokens <= cap) return { block, tokens, ids: valid.slice(0, kept).map((p) => p.name), unknown, cut: valid.slice(kept).map((p) => p.name) };+ }+ return { block: '', tokens: 0, ids: [], unknown, cut: valid.map((p) => p.name) };+}++/** One catalog's pins rendered against its current index (what setup writes into a harness's surface). */+export function pinnedBlockFor(home: string, catalog: string, harness?: string): PinnedBlock {+ return renderPinnedBlock(readPins(readResolverConfig(home), catalog), { harness, known: catalogSkillIds(home, catalog) });+}diff --git a/test/openclaw-skill-plugin.test.ts b/test/openclaw-skill-plugin.test.tsnew file mode 100644index 0000000000..7e3ca4a8e7--- /dev/null+++ b/test/openclaw-skill-plugin.test.ts@@ -0,0 +1,334 @@+/**+ * GBRA-435 PR 1: gbrain setup openclaw --skill-loading resolve|shadow|off and+ * the generated gbrain-skill-resolver plugin (src/core/setup/openclaw-skill-plugin.ts,+ * openclaw-skill-plugin-code.ts), plus gbrain skills pin (skill-pins.ts).+ *+ * Protects: a failed or partial OpenClaw install never exits 0+ * (skill_resolver_plugin_not_installed, exit 3, with the commands still to+ * run); a mode flip or a pin change runs no OpenClaw command (state file+ * only, so nothing reloads); pins are validated against the catalog, never+ * render an unknown name, are never also suggested, and survive --skill-loading+ * off; the plugin under Node injects the pinned block and up to 3 suggestions+ * on live turns, nothing on shadow, internal or off turns, commits a retried+ * turn once, refuses a library writable by others, gives up on a stuck worker+ * within the deadline and logs each miss; a brainless home stays brainless.+ */+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { createHash } from 'node:crypto';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';++setDefaultTimeout(120_000);+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const NODE = Bun.which('node');+const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++interface Box { root: string; home: string; state: string; bin: string; calls: string; env: Record<string, string | undefined> }++function skill(dir: string, name: string, description: string): void {+ mkdirSync(join(dir, name), { recursive: true });+ writeFileSync(join(dir, name, 'SKILL.md'), '---\nname: ' + name + '\ndescription: ' + description + '\n---\nSteps.\n');+}++/** A fake openclaw: records every call, edits openclaw.json like install/enable/config set do, and fails the step named in FAIL_STEP. */+const FAKE_OPENCLAW = String.raw`#!/bin/sh+echo "$*" >> "$OPENCLAW_CALLS"+[ -n "$FAIL_STEP" ] && [ "$1 $2" = "$FAIL_STEP" ] && { echo "boom: $FAIL_STEP failed" >&2; exit 1; }+cfg="$OPENCLAW_STATE_DIR/openclaw.json"+case "$1 $2" in+ "plugins install") node -e 'const f=require("fs"),p=process.argv[1],c=JSON.parse(f.readFileSync(p,"utf8"));c.plugins=c.plugins||{};c.plugins.load=c.plugins.load||{paths:[]};if(!c.plugins.load.paths.includes(process.argv[2]))c.plugins.load.paths.push(process.argv[2]);f.writeFileSync(p,JSON.stringify(c))' "$cfg" "$4";;+ "plugins enable") node -e 'const f=require("fs"),p=process.argv[1],c=JSON.parse(f.readFileSync(p,"utf8"));c.plugins.entries=c.plugins.entries||{};c.plugins.entries[process.argv[2]]={...(c.plugins.entries[process.argv[2]]||{}),enabled:true};f.writeFileSync(p,JSON.stringify(c))' "$cfg" "$3";;+ "config set") node -e 'const f=require("fs"),p=process.argv[1],c=JSON.parse(f.readFileSync(p,"utf8"));const id=process.argv[2].split(".")[2];c.plugins.entries[id].hooks={allowConversationAccess:true};f.writeFileSync(p,JSON.stringify(c))' "$cfg" "$3";;+ "plugins inspect") [ -n "$INSPECT_BROKEN" ] && { echo '{"status":"error"}'; exit 0; }; echo '{"status":"loaded","hooks":["before_prompt_build"]}';;+ "plugins uninstall") ;;+ "skills list") echo '[]' > /dev/null; exit 1;;+esac+`;++function box(opts: { openclaw?: boolean; skills?: number } = {}): Box {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-openclaw-skill-'));+ roots.push(root);+ const home = join(root, 'home'), state = join(root, 'state'), binDir = join(root, 'bin');+ mkdirSync(home, { recursive: true });+ mkdirSync(join(state, 'workspace', 'skills'), { recursive: true });+ mkdirSync(binDir);+ writeFileSync(join(state, 'openclaw.json'), '{}');+ const skills = join(state, 'workspace', 'skills');+ skill(skills, 'deploy-service', 'Use when you deploy a service to production');+ skill(skills, 'email-triage', 'Use when you triage the email inbox');+ skill(skills, 'calendar-sync', 'Use when you sync the calendar');+ for (let i = 0; i < (opts.skills ?? 0); i++) skill(skills, 'zz-filler-' + String(i).padStart(3, '0'), 'Use when you need filler task number ' + i);+ const bin = join(binDir, 'gbrain');+ writeFileSync(bin, '#!/bin/sh\nexec \'' + process.execPath + '\' --no-env-file \'' + CLI + '\' "$@"\n');+ chmodSync(bin, 0o755);+ if (opts.openclaw !== false) { writeFileSync(join(binDir, 'openclaw'), FAKE_OPENCLAW); chmodSync(join(binDir, 'openclaw'), 0o755); }+ const calls = join(root, 'openclaw-calls.log');+ const path = [binDir, NODE ? join(NODE, '..') : '', '/usr/bin', '/bin'].filter(Boolean).join(':');+ return { root, home, state, bin, calls, env: { HOME: home, GBRAIN_HOME: home, OPENCLAW_STATE_DIR: state, OPENCLAW_CALLS: calls, PATH: path, OPENCLAW_PROFILE: undefined, OPENCLAW_CONFIG_PATH: undefined, OPENCLAW_WORKSPACE_DIR: undefined, GBRAIN_SKILL_LOADING: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined } };+}++async function setup(b: Box, extra: string[], env: Record<string, string | undefined> = {}) {+ const r = await runCli(['setup', 'openclaw', '--instructions-only', '--gbrain-bin', b.bin, '--json', ...extra], { env: { ...b.env, ...env }, timeoutMs: 110_000 });+ let doc: any = null;+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }+ return { ...r, doc, resolver: doc?.skill_resolver };+}++const calls = (b: Box) => (existsSync(b.calls) ? readFileSync(b.calls, 'utf8').trim().split('\n').filter((l) => l.includes('gbrain-skill-resolver')) : []);+const gbrainHome = (b: Box) => join(b.home, '.gbrain');+const statePath = (b: Box) => join(gbrainHome(b), 'openclaw-skill-resolver.json');+const pluginDir = (b: Box) => join(b.state, 'gbrain', 'gbrain-skill-resolver');+const readState = (b: Box) => JSON.parse(readFileSync(statePath(b), 'utf8'));++/** Drive the generated plugin under Node with a fake OpenClaw api; each step is [kind, args]. */+function drive(b: Box, steps: unknown[], nodeOptions?: string): any {+ const script = join(b.root, 'drive.mjs');+ writeFileSync(script, String.raw`+import { pathToFileURL } from 'node:url';+import { readFileSync, writeFileSync } from 'node:fs';+const [dir, statePath, stepsJson] = process.argv.slice(2);+const m = (await import(pathToFileURL(dir + '/index.js').href)).default;+const h = {};+m.register({ on: (e, f) => { h[e] = f; } });+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+await sleep(500);+const out = [];+for (const [kind, a] of JSON.parse(stepsJson)) {+ const ctx = { agentId: 'main', sessionKey: a.session || 'agent:main:s1', inputProvenance: { kind: a.provenance || 'external_user' }, ...(a.sender ? { senderId: a.sender } : {}) };+ if (kind === 'turn') out.push(await h.before_prompt_build({ currentUserMessage: a.text, currentUserMessageId: a.id }, ctx) ?? null);+ else if (kind === 'read') { h.after_tool_call({ toolName: 'skills_read', params: { name: a.name } }, ctx); out.push('read'); }+ else if (kind === 'compact') { h.after_compaction({}, ctx); out.push('compact'); }+ else if (kind === 'state') { const s = JSON.parse(readFileSync(statePath, 'utf8')); Object.assign(s.agents.main, a); writeFileSync(statePath, JSON.stringify(s)); await sleep(20); out.push('state'); }+ else if (kind === 'sleep') { await sleep(a.ms); out.push('slept'); }+}+await sleep(300);+console.log(JSON.stringify(out));+process.exit(0);+`);+ const r = Bun.spawnSync([NODE!, script, pluginDir(b), statePath(b), JSON.stringify(steps)], { env: { PATH: b.env.PATH!, HOME: b.home, ...(nodeOptions ? { NODE_OPTIONS: nodeOptions } : {}) }, stdout: 'pipe', stderr: 'pipe', timeout: 60_000 });+ const text = r.stdout.toString().trim().split('\n').at(-1) ?? '';+ try { return JSON.parse(text); } catch { throw new Error('drive failed: ' + r.stderr.toString() + text); }+}++function logLines(b: Box): any[] {+ const dir = join(gbrainHome(b), 'skill-index', 'logs');+ return readdirSync(dir).filter((f) => f.startsWith('openclaw-')).flatMap((f) => readFileSync(join(dir, f), 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)));+}++describe.skipIf(!NODE)('gbrain setup openclaw --skill-loading', () => {+ test('shadow installs once; a flip to live runs no OpenClaw command and keeps the plugin files', async () => {+ const b = box();+ const first = await setup(b, ['--skill-loading', 'shadow']);+ expect(first.exitCode).toBe(0);+ expect(first.resolver.error).toBeUndefined();+ expect(first.resolver.steps.map((s: any) => s.step)).toEqual(['catalog', 'library', 'state', 'plugin', 'install', 'verify', 'self-test']);+ expect(calls(b)).toEqual([+ 'plugins install --link ' + pluginDir(b) + ' --force --accept-capabilities',+ 'plugins enable gbrain-skill-resolver',+ 'config set plugins.entries.gbrain-skill-resolver.hooks.allowConversationAccess true',+ 'plugins inspect gbrain-skill-resolver --runtime --json',+ ]);+ expect(readState(b).agents.main).toMatchObject({ mode: 'shadow', catalog: 'openclaw-main', top_k: 3, min_match: 'description', live_fraction: 1, pins_route: 'system' });+ expect(readFileSync(statePath(b), 'utf8')).not.toContain('.mjs');+ const index = readFileSync(join(pluginDir(b), 'index.js'), 'utf8');+ const before = calls(b).length;+ const flip = await setup(b, ['--skill-loading', 'resolve', '--live-fraction', '0.5']);+ expect(flip.exitCode).toBe(0);+ expect(calls(b).length).toBe(before);+ expect(flip.resolver.steps.find((s: any) => s.step === 'install')).toMatchObject({ action: 'skip' });+ expect(readFileSync(join(pluginDir(b), 'index.js'), 'utf8')).toBe(index);+ expect(readState(b).agents.main).toMatchObject({ mode: 'live', live_fraction: 0.5 });+ expect((Bun.spawnSync(['stat', '-c', '%a', statePath(b)]).stdout.toString().trim())).toBe('600');+ });++ test('no openclaw on PATH: exit 3, skill_resolver_plugin_not_installed, the commands still to run', async () => {+ const b = box({ openclaw: false });+ const r = await setup(b, ['--skill-loading', 'resolve']);+ expect(r.exitCode).toBe(3);+ expect(r.resolver.error.code).toBe('skill_resolver_plugin_not_installed');+ expect(r.resolver.error.commands).toHaveLength(3);+ expect(r.resolver.error.recovery).toContain('0 of 3 commands ran');+ expect(existsSync(join(pluginDir(b), 'index.js'))).toBe(true);+ expect(existsSync(statePath(b))).toBe(true);+ });++ test('a failed openclaw step: exit 3 naming it, with only the remaining commands', async () => {+ const b = box();+ const r = await setup(b, ['--skill-loading', 'resolve'], { FAIL_STEP: 'plugins enable' });+ expect(r.exitCode).toBe(3);+ expect(r.resolver.error.code).toBe('skill_resolver_plugin_not_installed');+ expect(r.resolver.error.message).toContain('boom: plugins enable failed');+ expect(r.resolver.error.commands).toEqual(['openclaw plugins enable gbrain-skill-resolver', 'openclaw config set plugins.entries.gbrain-skill-resolver.hooks.allowConversationAccess true'].map((c) => join(b.root, 'bin') + '/' + c));+ expect(r.resolver.error.recovery).toContain('1 of 3 commands ran');+ });++ test('plugins inspect not showing it loaded: exit 3, never success', async () => {+ const b = box();+ const r = await setup(b, ['--skill-loading', 'resolve'], { INSPECT_BROKEN: '1' });+ expect(r.exitCode).toBe(3);+ expect(r.resolver.error.code).toBe('skill_resolver_plugin_not_installed');+ });++ test('--dry-run writes nothing', async () => {+ const b = box();+ const r = await setup(b, ['--skill-loading', 'resolve', '--dry-run']);+ expect(r.exitCode).toBe(0);+ expect(existsSync(statePath(b))).toBe(false);+ expect(existsSync(pluginDir(b))).toBe(false);+ expect(calls(b)).toEqual([]);+ });++ test('a brainless home stays brainless', async () => {+ const b = box();+ await setup(b, ['--skill-loading', 'resolve']);+ const cfg = existsSync(join(gbrainHome(b), 'config.json')) ? JSON.parse(readFileSync(join(gbrainHome(b), 'config.json'), 'utf8')) : {};+ expect(cfg.engine).toBeUndefined();+ expect(cfg.database_url).toBeUndefined();+ });+});++describe.skipIf(!NODE)('gbrain skills pin', () => {+ test('validates against the catalog, updates the plugin state hot, and survives --skill-loading off', async () => {+ const b = box();+ await setup(b, ['--skill-loading', 'resolve']);+ const before = calls(b).length;+ const bad = await runCli(['skills', 'pin', 'add', 'not-a-skill', '--catalog', 'openclaw-main', '--json'], { env: b.env });+ expect(bad.exitCode).not.toBe(0);+ expect(bad.stdout + bad.stderr).toContain('skill_resolver_pin_unknown');+ const long = await runCli(['skills', 'pin', 'add', 'deploy-service', '--catalog', 'openclaw-main', '--line', 'x'.repeat(101)], { env: b.env });+ expect(long.exitCode).toBe(2);+ const ok = await runCli(['skills', 'pin', 'add', 'deploy-service', '--catalog', 'openclaw-main', '--line', 'Before any production deploy', '--json'], { env: b.env });+ expect(ok.exitCode).toBe(0);+ expect(JSON.parse(ok.stdout)).toMatchObject({ rendered: ['deploy-service'], openclaw_agents_updated: ['main'] });+ expect(calls(b).length).toBe(before);+ const st = readState(b).agents.main;+ expect(st.pinned_ids).toEqual(['deploy-service']);+ expect(st.pinned_block).toContain('id: "deploy-service" when: "Before any production deploy"');+ expect(st.pinned_block).toContain('skills_read({name})');+ const off = await setup(b, ['--skill-loading', 'off']);+ expect(off.exitCode).toBe(0);+ expect(existsSync(statePath(b))).toBe(false);+ expect(existsSync(pluginDir(b))).toBe(false);+ expect(calls(b).at(-1)).toBe('plugins uninstall gbrain-skill-resolver --force');+ const list = await runCli(['skills', 'pin', 'list', '--catalog', 'openclaw-main', '--json'], { env: b.env });+ expect(JSON.parse(list.stdout).pins).toEqual([{ name: 'deploy-service', line: 'Before any production deploy' }]);+ });+});++describe.skipIf(!NODE)('the gbrain-skill-resolver plugin under Node', () => {+ test('live: pins every turn, up to 3 suggestions, pinned never suggested, retry commits once; skips internal turns; shadow and off inject nothing', async () => {+ const b = box({ skills: 250 });+ await setup(b, ['--skill-loading', 'resolve']);+ await runCli(['skills', 'pin', 'add', 'deploy-service', '--catalog', 'openclaw-main'], { env: b.env });+ const out = drive(b, [+ ['turn', { text: 'deploy the service to production and triage the email inbox', id: 'm1' }],+ ['turn', { text: 'deploy the service to production and triage the email inbox', id: 'm1' }],+ ['turn', { text: 'sync the calendar', id: 'm2', provenance: 'inter_session' }],+ ['turn', { text: 'filler task number 249', id: 'm3', session: 'agent:main:s9' }],+ ['read', { name: 'email-triage' }],+ ['state', { mode: 'shadow' }],+ ['turn', { text: 'sync the calendar', id: 'm4', session: 'agent:main:s2' }],+ ['state', { mode: 'off' }],+ ['turn', { text: 'sync the calendar', id: 'm5', session: 'agent:main:s3' }],+ ], '--max-old-space-size=256');+ expect(out[0].appendSystemContext).toContain('<pinned_skills>');+ expect(out[0].appendContext).toContain('<relevant_skills>');+ expect(out[0].appendContext).toContain('email-triage');+ expect(out[0].appendContext).not.toContain('"deploy-service"');+ expect((out[0].appendContext.match(/^- id:/gm) ?? []).length).toBeLessThanOrEqual(3);+ expect(out[1]).toEqual(out[0]);+ expect(out[2]).toEqual({ appendSystemContext: out[0].appendSystemContext });+ expect(out[3].appendContext).toContain('zz-filler-249');+ expect(out[6]).toBeNull();+ expect(out[8]).toBeNull();+ const lines = logLines(b);+ expect(lines.map((l) => l.outcome)).toEqual(['suggested', 'retry', 'skipped_provenance', 'suggested', 'read', 'would_suggest']);+ expect(lines.find((l) => l.outcome === 'read')).toMatchObject({ skill: 'email-triage', suggested: true, pinned: false });+ expect(JSON.stringify(lines)).not.toContain('production');+ const sessions = readdirSync(join(gbrainHome(b), 'skill-index', 'sessions'));+ expect(sessions.length).toBeGreaterThan(0);+ });++ test('rollout knobs: control arm, owner senders, first-turn pins and compaction', async () => {+ const b = box();+ await setup(b, ['--skill-loading', 'resolve', '--pins-route', 'first_turn', '--owner-sender', 'owner-1']);+ await runCli(['skills', 'pin', 'add', 'deploy-service', '--catalog', 'openclaw-main'], { env: b.env });+ const out = drive(b, [+ ['turn', { text: 'triage the email inbox', id: 'm1', sender: 'owner-1' }],+ ['turn', { text: 'sync the calendar', id: 'm2', sender: 'owner-1' }],+ ['turn', { text: 'sync the calendar', id: 'm3', sender: 'stranger', session: 'agent:main:s5' }],+ ['compact', {}],+ ['turn', { text: 'sync the calendar please', id: 'm4', sender: 'owner-1' }],+ ['state', { live_fraction: 0 }],+ ['turn', { text: 'triage the email inbox', id: 'm5', sender: 'owner-1', session: 'agent:main:s6' }],+ ]);+ expect(out[0].appendSystemContext).toBeUndefined();+ expect(out[0].appendContext).toContain('<pinned_skills>');+ expect(out[0].appendContext).toContain('email-triage');+ expect(out[1].appendContext).not.toContain('<pinned_skills>');+ expect(out[2]).toEqual({ appendContext: expect.stringContaining('<pinned_skills>') });+ expect(out[4].appendContext).toContain('<pinned_skills>');+ expect(out[6]?.appendContext ?? '').not.toContain('<relevant_skills>');+ const lines = logLines(b);+ expect(lines.find((l) => l.outcome === 'skipped_sender')).toBeTruthy();+ expect(lines.at(-1)).toMatchObject({ arm: 'control', outcome: 'would_suggest' });+ });++ test('refuses a library writable by others, and survives a process-only NODE_OPTIONS flag', async () => {+ const b = box();+ await setup(b, ['--skill-loading', 'resolve']);+ const sha = readState(b).library_sha256;+ chmodSync(join(gbrainHome(b), 'lib', sha + '.mjs'), 0o666);+ const out = drive(b, [['turn', { text: 'triage the email inbox', id: 'm1' }]], '--max-old-space-size=256 --title=gateway');+ expect(out[0]).toBeNull();+ expect(logLines(b).map((l) => l.code)).toContain('skill_resolver_library_mismatch');+ });++ test('a stuck worker: every turn returns within the deadline, misses are logged, the worker is restarted', async () => {+ const b = box();+ await setup(b, ['--skill-loading', 'resolve']);+ const slow = 'export const GBRAIN_VERSION = "test"; export async function resolveSkills() { const end = Date.now() + 400; while (Date.now() < end) {} return { output: { block: "", suggestions: [], deduped: [], meta: {} } }; } export async function commitSessionAsync() {} export async function buildSkillIndex() {}\n';+ const sha = createHash('sha256').update(slow).digest('hex');+ writeFileSync(join(gbrainHome(b), 'lib', sha + '.mjs'), slow, { mode: 0o644 });+ const st = readState(b);+ st.library_sha256 = sha;+ writeFileSync(statePath(b), JSON.stringify(st));+ const t0 = Date.now();+ drive(b, [1, 2, 3].map((i) => ['turn', { text: 'triage the email inbox ' + i, id: 'm' + i }]));+ const outcomes = logLines(b).map((l) => l.code ?? l.outcome);+ expect(outcomes.filter((c) => c === 'skill_resolve_timeout').length).toBe(3);+ expect(outcomes).toContain('skill_resolver_worker_stuck');+ expect(logLines(b).filter((l) => l.outcome === 'timeout').every((l) => l.ms < 200)).toBe(true);+ expect(Date.now() - t0).toBeLessThan(30_000);+ });+});++describe.skipIf(!NODE)('doctor skill_resolver: the OpenClaw plugin', () => {+ test('reports the deadline-miss rate from the daily logs and warns above 5% once there are 20 turns', async () => {+ const b = box();+ expect((await setup(b, ['--skill-loading', 'shadow'])).exitCode).toBe(0);+ const dir = join(gbrainHome(b), 'skill-index', 'logs');+ mkdirSync(dir, { recursive: true });+ const at = new Date().toISOString();+ const file = join(dir, 'openclaw-' + at.slice(0, 10) + '.jsonl');+ const write = (n: number, outcome: string, extra = {}) => { for (let i = 0; i < n; i++) writeFileSync(file, JSON.stringify({ at, outcome, ...extra }) + '\n', { flag: 'a' }); };+ const old = new Date(Date.now() - 30 * 3600 * 1000).toISOString();+ writeFileSync(file, JSON.stringify({ at: old, outcome: 'timeout', code: 'skill_resolve_timeout' }) + '\n');+ write(20, 'would_suggest');+ write(3, 'skipped_provenance');+ write(1, 'timeout', { code: 'skill_resolve_timeout' });+ const doctor = async () => JSON.parse((await runCli(['doctor', '--only', 'skill_resolver', '--json'], { env: b.env })).stdout).checks.find((c: any) => c.name === 'skill_resolver');+ const ok = await doctor();+ expect(ok.status).toBe('ok');+ expect(ok.details.openclaw.recent).toMatchObject({ turns: 24, deadline_misses: 1, miss_rate: 1 / 21 });+ expect(ok.message).toContain('deadline misses 4.8%');+ write(1, 'timeout', { code: 'skill_resolve_timeout' });+ const warn = await doctor();+ expect(warn).toMatchObject({ status: 'warn', details: { code: 'skill_resolve_timeout' } });+ expect(warn.details.openclaw.recent.miss_rate).toBeCloseTo(2 / 22);+ });+});+