Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Cursor: setup writes a project's pinned skills to a separate always-applied rule kept out of commits

garrytan2a95d31eee7f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52d9bce263..4a98949c49 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,15 @@ identifiers and attribution are available in the pre-removal Git revision
- 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.
+### Cursor can keep a project's pinned skills in front of the agent
+
+**`gbrain setup cursor --skill-loading resolve`, run in a project, gives Cursor the skills you pin for that project on every request.** Cursor gets no per-turn suggestions: none of its hooks can add text to the model's request.
+
+- Setup builds a catalog for the project from the skill folders Cursor loads there (`.agents`, `.cursor`, `.claude` and `.codex` skills in the project and your home directory) and prints its name. `gbrain skills pin add <id> --catalog <name>` checks the id against that catalog.
+- The pins go in their own always-applied rule, `.cursor/rules/gbrain-pinned-skills.mdc`, with each skill's SKILL.md path. In a git repository its path goes in `.git/info/exclude`, so it is never committed. Your own rules are never touched, and with no pins there is no file.
+- `gbrain doctor` reports Cursor as partial: pinned only, no per-turn hook, unverified. Nothing on this machine can see Cursor's request to confirm the rule reaches the model.
+- `gbrain setup cursor --skill-loading off` removes the rule and its exclude line; the pins stay in config.json. 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 d72b59f9ae..e9dfb3a6a7 100644
--- a/docs/guides/skill-resolver.md
+++ b/docs/guides/skill-resolver.md
@@ -302,6 +302,35 @@ so those sessions get nothing, and doctor says so. `gbrain skills pin add <id>
--skill-loading off` removes the extension and the state; pins stay in
config.json.
+## Cursor pinned skills
+
+Cursor gets pinned skills only. No Cursor hook can add text to the model's
+request, so there are no per-turn suggestions, and no check on this machine
+can see Cursor's request, so this route is unverified. Doctor reports Cursor
+as partial: pinned only, no per-turn hook, unverified.
+
+Run `gbrain setup cursor --skill-loading resolve` in the project:
+
+1. Setup builds the project's catalog, `cursor-project-<16 hex>`, from the skill
+ directories Cursor loads there: the project's `.agents/skills`,
+ `.cursor/skills`, `.claude/skills` and `.codex/skills`, then the same four
+ under your home directory. It records the project in
+ `~/.gbrain/cursor-skill-pins.json`.
+2. Pins come from `gbrain skills pin add <id> --catalog <that catalog>` (setup
+ prints the name). A pin the catalog does not hold is left out. With no pins
+ there is no rule file.
+3. The pins go in their own always-applied rule,
+ `.cursor/rules/gbrain-pinned-skills.mdc`, with each skill's SKILL.md path.
+ Your own rules and gbrain's brain-first rule are never touched, and a file
+ at that path that gbrain did not write is left alone (setup exits 1).
+4. Inside a git repository the rule's path goes in the repository's
+ `info/exclude` (never `.gitignore`), so it is never committed.
+
+`gbrain skills pin add|remove` rewrites the rule from any directory, and
+Cursor applies it from its next request. `gbrain setup cursor --skill-loading
+off` in the project removes the rule, its exclude line and the record; 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/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv
index 3f810b9b6b..3fab917c7f 100644
--- a/scripts/core-world-reads-baseline.tsv
+++ b/scripts/core-world-reads-baseline.tsv
@@ -1205,3 +1205,6 @@ src/core/setup/hermes-skill-pins.ts fs_import 1 GBRA-435 Hermes skill pins: read
src/core/setup/pi-skill-extension.ts fs_import 1 GBRA-435 Pi skill-resolver extension: setup writes the extension files under the Pi agent dir and its state under GBRAIN_HOME (no brain or engine is opened); stays
src/core/setup/pi-skill-extension.ts process_env 4 GBRA-435 Pi skill-resolver extension: HOME and PI_CODING_AGENT_DIR locate Pi's skills and extensions, PATH finds pi and node, and the env is handed to the pi child and the self-test; stays
src/core/setup/pi-skill-extension.ts spawn_import 1 GBRA-435 Pi skill-resolver extension: setup runs the Node self-test and pi --help to confirm Pi loaded the extension; stays
+src/core/setup/cursor-skill-pins.ts fs_import 1 GBRA-435 Cursor pinned skills: setup writes the project's pinned-skills rule, its git exclude line and the project record under GBRAIN_HOME (no brain or engine is opened); stays
+src/core/setup/cursor-skill-pins.ts process_env 1 GBRA-435 Cursor pinned skills: HOME locates the user-level skill directories Cursor loads; stays
+src/core/setup/cursor-skill-pins.ts spawn_import 1 GBRA-435 Cursor pinned skills: setup runs git rev-parse to find the repository's info/exclude; stays
diff --git a/src/commands/doctor/checks/skill-resolver-cursor.ts b/src/commands/doctor/checks/skill-resolver-cursor.ts
new file mode 100644
index 0000000000..ddfd1fffe2
--- /dev/null
+++ b/src/commands/doctor/checks/skill-resolver-cursor.ts
@@ -0,0 +1,42 @@
+/**
+ * The Cursor half of doctor's skill_resolver check: the pinned-skills rule
+ * gbrain setup cursor --skill-loading resolve writes per project
+ * (src/core/setup/cursor-skill-pins.ts). For each recorded project it reports
+ * whether the rule file is gbrain's and present, the project catalog's
+ * freshness and the pin count. Cursor's coverage is always partial: pinned
+ * only, no per-turn hook, and unverified, since nothing on this host can
+ * see Cursor's model request.
+ *
+ * Read-only. Null when no project is recorded.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { catalogStatus } from '../../../core/skills/resolver/build.ts';
+import { CURSOR_COVERAGE_NOTE, CURSOR_PINS_HEAD, cursorPinsRulePath, readCursorPinsState } from '../../../core/setup/cursor-skill-pins.ts';
+
+export interface CursorProjectView { project: string; catalog: string; rule: 'present' | 'absent' | 'foreign'; fresh: boolean | null; stale_reason: string | null; skills: number; pins: number }
+export interface CursorSkillView { projects: CursorProjectView[]; coverage: 'partial'; coverage_note: string }
+
+export async function cursorSkillView(home: string): Promise<CursorSkillView | null> {
+ const entries = Object.entries(readCursorPinsState(home).projects);
+ if (entries.length === 0) return null;
+ const projects: CursorProjectView[] = [];
+ for (const [project, rec] of entries) {
+ const path = cursorPinsRulePath(project);
+ const rule = !existsSync(path) ? 'absent' : (() => { try { return readFileSync(path, 'utf8').startsWith(CURSOR_PINS_HEAD) ? 'present' as const : 'foreign' as const; } catch { return 'foreign' as const; } })();
+ const s = existsSync(join(home, 'skill-index', rec.catalog, 'receipt.json')) ? await catalogStatus(rec.catalog, { home }) : null;
+ projects.push({ project, catalog: rec.catalog, rule, fresh: s ? s.fresh : null, stale_reason: s?.stale_reason ?? (s ? null : 'missing'), skills: s?.receipt?.skill_count ?? 0, pins: rec.pinned_ids.length });
+ }
+ return { projects, coverage: 'partial', coverage_note: CURSOR_COVERAGE_NOTE };
+}
+
+/** The line for harness_wiring, and the first problem with its code and project, if any. */
+export function describeCursorSkillView(v: CursorSkillView): { line: string; problem: { code: string; what: string; project: string } | null } {
+ const parts = v.projects.map((p) => p.project + ' ' + p.pins + ' pinned, rule ' + p.rule + ', ' + (p.fresh ? 'fresh' : 'stale (' + p.stale_reason + ')'));
+ const line = 'cursor pins in ' + v.projects.length + ' project(s): ' + parts.join('; ') + ' (partial: ' + v.coverage_note + ')';
+ const bad = v.projects.find((p) => p.fresh === null || (p.pins > 0 && p.rule !== 'present'));
+ const problem = !bad ? null
+ : bad.fresh === null ? { code: 'skill_index_missing', what: 'the ' + bad.catalog + ' catalog for ' + bad.project + ' is missing, so its pins cannot be checked', project: bad.project }
+ : { code: 'skill_resolver_plugin_not_installed', what: bad.rule === 'foreign' ? 'the pinned-skills rule in ' + bad.project + ' is not gbrain\'s any more' : 'the pinned-skills rule is gone from ' + bad.project, project: bad.project };
+ return { line, problem };
+}
diff --git a/src/commands/doctor/checks/skill-resolver.ts b/src/commands/doctor/checks/skill-resolver.ts
index 2b770afbb6..cf70746b48 100644
--- a/src/commands/doctor/checks/skill-resolver.ts
+++ b/src/commands/doctor/checks/skill-resolver.ts
@@ -23,6 +23,7 @@ import { readResolverConfig, resolverHarnesses } from '../../../core/setup/skill
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';
+import { cursorSkillView, describeCursorSkillView, type CursorSkillView } from './skill-resolver-cursor.ts';
const name = 'skill_resolver';
const HARNESSES: ResolverHarness[] = ['claude-code', 'codex', 'hermes'];
@@ -40,6 +41,8 @@ export interface SkillResolverView {
openclaw?: OpenclawSkillView;
/** The Pi extension (gbrain setup pi --skill-loading resolve), when any of it exists. */
pi?: PiSkillView;
+ /** Cursor's pinned-skills rules (gbrain setup cursor --skill-loading resolve), when a project is recorded. */
+ cursor?: CursorSkillView;
}
function recentLane(home: string): SkillResolverView['recent'] | null {
@@ -83,8 +86,9 @@ export async function skillResolverView(home = configDir()): Promise<SkillResolv
}
const openclaw = await openclawSkillView(home);
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 cursor = await cursorSkillView(home);
+ if (harnesses.length === 0 && !recent && !(cfg.state === 'ok' && on.length) && !openclaw && !pi && !cursor) return null;
+ return { config: cfg.state, harnesses, recent: recent ?? { turns: 0, outcomes: {}, errors: {} }, ...(openclaw ? { openclaw } : {}), ...(pi ? { pi } : {}), ...(cursor ? { cursor } : {}) };
}
const setupArgv = (harness: string) => ['gbrain', 'setup', harness, '--skill-loading', 'resolve'];
@@ -100,7 +104,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}` : '';
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}.`;
+ const cursor = v.cursor ? `; ${describeCursorSkillView(v.cursor).line}` : '';
+ return `Skill resolver: ${parts.join('; ') || (v.openclaw || v.pi || v.cursor ? 'no hook harness on' : 'no harness on')}${v.recent.turns ? `; last ${v.recent.turns} turns${errs ? ` with ${errs}` : ' without errors'}` : ''}${oc}${pi}${cursor}.`;
}
export function skillResolverCheck(v: SkillResolverView | null): Check | null {
@@ -132,5 +137,11 @@ export function skillResolverCheck(v: SkillResolverView | null): Check | null {
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.' } };
}
+ const cursor = v.cursor ? describeCursorSkillView(v.cursor).problem : null;
+ if (cursor) {
+ return { name, status: 'warn', message: `${describeSkillResolver(v)} Cursor: ${cursor.what}.`, details: { ...details, code: cursor.code },
+ fix: { argv: setupArgv('cursor'), consent: ['persistent_install'], actor: 'agent', requires_exclusive: false, verify: doctorVerify(name), docs: `docs/guides/skill-resolver.md#${cursor.code}`,
+ why: `Run it in ${cursor.project}: it rebuilds that project's catalog and rewrites its pinned-skills rule; gbrain setup cursor --skill-loading off there removes them instead.` } };
+ }
return { name, status: 'ok', message: describeSkillResolver(v), details };
}
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 465c190ae8..761609239b 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -43,6 +43,7 @@ import { parseStdioMemberFlag } from '../core/stdio-member-flag.ts';
import { isRegistrationSurface, isValidName, REGISTRATION_SURFACE, registrationAdvertise, stdioServeArgv } from '../core/mcp-registration.ts';
import { hookLauncherPath } from '../core/setup/hook-launcher.ts';
import { readResolverConfig, resolverHarnesses } from '../core/setup/skill-resolver-config.ts';
+import { describeCursorPins, readCursorPinsState, removeCursorSkillPins, syncCursorSkillPins, type CursorPinsResult } from '../core/setup/cursor-skill-pins.ts';
import { describeResolverSetup, removeSkillResolverSetup, syncSkillResolverSetup, type ResolverSetupResult } from '../core/setup/skill-resolver-setup.ts';
import type { ResolverHarness } from '../core/setup/skill-resolver-hook.ts';
import { isValidSourceId } from '../core/source-id.ts';
@@ -190,6 +191,10 @@ Flags:
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.
+ gbrain setup cursor --skill-loading resolve, run in a project,
+ gives Cursor that project's pinned skills only (gbrain skills
+ pin) in .cursor/rules/gbrain-pinned-skills.mdc, kept out of
+ commits; Cursor has no per-turn hook gbrain can use.
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
@@ -305,8 +310,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' || 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)';
+ const resolverHarness = positionals[0] === 'claude-code' || positionals[0] === 'codex' || positionals[0] === 'hermes' || positionals[0] === 'pi' || positionals[0] === 'cursor' || openclaw;
+ if (flagLoading === 'resolve' && !resolverHarness) return '--skill-loading resolve wires Claude Code, Codex, Hermes, OpenClaw and Pi, and pinned skills for Cursor (claude-code, codex, cursor, 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';
@@ -1033,9 +1038,10 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
const check = !off && !flags.dryRun && instructions?.decision.value === 'accepted' && !flags.noHooks && process.env.GBRAIN_HOOKS !== '0' && turnHook && turnHook.action !== 'print' && turnHook.action !== 'remove' ? verifyTurnHook(harness, { projectDir }) : null;
const resolver = harness === 'claude-code' || harness === 'codex' || harness === 'hermes' ? await resolverFor(harness, flags, flags.gbrainBin ?? resolveGbrainBin() ?? '') : null;
const skillPlugin = harness === 'openclaw' ? await openclawSkillFor(flags) : null;
- const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) || resolver?.error ? 1 : 0;
+ const cursorPins = harness === 'cursor' && projectDir ? await cursorPinsFor(flags, projectDir) : null;
+ const code = instructions?.action === 'preserve' || skillsFailed(skills) || (check && !check.ok) || resolver?.error || cursorPins?.error ? 1 : 0;
if (out.json) {
- await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, ...(resolver ? { skill_resolver: resolver } : {}), ...(skillPlugin ? { skill_resolver: skillPlugin } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
+ await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, remove: flags.remove, instructions_only: true, instructions, ...(turnHook ? { turn_hook: turnHook } : {}), ...(check ? { turn_hook_check: check } : {}), skills, ...(resolver ? { skill_resolver: resolver } : {}), ...(skillPlugin ? { skill_resolver: skillPlugin } : {}), ...(cursorPins ? { skill_pins: cursorPins } : {}), mcp }, null, 2)}\n`, (t) => process.stdout.write(t));
return skillPlugin?.error ? exitCodeForCode(skillPlugin.error.code) : code;
}
if (instructions) say(out, flags.remove ? describeBrainFirstOutcome(instructions, flags.dryRun) : describeInstructions(instructions, flags.dryRun));
@@ -1044,15 +1050,34 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
if (skills && skillsOutcomeShown(skills)) say(out, describeSkillsBlockOutcome(skills, flags.dryRun));
if (resolver) for (const line of describeResolverSetup(resolver, flags.dryRun)) say(out, line);
if (skillPlugin) for (const line of describeOpenclawSkill(skillPlugin, flags.dryRun)) say(out, line);
+ if (cursorPins) for (const line of describeCursorPins(cursorPins, flags.dryRun)) say(out, line);
if (check?.ok) say(out, ` verify ${'turn hook'.padEnd(7)} ${check.message}`);
if (mcp.setup === 'manual' && !flags.remove) say(out, `MCP: setup does not register ${adapter.label}'s MCP server. Follow ${adapter.guide} (one command), then start a new session.`);
if (!flags.remove && instructions?.decision.value === 'accepted') say(out, 'Next: start a new session; the harness reads its instruction file at session start.');
if (resolver?.error) return refuse(resolverRefusal(resolver), out);
if (skillPlugin?.error) return refuse(openclawSkillRefusal(skillPlugin), out);
+ if (cursorPins?.error) {
+ const e = cursorPins.error;
+ return refuse(opError(e.code, e.message, 'Fix the cause named above, then preview with gbrain setup cursor --skill-loading resolve --dry-run from the project directory.', {
+ docs: `docs/guides/skill-resolver.md#${e.code}`,
+ fix: { argv: ['gbrain', 'setup', 'cursor', '--skill-loading', 'resolve', '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews every write the Cursor pinned-skills setup would make in this project; changes nothing.' } }), out);
+ }
if (check && !check.ok) return refuse(turnHookNotLoaded(harness, check, rerun), out);
return code;
}
+/**
+ * Cursor's pinned skills for the project setup runs in (cursor-skill-pins.ts):
+ * --skill-loading resolve turns them on, off or --remove takes them out, and
+ * a bare run refreshes a project that already has them.
+ */
+async function cursorPinsFor(flags: SetupFlags, projectDir: string): Promise<CursorPinsResult | null> {
+ const home = configDir();
+ if (flags.remove || flags.skillResolver === 'off') return removeCursorSkillPins({ home, project: projectDir, dryRun: flags.dryRun });
+ if (flags.skillResolver !== 'on' && !readCursorPinsState(home).projects[projectDir]) return null;
+ return syncCursorSkillPins({ home, project: projectDir, dryRun: flags.dryRun });
+}
+
/**
* gbrain setup pi: the skill resolver only (pi-skill-extension.ts). Setup
* does not register an MCP server or write instructions for Pi.
diff --git a/src/commands/skill-resolver.ts b/src/commands/skill-resolver.ts
index fff2b1688a..d14ce946d3 100644
--- a/src/commands/skill-resolver.ts
+++ b/src/commands/skill-resolver.ts
@@ -29,6 +29,7 @@ import { catalogSkillIds, pinProblem, PINS_MAX, readPins, renderPinnedBlock, wri
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 { CURSOR_PINS_CATALOG_PREFIX, cursorPinnedBlock, refreshCursorPins } from '../core/setup/cursor-skill-pins.ts';
import { hermesHomeDir } from '../core/setup/skill-resolver-hook.ts';
const HELP_INDEX = `Usage: gbrain skills index <build|status|remove> [options]
@@ -348,12 +349,14 @@ 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' : catalog === PI_SKILL_CATALOG ? 'pi' : undefined, known: catalogSkillIds(home, catalog) });
+ const cursor = catalog.startsWith(CURSOR_PINS_CATALOG_PREFIX);
+ const rendered = cursor ? cursorPinnedBlock(home, catalog) : 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 } : {}), ...(piUpdated ? { pi_state_updated: true } : {}) };
+ const cursorRule = cursor && sub !== 'list' ? refreshCursorPins(home, catalog) : 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 } : {}), ...(piUpdated ? { pi_state_updated: true } : {}), ...(cursorRule ? { cursor_rule: { project: cursorRule.project, steps: cursorRule.steps, ...(cursorRule.error ? { error: cursorRule.error } : {}) } } : {}) };
if (json) { await write(`${JSON.stringify(doc)}\n`); return; }
await write([
pins.length ? `${catalog}: ${pins.length} pin(s)` : `${catalog}: no pins`,
@@ -361,6 +364,7 @@ async function runPin(args: string[]): Promise<void> {
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'}.` : '',
+ cursorRule ? (cursorRule.error ? `Cursor: ${cursorRule.error.message}` : `Cursor (${cursorRule.project}): ${cursorRule.steps.filter((x) => x.step === 'rule').map((x) => `${x.action} ${x.detail}`).join('; ')}; Cursor applies the rule from its next request.`) : '',
].filter(Boolean).join('\n') + '\n');
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e0d1fd25ad..bcc6268407 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -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', '--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'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--all-agents', '--as', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--catalog', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--gbrain-skill-resolver', '--git-path', '--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', '--show-toplevel', '--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', '--git-path', '--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', '--show-toplevel', '--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'],
diff --git a/src/core/setup/cursor-skill-pins.ts b/src/core/setup/cursor-skill-pins.ts
new file mode 100644
index 0000000000..613c05d09a
--- /dev/null
+++ b/src/core/setup/cursor-skill-pins.ts
@@ -0,0 +1,228 @@
+/**
+ * cursor-skill-pins.ts — gbrain setup cursor --skill-loading resolve|off:
+ * the operator's pinned skills for one Cursor project, and nothing per turn.
+ * No Cursor hook can add text to the model's request, so Cursor gets no
+ * suggestions; its pinned skills go in a separate, always-applied project
+ * rule that gbrain owns (.cursor/rules/gbrain-pinned-skills.mdc). The
+ * user's own rules and gbrain's brain-first rule are never touched.
+ *
+ * Setup builds the project's catalog, cursor-project-<sha16 of the project
+ * path>, from the skill directories Cursor loads there (the project's
+ * .agents, .cursor, .claude and .codex skills, then the same four under the
+ * home directory), and records the project in ~/.gbrain/cursor-skill-pins.json
+ * so gbrain skills pin can rewrite the rule from any directory. Pins are
+ * checked against that catalog, and each line names the skill's SKILL.md;
+ * with no pins there is no rule file. Inside a git repository the rule's path
+ * goes in the repository's info/exclude (never .gitignore), so it is never
+ * committed. Off removes the rule, that exclude line and the project's
+ * record; the pins stay in config.json.
+ *
+ * No check can see Cursor's request, so doctor reports Cursor as partial:
+ * pinned only, no per-turn hook, unverified. Nothing here opens a brain.
+ */
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { dirname, isAbsolute, join, relative, sep } from 'node:path';
+import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
+import { bunSpawnSync } from '../spawn.ts';
+import { buildSkillIndex, catalogStatus } from '../skills/resolver/build.ts';
+import { ResolverError } from '../skills/resolver/errors.ts';
+import { skillIndexRoot } from '../skills/resolver/paths.ts';
+import { readDirSources } from '../skills/resolver/sources.ts';
+import { catalogSkillPaths, PIN_BLOCK_TOKEN_CAP, readPins, renderPinnedBlock, type PinnedBlock } from './skill-pins.ts';
+import { readResolverConfig } from './skill-resolver-config.ts';
+
+export const CURSOR_PINS_CATALOG_PREFIX = 'cursor-project-';
+export const CURSOR_PINS_RULE = '.cursor/rules/gbrain-pinned-skills.mdc';
+export const CURSOR_PINS_HEAD = '---\ndescription: Pinned skills, managed by gbrain (gbrain setup cursor --skill-loading off removes this file)\nalwaysApply: true\n---\n';
+export const CURSOR_COVERAGE_NOTE = 'pinned only, no per-turn hook, unverified';
+const STATE_FILE = 'cursor-skill-pins.json';
+const SKILL_DIRS = ['.agents/skills', '.cursor/skills', '.claude/skills', '.codex/skills'];
+const PINNED_ONLY_NOTE = 'Cursor gets the pinned skills only: no Cursor hook can add text to the model\'s request, so there are no per-turn suggestions, and no check can see that request, so this is unverified';
+
+export interface CursorProjectRecord { catalog: string; skill_dirs: string[]; pinned_ids: string[] }
+export interface CursorPinsState { v: 1; projects: Record<string, CursorProjectRecord> }
+export interface CursorPinsStep { step: 'catalog' | 'rule' | 'exclude' | 'state'; action: 'write' | 'keep' | 'remove' | 'skip'; detail: string }
+export interface CursorPinsResult {
+ mode: 'pinned' | 'off';
+ project: string;
+ catalog: string;
+ skills: number;
+ pins: number;
+ steps: CursorPinsStep[];
+ notes: string[];
+ error?: { code: 'skill_resolver_setup_incomplete' | 'skill_source_unreadable'; message: string };
+}
+
+const home0 = () => process.env.HOME?.trim() || homedir();
+const real = (p: string) => { try { return realpathSync(p); } catch { return p; } };
+export const cursorPinsStatePath = (home: string): string => join(home, STATE_FILE);
+export const cursorPinsCatalog = (project: string): string => CURSOR_PINS_CATALOG_PREFIX + createHash('sha256').update(real(project)).digest('hex').slice(0, 16);
+export const cursorPinsRulePath = (project: string): string => join(project, ...CURSOR_PINS_RULE.split('/'));
+const ours = (path: string) => { try { return readFileSync(path, 'utf8').startsWith(CURSOR_PINS_HEAD); } catch { return false; } };
+
+/** The skill directories Cursor loads in this project, whichever exist, the project's first. */
+export function cursorSkillDirs(project: string): string[] {
+ const seen = new Set<string>();
+ return [...SKILL_DIRS.map((d) => join(project, d)), ...SKILL_DIRS.map((d) => join(home0(), d))].filter((d) => {
+ if (!existsSync(d) || seen.has(real(d))) return false;
+ seen.add(real(d));
+ return true;
+ });
+}
+
+export function readCursorPinsState(home: string): CursorPinsState {
+ try {
+ const s = JSON.parse(readFileSync(cursorPinsStatePath(home), 'utf8')) as CursorPinsState;
+ if (s && s.v === 1 && s.projects && typeof s.projects === 'object' && !Array.isArray(s.projects)) return s;
+ } catch { /* none yet */ }
+ return { v: 1, projects: {} };
+}
+
+function writeState(home: string, state: CursorPinsState): void {
+ if (Object.keys(state.projects).length === 0) { try { unlinkSync(cursorPinsStatePath(home)); } catch { /* gone */ } return; }
+ mkdirSync(home, { recursive: true });
+ atomicWriteTextFile(cursorPinsStatePath(home), JSON.stringify(state, null, 2) + '\n', { freshMode: 0o600 });
+}
+
+/** One catalog's pins, each line naming its SKILL.md (Cursor loads a skill by reading its file). */
+export function cursorPinnedBlock(home: string, catalog: string): PinnedBlock {
+ const paths = catalogSkillPaths(home, catalog);
+ return renderPinnedBlock(readPins(readResolverConfig(home), catalog), { harness: 'cursor', known: paths ? new Set(paths.keys()) : null, ...(paths ? { paths } : {}) });
+}
+
+/** The exclude file git reads for this project and the line that names the rule; null outside a git repository. */
+function gitExclude(project: string): { file: string; line: string } | null {
+ const r = bunSpawnSync(['git', '-C', project, 'rev-parse', '--show-toplevel', '--git-path', 'info/exclude'], { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', timeout: 10_000 });
+ if (r.exitCode !== 0) return null;
+ const [top, path] = r.stdout.toString().trim().split('\n');
+ if (!top || !path) return null;
+ const rel = relative(real(top), real(project)).split(sep).join('/');
+ return { file: isAbsolute(path) ? path : join(project, path), line: '/' + (rel ? rel + '/' : '') + CURSOR_PINS_RULE };
+}
+
+function addExclude(ex: { file: string; line: string }, dryRun: boolean): CursorPinsStep {
+ let text = '';
+ try { text = readFileSync(ex.file, 'utf8'); } catch { /* git has none yet */ }
+ if (text.split('\n').includes(ex.line)) return { step: 'exclude', action: 'keep', detail: ex.file + ' lists ' + ex.line };
+ if (!dryRun) {
+ mkdirSync(dirname(ex.file), { recursive: true });
+ atomicWriteTextFile(ex.file, text + (text && !text.endsWith('\n') ? '\n' : '') + ex.line + '\n');
+ }
+ return { step: 'exclude', action: 'write', detail: ex.line + ' in ' + ex.file + ', so the rule is never committed' };
+}
+
+function dropExclude(ex: { file: string; line: string }, dryRun: boolean): CursorPinsStep | null {
+ let text: string;
+ try { text = readFileSync(ex.file, 'utf8'); } catch { return null; }
+ const lines = text.split('\n');
+ const kept = lines.filter((l) => l !== ex.line);
+ if (kept.length === lines.length) return null;
+ if (!dryRun) atomicWriteTextFile(ex.file, kept.join('\n'));
+ return { step: 'exclude', action: 'remove', detail: ex.line + ' from ' + ex.file };
+}
+
+/** Write (or, with no pins, remove) the project's rule and its exclude line, and record the project. */
+function place(home: string, out: CursorPinsResult, dirs: string[], dryRun: boolean): CursorPinsResult {
+ const path = cursorPinsRulePath(out.project);
+ if (existsSync(path) && !ours(path)) return { ...out, error: { code: 'skill_resolver_setup_incomplete', message: path + ' exists and is not gbrain\'s, so it was left as it is and no pins were placed. Move it, then run setup again.' } };
+ const pins = cursorPinnedBlock(home, out.catalog);
+ out.pins = pins.ids.length;
+ if (pins.unknown.length) out.notes.push('pinned skill(s) not in ' + out.catalog + ', left out of the rule: ' + pins.unknown.join(', ') + ' (skill_resolver_pin_unknown)');
+ if (pins.cut.length) out.notes.push('pinned skill(s) past the ' + PIN_BLOCK_TOKEN_CAP + '-token cap, left out of the rule: ' + pins.cut.join(', '));
+ const ex = gitExclude(out.project);
+ if (!pins.block) {
+ if (existsSync(path)) {
+ if (!dryRun) unlinkSync(path);
+ out.steps.push({ step: 'rule', action: 'remove', detail: path + ' (no pins left)' });
+ const d = ex && dropExclude(ex, dryRun);
+ if (d) out.steps.push(d);
+ } else out.steps.push({ step: 'rule', action: 'skip', detail: 'no pins for ' + out.catalog + ', so no rule file; add one with gbrain skills pin add <skill-id> --catalog ' + out.catalog });
+ } else {
+ const text = CURSOR_PINS_HEAD + pins.block + '\n';
+ const same = (() => { try { return readFileSync(path, 'utf8') === text; } catch { return false; } })();
+ if (!same && !dryRun) { mkdirSync(dirname(path), { recursive: true }); atomicWriteTextFile(path, text); }
+ out.steps.push({ step: 'rule', action: same ? 'keep' : 'write', detail: path + ' (' + pins.ids.length + ' pinned, always applied)' });
+ if (ex) out.steps.push(addExclude(ex, dryRun));
+ else out.notes.push(out.project + ' is not in a git repository, so nothing was excluded from commits');
+ }
+ const state = readCursorPinsState(home);
+ const rec: CursorProjectRecord = { catalog: out.catalog, skill_dirs: dirs, pinned_ids: pins.ids };
+ const same = JSON.stringify(state.projects[out.project] ?? null) === JSON.stringify(rec);
+ if (!same && !dryRun) { state.projects[out.project] = rec; writeState(home, state); }
+ out.steps.push({ step: 'state', action: same ? 'keep' : 'write', detail: cursorPinsStatePath(home) });
+ return out;
+}
+
+/** Turn pinned skills on for one Cursor project (the realpath of the directory setup runs in), or refresh them. Never throws for an expected failure. */
+export async function syncCursorSkillPins(opts: { home: string; project: string; dryRun: boolean }): Promise<CursorPinsResult> {
+ const { home, project, dryRun } = opts;
+ const out: CursorPinsResult = { mode: 'pinned', project, catalog: cursorPinsCatalog(project), skills: 0, pins: 0, steps: [], notes: [] };
+ const fail = (code: NonNullable<CursorPinsResult['error']>['code'], message: string): CursorPinsResult => ({ ...out, error: { code, message } });
+ const dirs = cursorSkillDirs(project);
+ if (dirs.length === 0) return fail('skill_resolver_setup_incomplete', 'No skill directory Cursor loads exists for ' + project + ' (looked for ' + SKILL_DIRS.join(', ') + ' there and under ' + home0() + '). Add a skill to one of them, then run setup again. Nothing was written.');
+ const catalog = out.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;
+ try {
+ if (fresh) out.skills = status!.receipt!.skill_count;
+ else if (dryRun) out.skills = readDirSources(dirs).skills.length;
+ else {
+ await buildSkillIndex({ catalog, dirs, harness: 'cursor', scope: 'project' }, { home });
+ out.skills = catalogSkillPaths(home, catalog)?.size ?? 0;
+ }
+ } catch (e) {
+ return fail(e instanceof ResolverError && e.code === 'skill_source_unreadable' ? 'skill_source_unreadable' : 'skill_resolver_setup_incomplete', 'The ' + catalog + ' catalog could not be built (' + (e instanceof ResolverError ? e.code : (e as Error).message) + '). Nothing else was written.');
+ }
+ 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(', ') });
+ if (dryRun && !fresh) {
+ out.steps.push({ step: 'rule', action: 'write', detail: cursorPinsRulePath(project) + ' once ' + catalog + ' is built and has pins' });
+ out.steps.push({ step: 'state', action: 'write', detail: cursorPinsStatePath(home) });
+ out.notes.push(PINNED_ONLY_NOTE);
+ return out;
+ }
+ const placed = place(home, out, dirs, dryRun);
+ if (!placed.error) placed.notes.push(PINNED_ONLY_NOTE);
+ return placed;
+}
+
+/** Rewrite the rule of the project whose catalog this is (gbrain skills pin add|remove). Null when no project has it. */
+export function refreshCursorPins(home: string, catalog: string): CursorPinsResult | null {
+ const state = readCursorPinsState(home);
+ const project = Object.keys(state.projects).find((p) => state.projects[p]!.catalog === catalog);
+ if (!project) return null;
+ return place(home, { mode: 'pinned', project, catalog, skills: 0, pins: 0, steps: [], notes: [] }, state.projects[project]!.skill_dirs, false);
+}
+
+/** Remove the project's rule (only gbrain's), its exclude line and its record; pins stay in config.json. Null when none of them exists. */
+export function removeCursorSkillPins(opts: { home: string; project: string; dryRun: boolean }): CursorPinsResult | null {
+ const { home, project, dryRun } = opts;
+ const path = cursorPinsRulePath(project);
+ const state = readCursorPinsState(home);
+ const rec = state.projects[project];
+ const mine = existsSync(path) && ours(path);
+ const ex = gitExclude(project);
+ const exStep = ex ? dropExclude(ex, dryRun) : null;
+ if (!rec && !mine && !exStep) return null;
+ const out: CursorPinsResult = { mode: 'off', project, catalog: rec?.catalog ?? cursorPinsCatalog(project), skills: 0, pins: 0, steps: [], notes: [] };
+ if (mine) {
+ if (!dryRun) unlinkSync(path);
+ out.steps.push({ step: 'rule', action: 'remove', detail: path });
+ } else if (existsSync(path)) out.notes.push(path + ' is not gbrain\'s, so it was left as it is');
+ if (exStep) out.steps.push(exStep);
+ if (rec) {
+ if (!dryRun) { delete state.projects[project]; writeState(home, state); }
+ out.steps.push({ step: 'state', action: 'remove', detail: project + ' from ' + cursorPinsStatePath(home) + ' (pins stay in config.json)' });
+ }
+ return out;
+}
+
+/** One human line per step, matching setup's step lines. */
+export function describeCursorPins(r: CursorPinsResult, dryRun: boolean): string[] {
+ const lines = r.steps.map((s) => ' ' + (dryRun && (s.action === 'write' || s.action === 'remove') ? 'would ' + s.action : s.action).padEnd(8) + ' ' + 'pins'.padEnd(7) + ' ' + s.step + ': ' + s.detail);
+ if (r.mode === 'pinned' && !r.error) lines.push('skill pins (cursor): ' + r.pins + ' pinned from ' + r.catalog + ' (' + r.skills + ' skills); ' + CURSOR_COVERAGE_NOTE);
+ for (const n of r.notes) lines.push(' note ' + 'pins'.padEnd(7) + ' ' + n);
+ return lines;
+}
diff --git a/src/core/setup/skill-pins.ts b/src/core/setup/skill-pins.ts
index eed7f2b96c..217ca8c9c2 100644
--- a/src/core/setup/skill-pins.ts
+++ b/src/core/setup/skill-pins.ts
@@ -74,14 +74,20 @@ export function writePins(read: Exclude<ResolverConfigRead, { state: 'unreadable
/** The skill ids a built catalog holds, or null when it has no readable index. */
export function catalogSkillIds(home: string, catalog: string): Set<string> | null {
+ const paths = catalogSkillPaths(home, catalog);
+ return paths ? new Set(paths.keys()) : null;
+}
+
+/** Each skill id a built catalog holds with its SKILL.md path ('' when the index has none), or null when it has no readable index. */
+export function catalogSkillPaths(home: string, catalog: string): Map<string, string> | null {
if (!validCatalogName(catalog)) return null;
const path = catalogFile(home, catalog, 'index.bin');
if (!existsSync(path)) return null;
let ix: IndexReader | null = null;
try {
ix = IndexReader.open(path);
- const ids = new Set<string>();
- for (let d = 0; d < ix.n; d++) ids.add(ix.meta(d).id);
+ const ids = new Map<string, string>();
+ for (let d = 0; d < ix.n; d++) { const m = ix.meta(d); ids.set(m.id, m.path ?? ''); }
return ids;
} catch { return null; } finally { ix?.close(); }
}
@@ -90,13 +96,15 @@ export function catalogSkillIds(home: string, catalog: string): Set<string> | nu
* The pinned block for one harness. With `known` set, a pin the catalog does
* not hold is left out and listed in `unknown`; with null (no index yet)
* nothing renders, because an unchecked name must never reach the model.
+ * With paths, each line also names the skill's SKILL.md, for a harness
+ * that loads a skill by reading its file.
*/
-export function renderPinnedBlock(pins: readonly Pin[], opts: { harness?: string; known: Set<string> | null; cap?: number }): PinnedBlock {
+export function renderPinnedBlock(pins: readonly Pin[], opts: { harness?: string; known: Set<string> | null; cap?: number; paths?: ReadonlyMap<string, string> }): PinnedBlock {
const cap = opts.cap ?? PIN_BLOCK_TOKEN_CAP;
if (!opts.known) return { block: '', tokens: 0, ids: [], unknown: pins.map((p) => p.name), cut: [] };
const valid = pins.filter((p) => opts.known!.has(p.name));
const unknown = pins.filter((p) => !opts.known!.has(p.name)).map((p) => p.name);
- const lines = valid.map((p) => `- id: ${quoted(p.name)}${p.line ? ` when: ${quoted(p.line)}` : ''}`);
+ const lines = valid.map((p) => `- id: ${quoted(p.name)}${p.line ? ` when: ${quoted(p.line)}` : ''}${opts.paths?.get(p.name) ? ` path: ${quoted(opts.paths.get(p.name)!)}` : ''}`);
const head = `Always-available skills, chosen by this agent's operator, whether or not a skill list shows them. ${loadLine(opts.harness)}`;
for (let kept = lines.length; kept > 0; kept--) {
const block = ['<pinned_skills>', head, ...lines.slice(0, kept), '</pinned_skills>'].join('\n');
diff --git a/test/setup-cursor-skill-pins.test.ts b/test/setup-cursor-skill-pins.test.ts
new file mode 100644
index 0000000000..3774e10839
--- /dev/null
+++ b/test/setup-cursor-skill-pins.test.ts
@@ -0,0 +1,213 @@
+/**
+ * GBRA-435 PR 3: gbrain setup cursor --skill-loading resolve|off, Cursor's
+ * pinned skills only (src/core/setup/cursor-skill-pins.ts), plus its half
+ * of doctor's skill_resolver check.
+ *
+ * Protects: setup run in a project builds that project's catalog from the
+ * skill directories Cursor loads and records the project; with no pins there
+ * is no rule file; gbrain skills pin add writes a separate always-applied
+ * rule (.cursor/rules/gbrain-pinned-skills.mdc) that names each pinned
+ * skill's SKILL.md and leaves out a pin the catalog does not hold; inside git
+ * the rule's path goes in info/exclude (from a subdirectory too), so it is
+ * never committed; a rule file gbrain did not write is never touched; off
+ * removes the rule, the exclude line and the record, keeping the pins, the
+ * user's exclude lines and the brain-first rule; doctor reports Cursor as
+ * partial (pinned only, no per-turn hook, unverified); a brainless home
+ * stays brainless and a plain gbrain setup cursor writes no pins.
+ */
+import { afterAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+import { cursorSkillView, describeCursorSkillView } from '../src/commands/doctor/checks/skill-resolver-cursor.ts';
+
+setDefaultTimeout(120_000);
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+const RULE = join('.cursor', 'rules', 'gbrain-pinned-skills.mdc');
+const BRAIN_FIRST = join('.cursor', 'rules', 'gbrain-brain-first.mdc');
+
+interface Box { root: string; home: string; repo: string; project: 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');
+}
+
+function git(cwd: string, ...args: string[]): string {
+ const r = Bun.spawnSync(['git', ...args], { cwd, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' } });
+ return r.stdout.toString();
+}
+
+function box(opts: { git?: boolean; sub?: string; skills?: boolean } = {}): Box {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-cursor-pins-')));
+ roots.push(root);
+ const home = join(root, 'home');
+ const repo = join(root, 'repo');
+ const project = opts.sub ? join(repo, opts.sub) : repo;
+ mkdirSync(home, { recursive: true });
+ mkdirSync(project, { recursive: true });
+ if (opts.git !== false) git(repo, 'init', '-q');
+ if (opts.skills !== false) {
+ skill(join(project, '.cursor', 'skills'), 'deploy-service', 'Use when you deploy a service to production');
+ skill(join(project, '.agents', 'skills'), 'email-triage', 'Use when you triage the email inbox');
+ }
+ return { root, home, repo, project, env: { HOME: home, GBRAIN_HOME: home, GBRAIN_SKILL_LOADING: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' } };
+}
+
+async function cli(b: Box, args: string[]) {
+ const r = await runCli([...args, '--json'], { env: b.env, cwd: b.project, timeoutMs: 110_000 });
+ let doc: any = null;
+ try { doc = JSON.parse(r.stdout); } catch { doc = null; }
+ return { ...r, doc };
+}
+const setup = (b: Box, extra: string[]) => cli(b, ['setup', 'cursor', ...extra]);
+const gbrainHome = (b: Box) => join(b.home, '.gbrain');
+const statePath = (b: Box) => join(gbrainHome(b), 'cursor-skill-pins.json');
+const rulePath = (b: Box) => join(b.project, RULE);
+const exclude = (b: Box) => { try { return readFileSync(join(b.repo, '.git', 'info', 'exclude'), 'utf8'); } catch { return ''; } };
+
+describe('gbrain setup cursor --skill-loading resolve (pinned skills only)', () => {
+ test('resolve records the project catalog and writes no rule while there are no pins; a brainless home stays brainless', async () => {
+ const b = box();
+ const r = await setup(b, ['--skill-loading', 'resolve']);
+ expect(r.exitCode).toBe(0);
+ const p = r.doc.skill_pins;
+ expect(p.error).toBeUndefined();
+ expect(p).toMatchObject({ mode: 'pinned', project: b.project, skills: 2, pins: 0 });
+ expect(p.catalog).toMatch(/^cursor-project-[0-9a-f]{16}$/);
+ expect(p.steps.find((s: any) => s.step === 'rule')).toMatchObject({ action: 'skip' });
+ expect(p.notes.join('\n')).toContain('no per-turn suggestions');
+ expect(existsSync(rulePath(b))).toBe(false);
+ expect(existsSync(join(b.project, BRAIN_FIRST))).toBe(true);
+ const st = JSON.parse(readFileSync(statePath(b), 'utf8'));
+ expect(st.projects[b.project]).toMatchObject({ catalog: p.catalog, pinned_ids: [] });
+ expect(st.projects[b.project].skill_dirs).toEqual([join(b.project, '.agents', 'skills'), join(b.project, '.cursor', 'skills')]);
+ 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();
+ });
+
+ test('skills pin add writes an always-applied rule with each SKILL.md path, excluded from git; setup again keeps the same bytes', async () => {
+ const b = box();
+ const catalog = (await setup(b, ['--skill-loading', 'resolve'])).doc.skill_pins.catalog;
+ const add = await cli(b, ['skills', 'pin', 'add', 'deploy-service', '--catalog', catalog, '--line', 'deploys and rollbacks']);
+ expect(add.exitCode).toBe(0);
+ expect(add.doc.cursor_rule.steps.find((s: any) => s.step === 'rule')).toMatchObject({ action: 'write' });
+ const rule = readFileSync(rulePath(b), 'utf8');
+ expect(rule.startsWith('---\ndescription: Pinned skills, managed by gbrain')).toBe(true);
+ expect(rule).toContain('alwaysApply: true\n---\n<pinned_skills>\n');
+ expect(rule).toContain('- id: "deploy-service" when: "deploys and rollbacks" path: "' + join(b.project, '.cursor', 'skills', 'deploy-service', 'SKILL.md') + '"');
+ expect(rule).toContain('read the SKILL.md at its path');
+ expect(exclude(b).split('\n')).toContain('/' + RULE);
+ writeFileSync(join(b.project, '.cursor', 'rules', 'team.mdc'), 'a rule the user commits\n');
+ const status = git(b.repo, 'status', '--porcelain', '--untracked-files=all');
+ expect(status).not.toContain('gbrain-pinned-skills.mdc');
+ expect(status).toContain('.cursor/rules/team.mdc');
+ const again = await setup(b, []);
+ expect(again.exitCode).toBe(0);
+ expect(again.doc.skill_pins.steps.filter((s: any) => s.step !== 'catalog').map((s: any) => [s.step, s.action])).toEqual([['rule', 'keep'], ['exclude', 'keep'], ['state', 'keep']]);
+ expect(readFileSync(rulePath(b), 'utf8')).toBe(rule);
+ expect(exclude(b).split('\n').filter((l) => l === '/' + RULE)).toHaveLength(1);
+ const remove = await cli(b, ['skills', 'pin', 'remove', 'deploy-service', '--catalog', catalog]);
+ expect(remove.exitCode).toBe(0);
+ expect(existsSync(rulePath(b))).toBe(false);
+ expect(exclude(b).split('\n')).not.toContain('/' + RULE);
+ });
+
+ test('a pin the project catalog does not hold is left out and reported', async () => {
+ const b = box();
+ const catalog = (await setup(b, ['--skill-loading', 'resolve'])).doc.skill_pins.catalog;
+ await cli(b, ['skills', 'pin', 'add', 'email-triage', '--catalog', catalog]);
+ const cfgPath = join(gbrainHome(b), 'config.json');
+ const cfg = JSON.parse(readFileSync(cfgPath, 'utf8'));
+ cfg.skills.resolver.pins[catalog].push({ name: 'gone-skill' });
+ writeFileSync(cfgPath, JSON.stringify(cfg));
+ const r = await setup(b, ['--skill-loading', 'resolve']);
+ expect(r.exitCode).toBe(0);
+ expect(r.doc.skill_pins.pins).toBe(1);
+ expect(r.doc.skill_pins.notes.join('\n')).toContain('gone-skill (skill_resolver_pin_unknown)');
+ const rule = readFileSync(rulePath(b), 'utf8');
+ expect(rule).toContain('"email-triage"');
+ expect(rule).not.toContain('gone-skill');
+ });
+
+ test('from a subdirectory of the repository the exclude line names the rule under it', async () => {
+ const b = box({ sub: 'apps/web' });
+ const catalog = (await setup(b, ['--skill-loading', 'resolve'])).doc.skill_pins.catalog;
+ await cli(b, ['skills', 'pin', 'add', 'deploy-service', '--catalog', catalog]);
+ expect(exclude(b).split('\n')).toContain('/apps/web/' + RULE);
+ expect(git(b.repo, 'status', '--porcelain', '--untracked-files=all')).not.toContain('gbrain-pinned-skills.mdc');
+ });
+
+ test('outside git the rule is written and setup says nothing was excluded', async () => {
+ const b = box({ git: false });
+ const catalog = (await setup(b, ['--skill-loading', 'resolve'])).doc.skill_pins.catalog;
+ await cli(b, ['skills', 'pin', 'add', 'deploy-service', '--catalog', catalog]);
+ const r = await setup(b, []);
+ expect(r.exitCode).toBe(0);
+ expect(existsSync(rulePath(b))).toBe(true);
+ expect(r.doc.skill_pins.steps.some((s: any) => s.step === 'exclude')).toBe(false);
+ expect(r.doc.skill_pins.notes.join('\n')).toContain('not in a git repository');
+ });
+
+ test('a rule file gbrain did not write is left as it is and setup exits non-zero', async () => {
+ const b = box();
+ mkdirSync(join(b.project, '.cursor', 'rules'), { recursive: true });
+ writeFileSync(rulePath(b), '---\nalwaysApply: true\n---\nMy own rule.\n');
+ const r = await setup(b, ['--skill-loading', 'resolve']);
+ expect(r.exitCode).not.toBe(0);
+ expect(readFileSync(rulePath(b), 'utf8')).toBe('---\nalwaysApply: true\n---\nMy own rule.\n');
+ const off = await setup(b, ['--skill-loading', 'off']);
+ expect(off.exitCode).toBe(0);
+ expect(readFileSync(rulePath(b), 'utf8')).toBe('---\nalwaysApply: true\n---\nMy own rule.\n');
+ });
+
+ test('off removes the rule, the exclude line and the record, and keeps the pins, the user\'s exclude lines and the brain-first rule', async () => {
+ const b = box();
+ const catalog = (await setup(b, ['--skill-loading', 'resolve'])).doc.skill_pins.catalog;
+ writeFileSync(join(b.repo, '.git', 'info', 'exclude'), exclude(b) + 'my-scratch/\n');
+ await cli(b, ['skills', 'pin', 'add', 'deploy-service', '--catalog', catalog]);
+ expect(existsSync(rulePath(b))).toBe(true);
+ const off = await setup(b, ['--skill-loading', 'off']);
+ expect(off.exitCode).toBe(0);
+ expect(off.doc.skill_pins.steps.map((s: any) => [s.step, s.action])).toEqual([['rule', 'remove'], ['exclude', 'remove'], ['state', 'remove']]);
+ expect(existsSync(rulePath(b))).toBe(false);
+ expect(existsSync(statePath(b))).toBe(false);
+ expect(exclude(b).split('\n')).toContain('my-scratch/');
+ expect(exclude(b).split('\n')).not.toContain('/' + RULE);
+ expect(existsSync(join(b.project, BRAIN_FIRST))).toBe(true);
+ const cfg = JSON.parse(readFileSync(join(gbrainHome(b), 'config.json'), 'utf8'));
+ expect(cfg.skills.resolver.pins[catalog]).toEqual([{ name: 'deploy-service' }]);
+ expect((await setup(b, ['--skill-loading', 'off'])).doc.skill_pins).toBeUndefined();
+ });
+
+ test('a plain gbrain setup cursor writes no pins, and a project with no skill directory refuses resolve', async () => {
+ const b = box({ skills: false });
+ const plain = await setup(b, []);
+ expect(plain.exitCode).toBe(0);
+ expect(plain.doc.skill_pins).toBeUndefined();
+ expect(existsSync(statePath(b))).toBe(false);
+ const r = await setup(b, ['--skill-loading', 'resolve']);
+ expect(r.exitCode).not.toBe(0);
+ expect(existsSync(statePath(b))).toBe(false);
+ expect(existsSync(rulePath(b))).toBe(false);
+ });
+
+ test('doctor reports Cursor as partial (pinned only, no per-turn hook, unverified) and flags a missing rule', async () => {
+ const b = box();
+ const catalog = (await setup(b, ['--skill-loading', 'resolve'])).doc.skill_pins.catalog;
+ await cli(b, ['skills', 'pin', 'add', 'deploy-service', '--catalog', catalog]);
+ const v = await cursorSkillView(gbrainHome(b));
+ expect(v).toMatchObject({ coverage: 'partial', coverage_note: 'pinned only, no per-turn hook, unverified' });
+ expect(v!.projects).toEqual([{ project: b.project, catalog, rule: 'present', fresh: true, stale_reason: null, skills: 2, pins: 1 }]);
+ const ok = describeCursorSkillView(v!);
+ expect(ok.problem).toBeNull();
+ expect(ok.line).toContain('(partial: pinned only, no per-turn hook, unverified)');
+ unlinkSync(rulePath(b));
+ const gone = describeCursorSkillView((await cursorSkillView(gbrainHome(b)))!);
+ expect(gone.problem).toMatchObject({ code: 'skill_resolver_plugin_not_installed', project: b.project });
+ });
+});