Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Pi: setup installs a skill-resolver extension

garrytan4297ad339752
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 75164a3097..52d9bce263 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,16 @@ identifiers and attribution are available in the pre-removal Git revision
- When the command fails, or lists none of the catalog's skills, nothing is filtered and setup says why. With no openclaw on PATH nothing changes.
- Run setup again after changing which skills an agent can use; the plugin reads the new list from its state file without a gateway reload.
+### Pi can turn on the skill resolver with one setup command
+
+**`gbrain setup pi --skill-loading resolve` installs a Pi extension that names the few installed skills that fit each request.** Pi lists every skill in its system prompt; with many skills the model picks from a long list, and now it also gets a short ranked one.
+
+- Setup builds the `pi-user` catalog from `$PI_CODING_AGENT_DIR/skills` and `~/.agents/skills`, and writes the extension to `$PI_CODING_AGENT_DIR/extensions/gbrain-skill-resolver/`. It runs one turn through the extension under Node and, when `pi` is on PATH, checks that `pi --help` lists `--gbrain-skill-resolver`; if Pi does not load it, setup exits 3 with `skill_resolver_plugin_not_installed`.
+- Before each user run, up to 3 suggestions go to the model as one hidden message with each skill's SKILL.md path. A skill already suggested in the session is not offered again until Pi compacts the conversation, also across `pi -p -c` runs. Pinned skills (`gbrain skills pin add <id> --catalog pi-user`) go in a system prompt section that stays the same from run to run. A pinned skill, or one Pi does not show the model, is never suggested.
+- With Pi 1.5.2 and a fake model server, a cold `pi -p` run waited 70 to 100 ms for suggestions (the budget is 150 ms on a cold run and 50 ms after), and a `pi -ne -p` run got nothing.
+- Pi started with extensions off (`pi --no-extensions`, or a program that embeds Pi with `noExtensions`, such as QM) gets no suggestions; setup and `gbrain doctor` say so. Project skill folders are not in the catalog.
+- `gbrain setup pi --skill-loading off` removes the extension and its state. Nothing opens a brain, so a keyless or brainless install stays as it is.
+
## [0.60.699.0] - 2026-11-12
### The Ubicloud gate VMs run a current git
diff --git a/docs/guides/skill-resolver.md b/docs/guides/skill-resolver.md
index 328b0e062a..d72b59f9ae 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 a
harness to call `gbrain skills resolve`, or turn on the hook lane with
- `gbrain setup <claude-code|codex|hermes> --skill-loading resolve` (OpenClaw: the
- plugin below). Setup writes nothing for it otherwise.
+ `gbrain setup <claude-code|codex|hermes> --skill-loading resolve` (OpenClaw and
+ Pi: the plugin and extension 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. No
network, no model, no clock, no randomness on the turn path.
@@ -41,7 +41,7 @@ One catalog per skill set. Names are 1-64 characters of `a-z`, `0-9`, `_` and
| Claude Code plugins | `gbrain skills index build --catalog claude-code-plugins --claude-plugins ~/.claude --harness claude-code` | The enabled user-scope plugins (`enabledPlugins` in `settings.json`, install paths from `plugins/installed_plugins.json`), each skill as `<plugin>:<skill>`. |
| Codex | `gbrain skills index build --catalog codex-user --dir ~/.codex/skills --harness codex` | Suggestion lines carry the SKILL.md path; Codex opens it. |
| Hermes, qm | `--dir <skills dir> --harness hermes` (or `qm`) | The id is the name the loader takes. |
-| Pi, Cursor | `--dir <skills dir> --harness pi` (or `cursor`) | Suggestion lines carry the SKILL.md path; the agent reads the file. |
+| Pi, Cursor | `--dir <skills dir> --harness pi` (or `cursor`) | Suggestion lines carry the SKILL.md path; the agent reads the file. For Pi, `gbrain setup pi --skill-loading resolve` builds `pi-user` for you (see below). |
| OpenClaw | `openclaw skills list --json \| gbrain skills index build --catalog openclaw-main --from-json - --dir <skills dir> --harness openclaw` | The list builds as is: the name is the id, and a skill OpenClaw hides from the model is skipped as ineligible. Each listed skill takes its body, path and triggers from the `--dir` skill of the same name; folder-only skills stay out. |
| Other adapters | `gbrain skills index build --catalog <name> --from-json - --harness <h>` | The adapter pipes its skill list (schema below) and owns rebuilds. |
| gbrain's own skills | `gbrain skills index build --catalog gbrain --bundled` | Rebuilt when the gbrain version changes. |
@@ -253,6 +253,55 @@ 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.
+## Pi extension
+
+Pi runs extensions inside its own Node process, so the resolver goes there as
+an extension instead of a per-turn CLI call.
+`gbrain setup pi --skill-loading resolve --gbrain-bin <abs path>`:
+
+1. Builds one catalog, `pi-user`, from the skill directories Pi loads in every
+ project: `$PI_CODING_AGENT_DIR/skills` (default `~/.pi/agent/skills`) and
+ `~/.agents/skills`. Project skills (`.pi/skills`, a project's
+ `.agents/skills`) are not in it.
+2. Writes the Node library to `~/.gbrain/lib/<sha256>.mjs` (the same one the
+ OpenClaw plugin uses), the state to `~/.gbrain/pi-skill-resolver.json`
+ (mode 0600) and the extension to
+ `$PI_CODING_AGENT_DIR/extensions/gbrain-skill-resolver/`.
+3. Runs one turn through the extension under Node, and, with `pi` on PATH,
+ checks that `pi --help` lists the extension's `--gbrain-skill-resolver`
+ flag. If it does not, Pi is not loading the extension: setup exits 3 with
+ `skill_resolver_plugin_not_installed` (check that `PI_CODING_AGENT_DIR` is
+ the same for Pi and for setup).
+
+Before each user run (Pi's `before_agent_start`) the extension sends up to 3
+suggestions with at least a description match as one hidden message right
+after the prompt, with each skill's SKILL.md path. Pi stores that message in
+the session and replays it on later turns, and a skill already suggested in a
+session is not suggested again, so each suggestion costs its tokens once.
+After a compaction (`session_compact`) the session starts fresh, so skills can
+be offered again. Pinned skills go in a system prompt section,
+`<gbrain_pinned_skills>`, on every run with the same text, so the prompt
+cache keeps working. Runs Pi starts itself (`messageType: custom`) get the pins
+but no suggestions. A pinned skill is never suggested, and neither is a skill
+Pi does not show the model on that run (not loaded, or
+`disable-model-invocation: true`).
+
+Ranking runs in a worker thread. A run waits at most 150 ms while the worker
+starts (the first run of a `pi -p` process) and 50 ms after that; a miss sends
+nothing and is logged as `timeout`. Measured with Pi 1.5.2 on a 4-core cloud
+machine, a cold `pi -p` run waited 70 to 100 ms, and the whole run took about
+150 ms longer than with `--no-extensions`. Each run appends one line (outcome,
+duration, suggested ids; never the prompt) to
+`skill-index/logs/pi-<date>.jsonl`, and `gbrain doctor --only skill_resolver`
+reports the extension, the library, the catalog and the last day's runs.
+
+Coverage is partial: Pi started with extensions off (`pi --no-extensions`, or
+a program that embeds Pi with `noExtensions`, as QM does) loads no extension,
+so those sessions get nothing, and doctor says so. `gbrain skills pin add <id>
+--catalog pi-user` updates the pins from Pi's next run. `gbrain setup pi
+--skill-loading off` removes the extension and the state; pins stay in
+config.json.
+
## Pinned skills
Pins are the operator's always-on skills for one catalog. gbrain ships none,
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 3c321d6b43..1171b30252 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -375,6 +375,7 @@ test/serve-http-github-webhook.test.ts handler wiring (source pin) 1 source-surf
test/serve-http-mcp-transport-cleanup.test.ts POST /mcp transport cleanup (#2844) 2 source-surface-helper
test/serve-http-metrics.test.ts serve-http.ts wiring (structural — the two defects of the original PR) 2 source-surface-helper
test/serve-stdin-eof-drain.test.ts serve-sync-runner stays off the boot path (#4409) 1 readFileSync
+test/setup-pi-skill-extension.test.ts (file-level) 5 readFileSync
test/setup-serves-several.test.ts gbrain setup --serves (spawned, PGLite) 11 readFileSync
test/setup-serves-several.test.ts labelling refuses or reports what it cannot make safe (pglite, repo-less) 8 readFileSync
test/setup.test.ts gbrain setup: setup migrations on the brain it creates (Cat 41 run 4) 3 readFileSync
diff --git a/src/commands/doctor/checks/skill-resolver-pi.ts b/src/commands/doctor/checks/skill-resolver-pi.ts
new file mode 100644
index 0000000000..088f854c5b
--- /dev/null
+++ b/src/commands/doctor/checks/skill-resolver-pi.ts
@@ -0,0 +1,87 @@
+/**
+ * The Pi half of doctor's `skill_resolver` check: the gbrain-skill-resolver
+ * extension (src/core/setup/pi-skill-extension.ts). It reports whether the
+ * extension files and the state exist, whether the library the state names is
+ * present with that sha256, the pi-user catalog's freshness and pin count,
+ * and from the last 24 hours of its daily logs the runs, outcomes and error
+ * codes. It always says that Pi started with extensions off (an embedder
+ * such as QM) gets no suggestions, since nothing on this host can see that.
+ *
+ * Read-only. Null when nothing of the extension 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 } from '../../../core/setup/openclaw-skill-plugin.ts';
+import { piSkillExtensionDir, readPiSkillState } from '../../../core/setup/pi-skill-extension.ts';
+
+const LOG_WINDOW_MS = 24 * 3600 * 1000;
+const LOG_READ_CAP = 4 * 1024 * 1024;
+
+export interface PiSkillView {
+ extension: 'present' | 'absent';
+ library: 'ok' | 'missing' | 'mismatch' | 'none';
+ gbrain_version: string | null;
+ catalog: { name: string; fresh: boolean | null; stale_reason: string | null; skills: number; pins: number } | null;
+ recent: { runs: number; outcomes: Record<string, number>; errors: Record<string, number> };
+ coverage: 'partial';
+ coverage_note: string;
+}
+
+function recentPi(home: string, now: number): PiSkillView['recent'] {
+ const recent: PiSkillView['recent'] = { runs: 0, outcomes: {}, errors: {} };
+ const dir = logsDir(home);
+ let files: string[] = [];
+ try { files = readdirSync(dir).filter((f) => /^pi-\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort().slice(-2); } catch { return recent; }
+ 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 };
+ 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 === 'rebuilt' || j.outcome === 'compaction') continue;
+ recent.runs++;
+ 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;
+ }
+ }
+ return recent;
+}
+
+export async function piSkillView(home: string, now = Date.now()): Promise<PiSkillView | null> {
+ const state = readPiSkillState(home);
+ const files = existsSync(join(piSkillExtensionDir(), 'index.js'));
+ if (!state && !files) return null;
+ let library: PiSkillView['library'] = 'none';
+ if (state) {
+ try { library = createHash('sha256').update(readFileSync(join(openclawSkillLibDir(home), `${state.library_sha256}.mjs`))).digest('hex') === state.library_sha256 ? 'ok' : 'mismatch'; } catch { library = 'missing'; }
+ }
+ let catalog: PiSkillView['catalog'] = null;
+ if (state) {
+ const s = existsSync(join(home, 'skill-index', state.catalog, 'receipt.json')) ? await catalogStatus(state.catalog, { home }) : null;
+ catalog = { name: state.catalog, fresh: s ? s.fresh : null, stale_reason: s?.stale_reason ?? (s ? null : 'missing'), skills: s?.receipt?.skill_count ?? 0, pins: state.pinned_ids.length };
+ }
+ return { extension: files ? 'present' : 'absent', library, gbrain_version: state?.gbrain_version ?? null, catalog, recent: recentPi(home, now),
+ coverage: 'partial', coverage_note: 'Pi started with extensions off (pi --no-extensions, or an embedder such as QM) gets no suggestions' };
+}
+
+/** The line for harness_wiring, and the first problem with its code, if any. */
+export function describePiSkillView(v: PiSkillView): { line: string; problem: { code: string; what: string } | null } {
+ const c = v.catalog;
+ const errs = Object.entries(v.recent.errors).map(([k, n]) => `${k} x${n}`).join(', ');
+ const line = `pi extension ${v.extension}, ${c ? `${c.skills} skills in ${c.name}, ${c.fresh ? 'fresh' : `stale (${c.stale_reason})`}, ${c.pins} pinned` : 'no state'}${v.recent.runs ? `, last 24h ${v.recent.runs} runs${errs ? ` with ${errs}` : ''}` : ''} (partial: ${v.coverage_note})`;
+ const problem = !c ? { code: 'skill_resolver_state_missing', what: 'the extension is present but its state file is missing, so it suggests nothing' }
+ : v.extension === 'absent' ? { code: 'skill_resolver_plugin_not_installed', what: 'the state is on but the extension is gone from Pi\'s extensions directory' }
+ : v.library === 'missing' ? { code: 'skill_resolver_library_missing', what: 'the library the state names is missing, so every run suggests nothing' }
+ : v.library === 'mismatch' ? { code: 'skill_resolver_library_mismatch', what: 'the library does not match the sha256 the state names, so the worker refuses it' }
+ : c.fresh === null ? { code: 'skill_index_missing', what: `the ${c.name} catalog is missing` } : null;
+ return { line, problem };
+}
diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.ts
index d8c4d96796..2b770afbb6 100644
--- a/src/commands/doctor/checks/skill-resolver.ts
+++ b/src/commands/doctor/checks/skill-resolver.ts
@@ -22,6 +22,7 @@ import { CLAUDE_PLUGINS_CATALOG, projectCatalogPrefix, userCatalogName } from '.
import { readResolverConfig, resolverHarnesses } from '../../../core/setup/skill-resolver-config.ts';
import { inspectSkillResolverHook, type ResolverHarness, type ResolverHookState } from '../../../core/setup/skill-resolver-hook.ts';
import { describeOpenclawSkill, openclawSkillView, type OpenclawSkillView } from './skill-resolver-openclaw.ts';
+import { describePiSkillView, piSkillView, type PiSkillView } from './skill-resolver-pi.ts';
const name = 'skill_resolver';
const HARNESSES: ResolverHarness[] = ['claude-code', 'codex', 'hermes'];
@@ -37,6 +38,8 @@ export interface SkillResolverView {
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;
+ /** The Pi extension (gbrain setup pi --skill-loading resolve), when any of it exists. */
+ pi?: PiSkillView;
}
function recentLane(home: string): SkillResolverView['recent'] | null {
@@ -79,8 +82,9 @@ export async function skillResolverView(home = configDir()): Promise<SkillResolv
harnesses.push({ harness, on: on.includes(harness), hook, catalogs: views });
}
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 pi = await piSkillView(home);
+ if (harnesses.length === 0 && !recent && !(cfg.state === 'ok' && on.length) && !openclaw && !pi) return null;
+ return { config: cfg.state, harnesses, recent: recent ?? { turns: 0, outcomes: {}, errors: {} }, ...(openclaw ? { openclaw } : {}), ...(pi ? { pi } : {}) };
}
const setupArgv = (harness: string) => ['gbrain', 'setup', harness, '--skill-loading', 'resolve'];
@@ -95,7 +99,8 @@ export function describeSkillResolver(v: SkillResolverView): string {
});
const errs = Object.entries(v.recent.errors).map(([c, n]) => `${c} x${n}`).join(', ');
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}.`;
+ const pi = v.pi ? `; ${describePiSkillView(v.pi).line}` : '';
+ return `Skill resolver: ${parts.join('; ') || (v.openclaw || v.pi ? 'no hook harness on' : 'no harness on')}${v.recent.turns ? `; last ${v.recent.turns} turns${errs ? ` with ${errs}` : ' without errors'}` : ''}${oc}${pi}.`;
}
export function skillResolverCheck(v: SkillResolverView | null): Check | null {
@@ -121,5 +126,11 @@ export function skillResolverCheck(v: SkillResolverView | null): Check | null {
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.' } };
}
+ const pi = v.pi ? describePiSkillView(v.pi).problem : null;
+ if (pi) {
+ return { name, status: 'warn', message: `${describeSkillResolver(v)} Pi: ${pi.what}.`, details: { ...details, code: pi.code },
+ fix: { argv: setupArgv('pi'), consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(name), docs: `docs/guides/skill-resolver.md#${pi.code}`,
+ why: 'Rebuilds the pi-user catalog, the library and the state, and rewrites the Pi extension; gbrain setup pi --skill-loading off removes it instead.' } };
+ }
return { name, status: 'ok', message: describeSkillResolver(v), details };
}
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 9f31fbc8bd..465c190ae8 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -27,6 +27,7 @@ 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 { describePiSkill, readPiSkillState, removePiSkillExtension, syncPiSkillExtension } from '../core/setup/pi-skill-extension.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';
@@ -187,6 +188,8 @@ Flags:
CODEX_HOME/skills; Hermes: $HERMES_HOME/skills) and adds a
separate per-turn hook that names the few skills that fit
each prompt (word match; nothing leaves the machine).
+ gbrain setup pi --skill-loading resolve does the same for
+ Pi with an extension in $PI_CODING_AGENT_DIR/extensions.
off removes what an earlier run wrote. The
choice is remembered; GBRAIN_SKILL_LOADING sets it too.
--skills-index-only Refresh every skills index recorded for this harness (its
@@ -302,8 +305,8 @@ function parseFlags(args: string[]): SetupFlags | string {
const envLoading = process.env[SKILL_LOADING_ENV]?.trim();
if (flagLoading === undefined && envLoading && envLoading !== 'resolve' && !isSkillLoading(envLoading)) return new InvalidSkillLoadingEnv(envLoading).message;
const openclaw = positionals[0] === 'openclaw';
- const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex' || positionals[0] === 'hermes' || openclaw;
- if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code, Codex, Hermes and OpenClaw (claude-code, codex, hermes, openclaw); other harnesses call gbrain skills resolve from their own adapter (docs/guides/skill-resolver.md)';
+ const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex' || positionals[0] === 'hermes' || positionals[0] === 'pi' || openclaw;
+ if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code, Codex, Hermes, OpenClaw and Pi (claude-code, codex, hermes, openclaw, pi); 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';
@@ -457,6 +460,7 @@ export async function runSetup(args: string[]): Promise<number> {
const flags = parsed;
const adapter = HARNESS_ADAPTERS.find((a) => a.id === flags.harness);
const mcpWired = flags.harness === 'claude-code' || flags.harness === 'codex';
+ if (flags.harness === 'pi') return runPiSetup(flags, out);
if (flags.skillsIndexOnly) return runSkillsIndexOnly(flags, out);
if ((flags.instructionsOnly && (isBrainFirstHarness(flags.harness) || adapter)) || (isBrainFirstHarness(flags.harness) && !mcpWired)) {
return runInstructionsOnly(flags, out);
@@ -1049,6 +1053,38 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
return code;
}
+/**
+ * gbrain setup pi: the skill resolver only (pi-skill-extension.ts). Setup
+ * does not register an MCP server or write instructions for Pi.
+ * --skill-loading resolve turns the extension on, off (or --remove) takes it
+ * out, --skills-index-only refreshes the library, catalog and state, and a
+ * bare run refreshes an extension that is on.
+ */
+async function runPiSetup(flags: SetupFlags, out: Out): Promise<number> {
+ const home = configDir();
+ const off = flags.skillResolver === 'off' || (flags.remove && flags.skillResolver !== 'on');
+ if (!off && flags.skillResolver !== 'on' && !readPiSkillState(home)) {
+ return refuse(opError('invalid_params', 'gbrain setup pi wires only the skill resolver, and it is not on. Pass --skill-loading resolve to turn it on.', 'Run gbrain setup pi --skill-loading resolve --dry-run to preview it.',
+ { docs: 'docs/guides/skill-resolver.md#pi-extension', fix: { argv: ['gbrain', 'setup', 'pi', '--skill-loading', 'resolve', '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews every write the Pi resolver setup would make; changes nothing.' } }), out);
+ }
+ const result = off ? removePiSkillExtension({ home, dryRun: flags.dryRun })
+ : await syncPiSkillExtension({ home, gbrainBin: flags.gbrainBin ?? resolveGbrainBin() ?? '', gbrainHomeEnv: process.env.GBRAIN_HOME?.trim() || null, dryRun: flags.dryRun, refreshOnly: flags.skillsIndexOnly });
+ if (out.json) {
+ await writeJsonDocument(`${JSON.stringify({ harness: 'pi', dry_run: flags.dryRun, remove: off, skill_resolver: result }, null, 2)}\n`, (t) => process.stdout.write(t));
+ return result?.error ? exitCodeForCode(result.error.code) : 0;
+ }
+ if (!result) say(out, 'The Pi skill resolver is not installed; nothing to remove.');
+ else for (const line of describePiSkill(result, flags.dryRun)) say(out, line);
+ if (result?.error) {
+ const e = result.error;
+ return refuse(opError(e.code, e.message, 'Fix the cause named above, then preview with gbrain setup pi --skill-loading resolve --dry-run.', {
+ docs: `docs/guides/skill-resolver.md#${e.code}`,
+ fix: { argv: ['gbrain', 'setup', 'pi', '--skill-loading', 'resolve', '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews every write the Pi resolver setup would make; changes nothing.' } }), out);
+ }
+ if (result && !off) say(out, 'Next: start a new Pi session; Pi loads extensions when it starts.');
+ return 0;
+}
+
/** --skills-index-only: refresh (or, with --skill-loading off, remove) the recorded skills indexes for one harness; nothing else is touched. */
async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number> {
const harness = flags.harness;
diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.ts
index c9e538f4ae..fff2b1688a 100644
--- a/src/commands/skill-resolver.ts
+++ b/src/commands/skill-resolver.ts
@@ -27,6 +27,7 @@ import { validCatalogName } from '../core/skills/resolver/paths.ts';
import { readResolverConfig, resolverHarnesses } 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';
+import { PI_SKILL_CATALOG, refreshPiPins } from '../core/setup/pi-skill-extension.ts';
import { HERMES_PINS_CATALOG, syncHermesPins } from '../core/setup/hermes-skill-pins.ts';
import { hermesHomeDir } from '../core/setup/skill-resolver-hook.ts';
@@ -347,16 +348,18 @@ async function runPin(args: string[]): Promise<void> {
}
writePins(read, catalog, pins);
}
- const rendered = renderPinnedBlock(pins, { harness: catalog.startsWith('openclaw-') ? 'openclaw' : catalog === HERMES_PINS_CATALOG ? 'hermes' : undefined, known: catalogSkillIds(home, catalog) });
+ const rendered = renderPinnedBlock(pins, { harness: catalog.startsWith('openclaw-') ? 'openclaw' : catalog === HERMES_PINS_CATALOG ? 'hermes' : catalog === PI_SKILL_CATALOG ? 'pi' : undefined, known: catalogSkillIds(home, catalog) });
const agents = sub === 'list' ? [] : refreshOpenclawPins(home);
+ const piUpdated = sub !== 'list' && catalog === PI_SKILL_CATALOG && refreshPiPins(home);
const hermesOn = catalog === HERMES_PINS_CATALOG && sub !== 'list' && resolverHarnesses(read.state === 'ok' ? read.doc : null).includes('hermes');
const soul = hermesOn ? syncHermesPins({ home, hermesHome: hermesHomeDir(), dryRun: false }) : null;
- const doc = { catalog, pins, rendered: rendered.ids, unknown: rendered.unknown, cut: rendered.cut, block_tokens: rendered.tokens, ...(agents.length ? { openclaw_agents_updated: agents } : {}), ...(soul ? { hermes_soul: soul } : {}) };
+ const doc = { catalog, pins, rendered: rendered.ids, unknown: rendered.unknown, cut: rendered.cut, block_tokens: rendered.tokens, ...(agents.length ? { openclaw_agents_updated: agents } : {}), ...(soul ? { hermes_soul: soul } : {}), ...(piUpdated ? { pi_state_updated: true } : {}) };
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.` : '',
+ piUpdated ? 'Pi uses the new pins from its next run.' : '',
soul ? `Hermes: ${soul.action} ${soul.detail}${soul.action === 'skip' ? '' : '; Hermes reads SOUL.md at session start'}.` : '',
].filter(Boolean).join('\n') + '\n');
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index cca0fb7231..e0d1fd25ad 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', '--filter', '--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', '--abort', '--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', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--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', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--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', '--filter', '--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-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--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', '--label-lowerings', '--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', '--members', '--members-file', '--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-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--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-stdio-member', '--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', '--preload', '--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', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--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', '--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', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--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', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--window', '--workers', '--working-tree', '--workspace', '--worktree', '--write-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--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', '--allow-without-owner', '--allowed-operations', '--anchor', '--applied', '--apply', '--apply-rewrites', '--approval-out', '--approved', '--as', '--assign-corpus', '--assume-unchanged', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--claude-plugins', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--config', '--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', '--email', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--env-file', '--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', '--filter', '--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', '--gbrain-skill-resolver', '--generation', '--get', '--get-all', '--get-regexp', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--heads', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--ignore-unmatch', '--images', '--import', '--include-ambiguous', '--include-covered', '--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', '--label-lowerings', '--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', '--members', '--members-file', '--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-extensions', '--no-extract', '--no-federated', '--no-filters', '--no-follow-tags', '--no-gpg-sign', '--no-hooks', '--no-index', '--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-stdio-member', '--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', '--preload', '--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', '--raw-only', '--reader-mode', '--readers', '--reason', '--reauth', '--rebase', '--rebuild', '--recommended', '--recurse-submodules', '--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', '--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', '--safe', '--sample', '--save', '--scan-secrets', '--scan-timeout', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--serves', '--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', '--skip-worktree', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--slugs-file', '--source', '--source-id', '--source-ids', '--sources', '--squash', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stdio-member', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--tags', '--take', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--tsconfig-override', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset', '--unset-all', '--unsettle', '--unshallow', '--untrack', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--where', '--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'],
@@ -85,7 +85,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--readers', '--rebase', '--require-clean', '--resolve', '--scan-secrets', '--scan-timeout', '--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', '--attest-read', '--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', '--embedding-dimensions', '--embedding-model', '--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', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--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', '--scan-secrets', '--scope', '--scopes', '--serves', '--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', '--where', '--window', '--workers', '--workspace', '--yes'],
+ 'maintain': ['--absolute-git-dir', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--attest-read', '--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', '--embedding-dimensions', '--embedding-model', '--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-extensions', '--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', '--prefix', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--raw-only', '--reader-mode', '--readers', '--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', '--scan-secrets', '--scope', '--scopes', '--serves', '--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', '--where', '--window', '--workers', '--workspace', '--yes'],
'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--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', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'],
'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'],
@@ -124,8 +124,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', '--as', '--attest-actor', '--attest-ops', '--attest-read', '--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', '--limit', '--log-full-params', '--may-act-for', '--member', '--members', '--members-file', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--no-stdio-member', '--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', '--serves', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--stdio-member', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--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', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--serves', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--workspace', '--yes'],
- 'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--only', '--out', '--previous', '--reset-session', '--routing', '--runtime', '--scope', '--session', '--shadow', '--shadow-log', '--skill-loading', '--source', '--text', '--top-k'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--harness', '--header', '--help', '--http', '--images', '--input-type', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--limit', '--link', '--live-fraction', '--mcp-only', '--mcp-url', '--member', '--members', '--members-file', '--name', '--no-capture', '--no-embedding', '--no-extensions', '--no-hooks', '--no-instructions', '--no-providers', '--no-stdio-member', '--oauth-client-id', '--oauth-client-secret', '--only', '--owner-sender', '--path', '--pglite', '--pins-route', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--serves', '--skill-loading', '--skills-index-only', '--source', '--source-id', '--source-ids', '--stale', '--stdio-member', '--surface', '--token', '--url', '--workspace', '--yes'],
+ 'skill-resolver': ['--accept-capabilities', '--agent', '--brain', '--bundled', '--catalog', '--claude-plugins', '--dir', '--exclude', '--expect-catalog', '--explain-target', '--fail-open', '--force', '--from-json', '--gbrain-bin', '--gbrain-skill-resolver', '--harness', '--help', '--input-json', '--input-type', '--json', '--line', '--link', '--load-hint', '--min-match', '--names-only', '--no-extensions', '--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'],
@@ -135,7 +135,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', '--reason', '--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', '--attest-read', '--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', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get-regexp', '--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', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--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', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--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', '--where', '--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', '--attest-read', '--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', '--filter', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--get-regexp', '--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-extensions', '--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', '--prefix', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--raw-only', '--reader-mode', '--readers', '--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', '--scan-secrets', '--scope', '--scopes', '--self-transfer', '--serial', '--serves', '--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', '--where', '--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/setup/openclaw-skill-plugin.ts b/src/core/setup/openclaw-skill-plugin.ts
index 94778d97c6..ce801eb67f 100644
--- a/src/core/setup/openclaw-skill-plugin.ts
+++ b/src/core/setup/openclaw-skill-plugin.ts
@@ -173,7 +173,7 @@ export function openclawSkillPluginRegistered(dir = openclawSkillPluginDir()): b
}
/** 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 }> {
+export async function ensureResolverLibrary(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));
@@ -322,7 +322,7 @@ export async function syncOpenclawSkillPlugin(opts: OpenclawSkillSyncOptions): P
}
let lib: { sha256: string; wrote: boolean; path: string };
- try { lib = await ensureLibrary(home, prior?.library_sha256 ?? null); } catch (e) {
+ try { lib = await ensureResolverLibrary(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.` });
}
diff --git a/src/core/setup/pi-skill-extension-code.ts b/src/core/setup/pi-skill-extension-code.ts
new file mode 100644
index 0000000000..9077c36d20
--- /dev/null
+++ b/src/core/setup/pi-skill-extension-code.ts
@@ -0,0 +1,265 @@
+/**
+ * pi-skill-extension-code.ts — the files of the generated Pi extension
+ * `gbrain-skill-resolver` (written by pi-skill-extension.ts into
+ * $PI_CODING_AGENT_DIR/extensions/gbrain-skill-resolver): index.js, the
+ * extension Pi loads into its own Node process, and worker.js, the same
+ * resolver worker thread the OpenClaw plugin runs (it rebuilds with harness
+ * pi and acknowledges each commit, so a one-shot `pi -p` can wait for it
+ * before it exits). Only paths and the gbrain bin are baked in, never pins
+ * or a library path.
+ */
+import { openclawSkillWorkerJs } from './openclaw-skill-plugin-code.ts';
+
+export const PI_SKILL_EXTENSION_CODE_VERSION = 1;
+
+export interface PiLoaderConstants { home: string; libDir: string; statePath: string; logDir: string; workerPath: string; gbrainBin: string; gbrainHomeEnv: string | null }
+
+const LOADER_JS = String.raw`// Managed by gbrain setup pi; a re-run rewrites this file. Remove: gbrain setup pi --skill-loading off
+// gbrain-skill-resolver for Pi: before each user run, up to a few installed skills that fit the prompt go to the
+// model as one hidden message, and the operator's pinned skills as a system prompt section. Settings come from a
+// data-only state file gbrain writes, re-read when it changes. Every failure lets the run go ahead unchanged, and
+// no handler waits longer than the deadline (longer on a run whose worker is still starting).
+import { Worker } from 'node:worker_threads';
+import { execFile } from 'node:child_process';
+import { mkdirSync, readFileSync, statSync } 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 WORKER_PATH = __WORKER__;
+const GBRAIN_BIN = __BIN__;
+const GBRAIN_HOME_ENV = __GBRAIN_HOME_ENV__;
+const FLAG = 'gbrain-skill-resolver';
+const SECTION = 'gbrain_pinned_skills';
+const MESSAGE_TYPE = 'gbrain-skill-suggestions';
+const TEST_DEADLINE_MS = Number(process.env.GBRAIN_TEST_PI_SKILL_DEADLINE_MS) || 0;
+const DEADLINE_MS = TEST_DEADLINE_MS || 50;
+const COLD_DEADLINE_MS = TEST_DEADLINE_MS || 150;
+const STUCK_AFTER = 3;
+
+let state = null;
+let stateMtime = -1;
+let worker = null;
+let workerSha = null;
+let warm = false;
+let timeouts = 0;
+let seq = 0;
+let skewChecked = false;
+let logReady = false;
+const waiters = new Map();
+const commits = new Map();
+const resetNext = new Set();
+
+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 && typeof s.catalog === 'string') state = s;
+ } catch { /* a damaged file keeps the last good state */ }
+ }
+ return state;
+}
+
+let logTail = Promise.resolve();
+
+function log(line) {
+ try {
+ const at = new Date();
+ if (!logReady) { mkdirSync(LOG_DIR, { recursive: true, mode: 0o700 }); logReady = true; }
+ const text = JSON.stringify({ at: at.toISOString(), ...line }) + '\n';
+ logTail = logTail.then(() => appendFile(join(LOG_DIR, 'pi-' + at.toISOString().slice(0, 10) + '.jsonl'), text, { mode: 0o600 })).catch(() => {});
+ } catch { /* logging never fails a run */ }
+}
+
+function dropWorker() {
+ const w = worker;
+ worker = null;
+ workerSha = null;
+ warm = false;
+ for (const [, done] of waiters) done(null);
+ waiters.clear();
+ for (const [, c] of commits) c.done();
+ commits.clear();
+ if (w) w.terminate().catch(() => {});
+}
+
+function ensureWorker(s) {
+ if (worker && workerSha === s.library_sha256) return worker;
+ if (worker) dropWorker();
+ let w;
+ try {
+ w = new Worker(WORKER_PATH, { execArgv: [], env: {}, workerData: { home: HOME, libDir: LIB_DIR, sha: s.library_sha256 } });
+ } catch {
+ log({ outcome: 'error', code: 'skill_resolver_worker_crash' });
+ return null;
+ }
+ w.on('message', (m) => {
+ if (m && m.type === 'warm') { warm = !m.code; 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; }
+ if (m && m.type === 'committed') { const c = commits.get(m.id); if (c) { commits.delete(m.id); c.done(); } 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(); } });
+ w.on('exit', () => { if (worker === w) { worker = null; workerSha = null; warm = false; } });
+ w.unref();
+ worker = w;
+ workerSha = s.library_sha256;
+ w.postMessage({ type: 'warm' });
+ return w;
+}
+
+function ask(w, msg, ms) {
+ const id = ++seq;
+ return new Promise((resolve) => {
+ const t = setTimeout(() => { waiters.delete(id); resolve({ id, late: true }); }, ms);
+ waiters.set(id, (m) => { clearTimeout(t); resolve(m ? { ...m, id } : { id, late: true }); });
+ w.postMessage({ ...msg, id });
+ });
+}
+
+function commit(w, id) {
+ let done = () => {};
+ const settled = new Promise((resolve) => { done = resolve; });
+ commits.set(id, { done, settled });
+ w.postMessage({ type: 'commit', id });
+}
+
+/** Wait, at most ms, for the session commits still in flight, so a one-shot run keeps its dedupe. */
+function flush(ms) {
+ if (commits.size === 0) return Promise.resolve();
+ return Promise.race([Promise.all([...commits.values()].map((c) => c.settled)), new Promise((resolve) => setTimeout(resolve, ms))]);
+}
+
+function sessionOf(ctx) {
+ try { const id = ctx && ctx.sessionManager && ctx.sessionManager.getSessionId(); if (typeof id === 'string' && id) return 'pi:' + id.slice(0, 200); } catch { /* no session manager */ }
+ return 'pi:default';
+}
+
+/** Catalog skills Pi does not show the model this run: absent from its loaded skills, or loaded with model invocation off. None when Pi names none of them. */
+function hiddenFrom(event, s) {
+ const loaded = event && event.systemPromptOptions && Array.isArray(event.systemPromptOptions.skills) ? event.systemPromptOptions.skills.filter((k) => k && typeof k.name === 'string') : null;
+ const ids = Array.isArray(s.catalog_ids) ? s.catalog_ids : [];
+ if (!loaded || !ids.length) return [];
+ const names = new Set(loaded.map((k) => k.name));
+ if (!ids.some((n) => names.has(n))) return [];
+ const visible = new Set(loaded.filter((k) => k.disableModelInvocation !== true).map((k) => k.name));
+ return ids.filter((n) => !visible.has(n));
+}
+
+function checkSkew(s) {
+ if (skewChecked) return;
+ skewChecked = true;
+ const env = { ...process.env, ...(GBRAIN_HOME_ENV ? { GBRAIN_HOME: GBRAIN_HOME_ENV } : {}) };
+ delete env.GBRAIN_SKILL_LOADING;
+ const probe = 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;
+ const child = execFile(GBRAIN_BIN, ['setup', 'pi', '--skills-index-only'], { timeout: 300_000, env }, () => {
+ const after = readState();
+ if (!after || after.gbrain_version !== v[0]) log({ outcome: 'error', code: 'skill_resolver_library_skew', cli: v[0], library: after ? after.gbrain_version : null });
+ });
+ if (child.unref) child.unref();
+ });
+ unrefChild(probe);
+}
+
+/** A one-shot pi -p exits without waiting for a version check it no longer needs. */
+function unrefChild(c) {
+ try { c.unref(); for (const st of [c.stdin, c.stdout, c.stderr]) if (st && st.unref) st.unref(); } catch { /* best effort */ }
+}
+
+async function beforeAgentStart(event, ctx) {
+ const s = readState();
+ if (!s || s.mode !== 'live') return undefined;
+ const t0 = Date.now();
+ const pins = typeof s.pinned_block === 'string' && s.pinned_block !== '';
+ const sections = event && event.systemPromptOptions && event.systemPromptOptions.sections;
+ if (pins && sections && typeof sections === 'object') sections[SECTION] = s.pinned_block;
+ const finish = (line, block) => {
+ log({ ms: Date.now() - t0, pins: pins ? (s.pinned_ids || []).length : 0, ...line });
+ return block ? { message: { customType: MESSAGE_TYPE, content: block, display: false } } : undefined;
+ };
+ if (event && event.messageType === 'custom') return finish({ outcome: 'skipped_custom' });
+ const text = event && typeof event.prompt === 'string' ? event.prompt.trim() : '';
+ if (!text) return finish({ outcome: 'skipped_empty' });
+ const w = ensureWorker(s);
+ if (!w) return finish({ outcome: 'error', code: 'skill_resolver_worker_unavailable' });
+ const key = sessionOf(ctx);
+ const reset = resetNext.delete(key);
+ const hidden = hiddenFrom(event, s);
+ const exclude = [...(Array.isArray(s.pinned_ids) ? s.pinned_ids : []), ...(Array.isArray(s.exclude_ids) ? s.exclude_ids : []), ...hidden].slice(0, 1024);
+ const deadline = warm ? DEADLINE_MS : COLD_DEADLINE_MS;
+ const input = { message: text, session_id: key, harness: 'pi', top_k: Number.isInteger(s.top_k) ? s.top_k : 3, exclude, ...(reset ? { reset_session: true } : {}) };
+ const reply = await ask(w, { type: 'resolve', input, catalog: s.catalog, deadlineMs: deadline - 5, floor: s.min_match || null, dirs: s.skill_dirs || [] }, deadline);
+ if (reply.late) {
+ if (reset) resetNext.add(key);
+ timeouts += 1;
+ if (timeouts >= STUCK_AFTER) { log({ outcome: 'error', code: 'skill_resolver_worker_stuck' }); timeouts = 0; dropWorker(); }
+ return finish({ outcome: 'timeout', code: 'skill_resolve_timeout', cold: deadline === COLD_DEADLINE_MS });
+ }
+ timeouts = 0;
+ if (reply.code && !reply.block) return finish({ outcome: 'error', code: reply.code });
+ const names = Array.isArray(reply.names) ? reply.names : [];
+ commit(w, reply.id);
+ const outcome = names.length ? 'suggested' : reply.no_skill_reason || (reply.budget_exhausted ? 'budget' : reply.deduped ? 'deduped' : 'no_match');
+ return finish({ outcome, suggested: names, strengths: reply.strengths, hidden: hidden.length, code: reply.code || null }, names.length ? reply.block : '');
+}
+
+export default function gbrainSkillResolver(pi) {
+ pi.registerFlag(FLAG, { description: 'gbrain skill resolver is loaded (managed by gbrain setup pi; this flag changes nothing)', type: 'boolean', default: false });
+ try { const s = readState(); if (s && s.mode === 'live') ensureWorker(s); } catch { /* the first run starts it */ }
+ pi.on('session_start', () => { try { const s = readState(); if (s && s.mode === 'live') { ensureWorker(s); checkSkew(s); } } catch { /* best effort */ } });
+ pi.on('before_agent_start', async (event, ctx) => { try { return await beforeAgentStart(event, ctx); } catch { return undefined; } });
+ pi.on('session_compact', (event, ctx) => { try { resetNext.add(sessionOf(ctx)); if (state) log({ outcome: 'compaction', reason: event && event.reason ? String(event.reason).slice(0, 20) : null }); } catch { /* best effort */ } });
+ pi.on('session_shutdown', async () => { try { await flush(500); await logTail; } catch { /* best effort */ } dropWorker(); });
+}
+
+/** One shadow turn through the worker (gbrain setup pi's self-test, under Node); commits nothing. */
+export async function selfTest(message) {
+ const s = readState();
+ if (!s) return { ok: false, code: 'skill_resolver_state_missing' };
+ const w = ensureWorker(s);
+ if (!w) return { ok: false, code: 'skill_resolver_worker_unavailable' };
+ const warmed = 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 (warmed.code) { dropWorker(); return { ok: false, code: warmed.code }; }
+ const t0 = Date.now();
+ const reply = await ask(w, { type: 'resolve', input: { message, harness: 'pi', top_k: Number.isInteger(s.top_k) ? s.top_k : 3, shadow: true }, catalog: s.catalog, deadlineMs: 1000, floor: s.min_match || null, dirs: [] }, 2000);
+ 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: warmed.version, suggested: reply.names || [] };
+}
+`;
+
+const OPENCLAW_REBUILD = "harness: 'openclaw' }, { home })";
+const OPENCLAW_COMMIT = "if (p && loaded.lib) loaded.lib.commitSessionAsync(home, p.key, p.delta).catch(() => {});\n return;";
+
+/** The OpenClaw worker with two changes: rebuilds use harness pi, and every commit is acknowledged once it settles. */
+export function piSkillWorkerJs(): string {
+ const base = openclawSkillWorkerJs();
+ if (!base.includes(OPENCLAW_REBUILD) || !base.includes(OPENCLAW_COMMIT)) throw new Error('the OpenClaw resolver worker changed shape; update piSkillWorkerJs');
+ return base
+ .replace('// Managed by gbrain setup openclaw (gbrain-skill-resolver worker thread)', '// Managed by gbrain setup pi (gbrain-skill-resolver worker thread)')
+ .replace(OPENCLAW_REBUILD, "harness: 'pi' }, { home })")
+ .replace(OPENCLAW_COMMIT, "const ack = () => parentPort.postMessage({ type: 'committed', id: m.id });\n if (p && loaded.lib) loaded.lib.commitSessionAsync(home, p.key, p.delta).then(ack, ack); else ack();\n return;");
+}
+
+export function piSkillLoaderJs(c: PiLoaderConstants): 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),
+ __WORKER__: JSON.stringify(c.workerPath), __BIN__: JSON.stringify(c.gbrainBin), __GBRAIN_HOME_ENV__: JSON.stringify(c.gbrainHomeEnv),
+ };
+ return LOADER_JS.replace(/__(HOME|LIB_DIR|STATE|LOG_DIR|WORKER|BIN|GBRAIN_HOME_ENV)__/g, (m) => values[m]!);
+}
diff --git a/src/core/setup/pi-skill-extension.ts b/src/core/setup/pi-skill-extension.ts
new file mode 100644
index 0000000000..1ac2af86bc
--- /dev/null
+++ b/src/core/setup/pi-skill-extension.ts
@@ -0,0 +1,236 @@
+/**
+ * pi-skill-extension.ts — gbrain setup pi --skill-loading resolve|off: the
+ * skill resolver for the Pi coding agent, as a generated Pi extension.
+ *
+ * Pi loads extensions into its own Node process from
+ * $PI_CODING_AGENT_DIR/extensions (default ~/.pi/agent). Setup builds one
+ * catalog, pi-user, from the skill directories Pi loads for every project
+ * ($PI_CODING_AGENT_DIR/skills and ~/.agents/skills), keeps the resolver
+ * library at ~/.gbrain/lib/<sha256>.mjs (the one the OpenClaw plugin uses),
+ * writes a data-only state file (~/.gbrain/pi-skill-resolver.json) and the
+ * extension (pi-skill-extension-code.ts). On each user run the extension
+ * sends up to top_k suggestions as one hidden message and the pinned block as
+ * a system prompt section; a skill Pi does not show the model that run is
+ * never suggested. Project skills (.pi/skills, .agents/skills) are not in the
+ * catalog. Pi run with extensions off (pi --no-extensions, or an embedder
+ * whose resource loader sets noExtensions) gets nothing, and setup says so.
+ *
+ * Setup proves the extension resolves under Node (self-test) and, with pi on
+ * PATH, that `pi --help` lists its --gbrain-skill-resolver flag. Nothing here
+ * opens a brain, so a brainless or keyless home stays as it is.
+ */
+import { existsSync, mkdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join, resolve } 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 { laneTurnSettings } from '../skills/resolver/config.ts';
+import { ensureResolverLibrary, openclawSkillLibDir } from './openclaw-skill-plugin.ts';
+import { piSkillLoaderJs, piSkillWorkerJs } from './pi-skill-extension-code.ts';
+import { catalogSkillIds, pinnedBlockFor } from './skill-pins.ts';
+import { readResolverConfig } from './skill-resolver-config.ts';
+
+export const PI_SKILL_EXTENSION_ID = 'gbrain-skill-resolver';
+export const PI_SKILL_CATALOG = 'pi-user';
+export const PI_SKILL_FLAG = '--gbrain-skill-resolver';
+const STATE_FILE = 'pi-skill-resolver.json';
+const TOP_K_DEFAULT = 3;
+const FLOOR_DEFAULT = 'description';
+const CATALOG_IDS_MAX = 1024;
+export const PI_NO_EXTENSIONS_NOTE = 'Pi started with extensions off (pi --no-extensions, or a program that embeds Pi with noExtensions, as QM does) loads no extension, so those sessions get no suggestions';
+
+export interface PiSkillState {
+ v: 1; gbrain_version: string; library_sha256: string; mode: 'live'; catalog: string; skill_dirs: string[];
+ top_k: number; min_match: string; exclude_ids: string[]; pinned_block: string; pinned_ids: string[]; catalog_ids: string[];
+}
+export interface PiSkillStep { step: 'catalog' | 'library' | 'state' | 'extension' | 'self-test' | 'verify'; action: 'write' | 'keep' | 'remove' | 'skip' | 'run'; detail: string }
+export interface PiSkillResult {
+ mode: 'live' | 'off';
+ steps: PiSkillStep[];
+ catalog: string;
+ skills: number;
+ pins: number;
+ notes: string[];
+ error?: { code: 'skill_resolver_setup_incomplete' | 'skill_resolver_plugin_not_installed' | 'skill_resolver_selftest_failed' | 'skill_resolver_config_invalid' | 'skill_source_unreadable'; message: string };
+}
+type Run = (argv: string[]) => { ok: boolean; output: string };
+export interface PiSkillDeps { piBin?: string | null; nodeBin?: string | null; run?: Run }
+
+const home0 = () => process.env.HOME?.trim() || homedir();
+export function piAgentDir(): string {
+ const v = process.env.PI_CODING_AGENT_DIR?.trim();
+ return v ? resolve(v.replace(/^~(?=\/|$)/, home0())) : join(home0(), '.pi', 'agent');
+}
+export const piSkillExtensionDir = (): string => join(piAgentDir(), 'extensions', PI_SKILL_EXTENSION_ID);
+export const piSkillStatePath = (home: string): string => join(home, STATE_FILE);
+/** The skill directories Pi loads in every project, whichever exist. */
+export function piSkillDirs(): string[] {
+ return [...new Set([join(piAgentDir(), 'skills'), join(home0(), '.agents', 'skills')].filter((d) => existsSync(d)))];
+}
+
+export function readPiSkillState(home: string): PiSkillState | null {
+ try {
+ const s = JSON.parse(readFileSync(piSkillStatePath(home), 'utf8')) as PiSkillState;
+ return s && s.v === 1 && typeof s.catalog === 'string' ? s : null;
+ } catch { return null; }
+}
+
+function defaultRun(argv: string[]): { ok: boolean; output: string } {
+ const r = bunSpawnSync(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env, timeout: 60_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 lastLine = (s: string) => s.trim().split('\n').at(-1) || 'no output';
+
+function extensionFiles(home: string, gbrainBin: string, gbrainHomeEnv: string | null): Record<string, string> {
+ const dir = piSkillExtensionDir();
+ return {
+ 'package.json': `${JSON.stringify({ name: PI_SKILL_EXTENSION_ID, version: '1.0.0', private: true, type: 'module', pi: { extensions: ['./index.js'] } }, null, 2)}\n`,
+ 'index.js': piSkillLoaderJs({ home, libDir: openclawSkillLibDir(home), statePath: piSkillStatePath(home), logDir: logsDir(home), workerPath: join(dir, 'worker.js'), gbrainBin, gbrainHomeEnv }),
+ 'worker.js': piSkillWorkerJs(),
+ };
+}
+
+/** Run one shadow turn through the generated extension under Node, the runtime Pi uses. */
+function selfTest(node: string, dir: string, message: string, run: Run): { ok: boolean; detail: string } {
+ const script = `import(${JSON.stringify(pathToFileURL(join(dir, 'index.js')).href)}).then((m) => m.selfTest(${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 extension under ${node}: ${doc.suggested?.length ?? 0} suggestion(s) in ${doc.ms ?? '?'} ms` };
+ return { ok: false, detail: `the extension's self-test under ${node} failed (${doc.code ?? lastLine(r.output)})` };
+}
+
+export interface PiSkillSyncOptions { home: string; gbrainBin: string; gbrainHomeEnv: string | null; dryRun: boolean; refreshOnly?: boolean; deps?: PiSkillDeps }
+
+/** Turn the Pi extension on, or refresh it (library, catalog and state only with refreshOnly). Never throws for an expected failure. */
+export async function syncPiSkillExtension(opts: PiSkillSyncOptions): Promise<PiSkillResult> {
+ const { home, dryRun } = opts;
+ const deps = opts.deps ?? {};
+ const run = deps.run ?? defaultRun;
+ const out: PiSkillResult = { mode: 'live', steps: [], catalog: PI_SKILL_CATALOG, skills: 0, pins: 0, notes: [] };
+ const fail = (code: NonNullable<PiSkillResult['error']>['code'], message: string): PiSkillResult => ({ ...out, error: { code, message } });
+ if (!opts.gbrainBin.startsWith('/')) return fail('skill_resolver_setup_incomplete', 'No absolute gbrain binary was found for the extension (Pi may start with no PATH that has gbrain); pass --gbrain-bin. Nothing was written.');
+ const dirs = piSkillDirs();
+ if (dirs.length === 0) return fail('skill_resolver_setup_incomplete', `No Pi skill directory exists (looked for ${join(piAgentDir(), 'skills')} and ${join(home0(), '.agents', 'skills')}). Add a skill to one of them, then run setup again. Nothing was written.`);
+ let lane: { top_k: number; min_match: string; exclude_ids: string[] };
+ try {
+ const read = readResolverConfig(home);
+ const section = read.state === 'ok' ? (read.doc.skills as { resolver?: Record<string, unknown> } | undefined)?.resolver ?? {} : {};
+ const s = laneTurnSettings(section, 'pi');
+ lane = { top_k: s.top_k ?? TOP_K_DEFAULT, min_match: s.min_match_strength ?? FLOOR_DEFAULT, exclude_ids: s.exclude ?? [] };
+ } catch (e) {
+ if (e instanceof ResolverError && e.code === 'skill_resolver_config_invalid') return fail('skill_resolver_config_invalid', `${e.message} Nothing was written.`);
+ throw e;
+ }
+ const prior = readPiSkillState(home);
+ const catalog = PI_SKILL_CATALOG;
+ 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;
+ let ids: string[];
+ if (fresh) ids = [...(catalogSkillIds(home, catalog) ?? [])];
+ else if (dryRun) ids = readDirSources(dirs).skills.map((s) => s.id);
+ else {
+ try { await buildSkillIndex({ catalog, dirs, harness: 'pi' }, { home }); } catch (e) {
+ return fail(e instanceof ResolverError && e.code === 'skill_source_unreadable' ? 'skill_source_unreadable' : 'skill_resolver_setup_incomplete', `The pi-user catalog could not be built (${e instanceof ResolverError ? e.code : (e as Error).message}). Nothing else was written.`);
+ }
+ ids = [...(catalogSkillIds(home, catalog) ?? [])];
+ }
+ out.skills = fresh ? status!.receipt!.skill_count : ids.length;
+ if (out.skills < 1) return fail('skill_resolver_setup_incomplete', `No model-invocable skill in ${dirs.join(', ')}. Add one, then run setup again.`);
+ out.steps.push({ step: 'catalog', action: fresh ? 'keep' : 'write', detail: `${catalog}: ${out.skills} skills from ${dirs.join(', ')}` });
+ const pins = dryRun ? { block: '', ids: [] as string[], unknown: [] as string[] } : pinnedBlockFor(home, catalog, 'pi');
+ out.pins = pins.ids.length;
+ if (pins.unknown.length) out.notes.push(`pinned skill(s) not in ${catalog}, left out of the block: ${pins.unknown.join(', ')} (skill_resolver_pin_unknown)`);
+ if (ids.length > CATALOG_IDS_MAX) out.notes.push(`${catalog} holds ${ids.length} skills; only the first ${CATALOG_IDS_MAX} are checked against the skills Pi loads each run`);
+ const dir = piSkillExtensionDir();
+ const files = extensionFiles(home, opts.gbrainBin, opts.gbrainHomeEnv);
+ const changed = Object.entries(files).some(([name, text]) => { try { return readFileSync(join(dir, name), 'utf8') !== text; } catch { return true; } });
+ 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: piSkillStatePath(home) });
+ if (!opts.refreshOnly) out.steps.push({ step: 'extension', action: changed ? 'write' : 'keep', detail: dir });
+ return out;
+ }
+ let lib: { sha256: string; wrote: boolean; path: string };
+ try { lib = await ensureResolverLibrary(home, prior?.library_sha256 ?? null); } catch (e) {
+ return fail('skill_resolver_setup_incomplete', `The skill resolver library could not be built (${(e as Error).message}). The catalog was built; the state file and the extension were not written.`);
+ }
+ out.steps.push({ step: 'library', action: lib.wrote ? 'write' : 'keep', detail: lib.path });
+ const state: PiSkillState = { v: 1, gbrain_version: VERSION, library_sha256: lib.sha256, mode: 'live', catalog, skill_dirs: dirs, top_k: lane.top_k, min_match: lane.min_match,
+ exclude_ids: lane.exclude_ids, pinned_block: pins.block, pinned_ids: pins.ids, catalog_ids: ids.slice(0, CATALOG_IDS_MAX) };
+ const stateText = `${JSON.stringify(state, null, 2)}\n`;
+ const stateChanged = (() => { try { return readFileSync(piSkillStatePath(home), 'utf8') !== stateText; } catch { return true; } })();
+ if (stateChanged) { mkdirSync(home, { recursive: true }); atomicWriteTextFile(piSkillStatePath(home), stateText, { freshMode: 0o600 }); }
+ out.steps.push({ step: 'state', action: stateChanged ? 'write' : 'keep', detail: piSkillStatePath(home) });
+ 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('skill_resolver_plugin_not_installed', `The extension could not be written to ${dir} (${(e as Error).message}). The library, catalog and state were written.`);
+ }
+ out.steps.push({ step: 'extension', action: changed ? 'write' : 'keep', detail: dir });
+ const node = deps.nodeBin !== undefined ? deps.nodeBin : which('node');
+ if (!node) out.notes.push('no node on PATH, so the extension self-test did not run; Pi runs it under its own Node');
+ else {
+ const message = (() => { try { return readDirSources(dirs).skills.find((s) => s.description)?.description ?? 'help'; } catch { return 'help'; } })();
+ const t = selfTest(node, dir, message, run);
+ if (!t.ok) return fail('skill_resolver_selftest_failed', `${t.detail}. The extension is written but would not resolve a run.`);
+ out.steps.push({ step: 'self-test', action: 'run', detail: t.detail });
+ }
+ const pi = deps.piBin !== undefined ? deps.piBin : which('pi');
+ if (!pi) out.notes.push(`no pi on PATH, so setup could not check that Pi loads the extension; \`pi --help\` lists ${PI_SKILL_FLAG} once it does`);
+ else {
+ const help = run([pi, '--help']);
+ if (!help.output.includes(PI_SKILL_FLAG)) return fail('skill_resolver_plugin_not_installed', `The extension was written to ${dir}, but \`${pi} --help\` does not list ${PI_SKILL_FLAG}, so this Pi does not load it (${lastLine(help.output)}). Check that PI_CODING_AGENT_DIR is the same for Pi and for this setup.`);
+ out.steps.push({ step: 'verify', action: 'run', detail: `${pi} --help lists ${PI_SKILL_FLAG}` });
+ }
+ out.notes.push(PI_NO_EXTENSIONS_NOTE);
+ return out;
+}
+
+/** Re-render the pinned block into the state file (gbrain skills pin add|remove); the extension reads it on its next run. True when it changed. */
+export function refreshPiPins(home: string): boolean {
+ const prior = readPiSkillState(home);
+ if (!prior) return false;
+ const pins = pinnedBlockFor(home, prior.catalog, 'pi');
+ if (pins.block === prior.pinned_block && JSON.stringify(pins.ids) === JSON.stringify(prior.pinned_ids)) return false;
+ atomicWriteTextFile(piSkillStatePath(home), `${JSON.stringify({ ...prior, pinned_block: pins.block, pinned_ids: pins.ids }, null, 2)}\n`, { freshMode: 0o600 });
+ return true;
+}
+
+/** Remove the extension directory and the state file (pins stay in config.json). Null when neither exists. */
+export function removePiSkillExtension(opts: { home: string; dryRun: boolean }): PiSkillResult | null {
+ const dir = piSkillExtensionDir();
+ const state = existsSync(piSkillStatePath(opts.home));
+ if (!state && !existsSync(dir)) return null;
+ const out: PiSkillResult = { mode: 'off', steps: [], catalog: PI_SKILL_CATALOG, skills: 0, pins: 0, notes: [] };
+ if (existsSync(dir)) {
+ if (!opts.dryRun) rmSync(dir, { recursive: true, force: true });
+ out.steps.push({ step: 'extension', action: 'remove', detail: dir });
+ }
+ if (state) {
+ if (!opts.dryRun) { try { unlinkSync(piSkillStatePath(opts.home)); } catch { /* gone */ } }
+ out.steps.push({ step: 'state', action: 'remove', detail: `${piSkillStatePath(opts.home)} (pins stay in config.json)` });
+ }
+ return out;
+}
+
+/** One human line per step, matching setup's step lines. */
+export function describePiSkill(r: PiSkillResult, 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}`);
+ if (r.mode === 'live' && !r.error) lines.push(`skill resolver (pi): on; ${r.skills} skills in ${r.catalog}; ${r.pins} pinned`);
+ for (const n of r.notes) lines.push(` note ${'resolver'.padEnd(7)} ${n}`);
+ return lines;
+}
diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.ts
index e602e96282..a8ebec711d 100644
--- a/test/cli-socket.test.ts
+++ b/test/cli-socket.test.ts
@@ -115,7 +115,7 @@ const NOT_READ_BEHAVIOR = new Set([
'GBRAIN_BIN', 'GBRAIN_BIN_OVERRIDE', 'GBRAIN_BINARY_VERSION', 'GBRAIN_ROOT', 'GBRAIN_VERIFY', 'GBRAIN_FRICTION_RUN_ID', 'GBRAIN_NOTABILITY_EVAL_REAL',
'GBRAIN_WHOKNOWS_FIXTURE_PATH', 'GBRAIN_PACK_STAT_TTL_MS', 'GBRAIN_EMBEDDING', 'GBRAIN_BASE_PATH_PREFIXES', 'GBRAIN_RECOVERED_RETRY',
'GBRAIN_SKILLS_NO_AUTOREBUILD', 'GBRAIN_TEST_SKILL_LANE_DEADLINE_MS', 'GBRAIN_TEST_SKILL_LANE_STALL', 'GBRAIN_VERSION',
- 'GBRAIN_HOME_ENV', 'GBRAIN_TEST_OPENCLAW_SKILL_DEADLINE_MS',
+ 'GBRAIN_HOME_ENV', 'GBRAIN_TEST_OPENCLAW_SKILL_DEADLINE_MS', 'GBRAIN_TEST_PI_SKILL_DEADLINE_MS',
]);
describe('identity', () => {
diff --git a/test/setup-pi-skill-extension.test.ts b/test/setup-pi-skill-extension.test.ts
new file mode 100644
index 0000000000..c81de22f86
--- /dev/null
+++ b/test/setup-pi-skill-extension.test.ts
@@ -0,0 +1,206 @@
+/**
+ * GBRA-435 PR 2: gbrain setup pi --skill-loading resolve|off and the generated
+ * Pi extension gbrain-skill-resolver (src/core/setup/pi-skill-extension.ts,
+ * pi-skill-extension-code.ts), plus its half of doctor's skill_resolver check.
+ *
+ * Protects: setup builds pi-user from $PI_CODING_AGENT_DIR/skills, writes the
+ * library, state and extension, self-tests it under Node and, with pi on
+ * PATH, proves Pi loads it (pi --help lists --gbrain-skill-resolver), or
+ * exits 3; under Node the extension sends suggestions as one hidden message
+ * with skill paths, puts the pins in a system prompt section on every run,
+ * suggests nothing on custom runs, never suggests a pinned skill or one Pi
+ * hides from the model, dedupes within a session until session_compact;
+ * off removes it; a brainless home stays brainless.
+ */
+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+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; agent: string; skills: string; bin: 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 pi: --help lists the extension's flag only when the extension file is where Pi loads it (and PI_NO_LOAD is unset). */
+const FAKE_PI = '#!/bin/sh\necho "$*" >> "$PI_CALLS"\nif [ "$1" = "--help" ]; then echo "Usage: pi [options]"; [ -z "$PI_NO_LOAD" ] && [ -f "$PI_CODING_AGENT_DIR/extensions/gbrain-skill-resolver/index.js" ] && printf "Extension CLI Flags:\\n --gbrain-skill-resolver gbrain\\n"; fi\nexit 0\n';
+
+function box(opts: { pi?: boolean; skills?: boolean } = {}): Box {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-pi-skill-'));
+ roots.push(root);
+ const home = join(root, 'home'), agent = join(root, 'pi-agent'), binDir = join(root, 'bin');
+ const skills = join(agent, 'skills');
+ mkdirSync(home, { recursive: true });
+ mkdirSync(binDir);
+ if (opts.skills !== false) {
+ 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');
+ } else mkdirSync(agent, { recursive: true });
+ const bin = join(binDir, 'gbrain');
+ writeFileSync(bin, '#!/bin/sh\nexec \'' + process.execPath + '\' --no-env-file \'' + CLI + '\' "$@"\n');
+ chmodSync(bin, 0o755);
+ if (opts.pi !== false) { writeFileSync(join(binDir, 'pi'), FAKE_PI); chmodSync(join(binDir, 'pi'), 0o755); }
+ const path = [binDir, NODE ? join(NODE, '..') : '', '/usr/bin', '/bin'].filter(Boolean).join(':');
+ return { root, home, agent, skills, bin, env: { HOME: home, GBRAIN_HOME: home, PI_CODING_AGENT_DIR: agent, PI_CALLS: join(root, 'pi-calls.log'), PATH: path, 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', 'pi', '--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 gbrainHome = (b: Box) => join(b.home, '.gbrain');
+const statePath = (b: Box) => join(gbrainHome(b), 'pi-skill-resolver.json');
+const extDir = (b: Box) => join(b.agent, 'extensions', 'gbrain-skill-resolver');
+const readState = (b: Box) => JSON.parse(readFileSync(statePath(b), 'utf8'));
+
+/** Load the generated extension under Node with a fake Pi api and run the steps. */
+function drive(b: Box, steps: unknown[]): any {
+ const script = join(b.root, 'drive.mjs');
+ writeFileSync(script, String.raw`
+import { pathToFileURL } from 'node:url';
+const [dir, stepsJson] = process.argv.slice(2);
+const m = await import(pathToFileURL(dir + '/index.js').href);
+const h = {};
+const flags = [];
+m.default({ on: (e, f) => { h[e] = f; }, registerFlag: (n) => flags.push(n) });
+const out = [{ flags, events: Object.keys(h).sort() }];
+for (const [kind, a] of JSON.parse(stepsJson)) {
+ const ctx = { sessionManager: { getSessionId: () => a.session || 's1' } };
+ if (kind === 'start') { await h.session_start({ type: 'session_start' }, ctx); out.push('started'); }
+ else if (kind === 'run') {
+ const event = { type: 'before_agent_start', messageType: a.custom ? 'custom' : 'user', ...(a.custom ? { message: { role: 'custom' } } : { prompt: a.prompt }), systemPromptOptions: { sections: {}, ...(a.skills ? { skills: a.skills } : {}) } };
+ const r = await h.before_agent_start(event, ctx);
+ out.push({ result: r ?? null, sections: event.systemPromptOptions.sections });
+ }
+ else if (kind === 'compact') { h.session_compact({ type: 'session_compact', reason: 'manual' }, ctx); out.push('compacted'); }
+ else if (kind === 'flush') { await h.session_shutdown({ type: 'session_shutdown' }, ctx); out.push('flushed'); }
+}
+console.log(JSON.stringify(out));
+process.exit(0);
+`);
+ const r = Bun.spawnSync([NODE!, script, extDir(b), JSON.stringify(steps)], { env: { PATH: b.env.PATH!, HOME: b.home, GBRAIN_TEST_PI_SKILL_DEADLINE_MS: '3000' }, 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); }
+}
+
+describe.skipIf(!NODE)('gbrain setup pi --skill-loading', () => {
+ test('resolve: catalog, library, state and extension, a self-test under Node and pi --help proving Pi loads it; a brainless home stays brainless', async () => {
+ const b = box();
+ const r = await setup(b, ['--skill-loading', 'resolve']);
+ expect(r.exitCode).toBe(0);
+ expect(r.resolver.error).toBeUndefined();
+ expect(r.resolver.steps.map((s: any) => s.step)).toEqual(['catalog', 'library', 'state', 'extension', 'self-test', 'verify']);
+ expect(r.resolver).toMatchObject({ mode: 'live', catalog: 'pi-user', skills: 3, pins: 0 });
+ expect(r.resolver.notes.join('\n')).toContain('extensions off');
+ const st = readState(b);
+ expect(st).toMatchObject({ v: 1, mode: 'live', catalog: 'pi-user', skill_dirs: [b.skills], top_k: 3, min_match: 'description' });
+ expect([...st.catalog_ids].sort()).toEqual(['calendar-sync', 'deploy-service', 'email-triage']);
+ expect(existsSync(join(gbrainHome(b), 'lib', st.library_sha256 + '.mjs'))).toBe(true);
+ for (const f of ['package.json', 'index.js', 'worker.js']) expect(existsSync(join(extDir(b), f))).toBe(true);
+ expect(JSON.parse(readFileSync(join(extDir(b), 'package.json'), 'utf8'))).toMatchObject({ type: 'module', pi: { extensions: ['./index.js'] } });
+ expect(readFileSync(join(extDir(b), 'worker.js'), 'utf8')).toContain("harness: 'pi' }");
+ expect(readFileSync(join(b.root, 'pi-calls.log'), 'utf8')).toContain('--help');
+ 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();
+ const again = await setup(b, []);
+ expect(again.exitCode).toBe(0);
+ expect(again.resolver.steps.find((s: any) => s.step === 'extension')).toMatchObject({ action: 'keep' });
+ });
+
+ test('the extension: one hidden message with paths, pins as a system section every run, nothing on custom runs, never a pinned or hidden skill, dedupe until session_compact', async () => {
+ const b = box();
+ expect((await setup(b, ['--skill-loading', 'resolve'])).exitCode).toBe(0);
+ const pin = await runCli(['skills', 'pin', 'add', 'calendar-sync', '--catalog', 'pi-user', '--json'], { env: b.env });
+ expect(pin.exitCode).toBe(0);
+ expect(JSON.parse(pin.stdout)).toMatchObject({ rendered: ['calendar-sync'], pi_state_updated: true });
+ expect(readState(b).pinned_ids).toEqual(['calendar-sync']);
+ const loaded = [
+ { name: 'deploy-service', disableModelInvocation: false },
+ { name: 'email-triage', disableModelInvocation: true },
+ { name: 'calendar-sync', disableModelInvocation: false },
+ ];
+ const prompt = 'deploy the service to production, triage the email inbox and sync the calendar';
+ const out = drive(b, [['start', {}], ['run', { prompt, skills: loaded }], ['flush', {}], ['run', { prompt, skills: loaded }], ['run', { custom: true }], ['compact', {}], ['run', { prompt, skills: loaded }], ['flush', {}]]);
+ expect(out[0].flags).toEqual(['gbrain-skill-resolver']);
+ expect(out[0].events).toEqual(['before_agent_start', 'session_compact', 'session_shutdown', 'session_start']);
+ const first = out[2];
+ expect(first.result.message).toMatchObject({ customType: 'gbrain-skill-suggestions', display: false });
+ expect(first.result.message.content).toContain('deploy-service');
+ expect(first.result.message.content).toContain(join('deploy-service', 'SKILL.md'));
+ expect(first.result.message.content).not.toContain('email-triage');
+ expect(first.result.message.content).not.toContain('calendar-sync');
+ expect(first.sections.gbrain_pinned_skills).toContain('calendar-sync');
+ expect(out[4].result).toBeNull();
+ expect(out[4].sections.gbrain_pinned_skills).toBe(first.sections.gbrain_pinned_skills);
+ expect(out[5].result).toBeNull();
+ expect(out[5].sections.gbrain_pinned_skills).toBe(first.sections.gbrain_pinned_skills);
+ expect(out[7].result.message.content).toContain('deploy-service');
+ const logs = readFileSync(join(gbrainHome(b), 'skill-index', 'logs', 'pi-' + new Date().toISOString().slice(0, 10) + '.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l));
+ expect(logs.map((l) => l.outcome)).toEqual(['suggested', 'deduped', 'skipped_custom', 'compaction', 'suggested']);
+ expect(logs[0]).toMatchObject({ hidden: 1, pins: 1 });
+ expect(JSON.stringify(logs)).not.toContain('production');
+ });
+
+ test('off removes the extension and the state; --dry-run writes nothing; a bare run with nothing on refuses', async () => {
+ const b = box();
+ const bare = await setup(b, []);
+ expect(bare.exitCode).not.toBe(0);
+ const dry = await setup(b, ['--skill-loading', 'resolve', '--dry-run']);
+ expect(dry.exitCode).toBe(0);
+ expect(existsSync(statePath(b))).toBe(false);
+ expect(existsSync(extDir(b))).toBe(false);
+ expect((await setup(b, ['--skill-loading', 'resolve'])).exitCode).toBe(0);
+ const off = await setup(b, ['--skill-loading', 'off']);
+ expect(off.exitCode).toBe(0);
+ expect(off.resolver.steps.map((s: any) => [s.step, s.action])).toEqual([['extension', 'remove'], ['state', 'remove']]);
+ expect(existsSync(statePath(b))).toBe(false);
+ expect(existsSync(extDir(b))).toBe(false);
+ });
+
+ test('no pi on PATH: on, with a note; a pi that does not load it: exit 3, skill_resolver_plugin_not_installed; no skill directory: refuses and writes nothing', async () => {
+ const none = box({ pi: false });
+ const r = await setup(none, ['--skill-loading', 'resolve']);
+ expect(r.exitCode).toBe(0);
+ expect(r.resolver.notes.join('\n')).toContain('no pi on PATH');
+ const b = box();
+ const broken = await setup(b, ['--skill-loading', 'resolve'], { PI_NO_LOAD: '1' });
+ expect(broken.exitCode).toBe(3);
+ expect(broken.resolver.error.code).toBe('skill_resolver_plugin_not_installed');
+ const empty = box({ skills: false });
+ const refused = await setup(empty, ['--skill-loading', 'resolve']);
+ expect(refused.exitCode).not.toBe(0);
+ expect(refused.resolver.error.code).toBe('skill_resolver_setup_incomplete');
+ expect(existsSync(statePath(empty))).toBe(false);
+ expect(existsSync(extDir(empty))).toBe(false);
+ });
+});
+
+describe.skipIf(!NODE)('doctor skill_resolver: the Pi extension', () => {
+ test('reports the extension, library and catalog as partial coverage, and warns when the extension is gone', async () => {
+ const b = box();
+ expect((await setup(b, ['--skill-loading', 'resolve'])).exitCode).toBe(0);
+ 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.pi).toMatchObject({ extension: 'present', library: 'ok', coverage: 'partial', catalog: { name: 'pi-user', fresh: true, skills: 3 } });
+ expect(ok.message).toContain('pi extension present');
+ rmSync(extDir(b), { recursive: true, force: true });
+ const warn = await doctor();
+ expect(warn).toMatchObject({ status: 'warn', details: { code: 'skill_resolver_plugin_not_installed' } });
+ expect(warn.fix.argv).toEqual(['gbrain', 'setup', 'pi', '--skill-loading', 'resolve']);
+ });
+});