Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
skills: rule-level loader ownership, no silent re-grant, typed revoke failures, shellQuote, doctor launcher_missing, connection-scoped bootstrap removal; compiled-binary embed guard
garrytan01597863afa6
diff --git a/AGENTS.md b/AGENTS.mdindex 3ae459eb23..d878104033 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -271,11 +271,6 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contto opt out). Non-metric event rows (`meeting`, `job_change`,`location_change`) ride through the same pipeline via `facts.event_type`;pass `kind: 'event'` or `'all'` to `find_trajectory` to query them.-- **Load gbrain's skills only when a task needs them (opt-in):**- `gbrain setup <harness> --skill-loading spring` adds a compact skills index- beside the brain-first block; the agent loads a matching skill with- `gbrain bundled-skill <name>` (no brain or MCP needed). Default off.- [Skill loading](docs/guides/setup.md#skill-loading-opt-in).- **Answer "who is waiting on me?":** connect the user's Google account once(`gbrain google setup` — two user interactions; relay the `[SHOW USER]`blocks verbatim), then `gbrain waiting --json` returns the ranked peoplediff --git a/docs/guides/setup.md b/docs/guides/setup.mdindex 5d7277d733..8e8222e51a 100644--- a/docs/guides/setup.md+++ b/docs/guides/setup.md@@ -205,7 +205,9 @@ gbrain. MCP `get_skill` is unchanged.| Which skills | Host installs (`setup`, `bootstrap harness`) list all bundled skills; hosted and thin-client connections leave out the host-maintenance ones. || Opt out | `--skill-loading off`; `--no-instructions` removes both blocks; `--remove` takes both out and deletes a file only gbrain created once nothing else is in it. || After an upgrade | The block records the skill catalog it indexes. `gbrain doctor` (`harness_wiring`) names a stale index and the refresh command (`gbrain setup <harness> --skills-index-only`, which rewrites only the skills block, keeping its recorded file, launcher and skill set). It never warns on a stale index alone, and nothing rewrites the file during an upgrade. |-| Choice record | `~/.gbrain/skill-loading.json` (harness, file, mode, launcher, audience, catalog). |+| Launcher check | Before writing, setup runs `<launcher> bundled-skill --json` and refuses (nothing written, exit 1) when the launcher is not an absolute path, does not run, or serves other skills than the ones indexed. Pass `--gbrain-bin <absolute path>` to name another gbrain. `gbrain doctor` reports an index whose recorded launcher is gone. |+| Claude Code permission | Claude Code asks before each Bash command it has no rule for (and headless runs deny it), so on Claude Code spring also adds one rule, `Bash(<launcher> bundled-skill:*)`, to `~/.claude/settings.json`. gbrain records that it added it and takes it out with the last index that uses it; a rule you had before is left alone. If you delete the rule, gbrain doesn't add it back until you run with `--skill-loading spring` again. |+| Choice record | `~/.gbrain/skill-loading.json` (harness, file, mode, launcher, audience, catalog, and the Claude Code rule and whether gbrain added it). |## Harness capability tablediff --git a/llms-full.txt b/llms-full.txtindex 5410997fa6..3924df4807 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -2030,11 +2030,6 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the contto opt out). Non-metric event rows (`meeting`, `job_change`,`location_change`) ride through the same pipeline via `facts.event_type`;pass `kind: 'event'` or `'all'` to `find_trajectory` to query them.-- **Load gbrain's skills only when a task needs them (opt-in):**- `gbrain setup <harness> --skill-loading spring` adds a compact skills index- beside the brain-first block; the agent loads a matching skill with- `gbrain bundled-skill <name>` (no brain or MCP needed). Default off.- [Skill loading](docs/guides/setup.md#skill-loading-opt-in).- **Answer "who is waiting on me?":** connect the user's Google account once(`gbrain google setup` — two user interactions; relay the `[SHOW USER]`blocks verbatim), then `gbrain waiting --json` returns the ranked peoplediff --git a/package.json b/package.jsonindex 7dab95579d..6fdd66acf5 100644--- a/package.json+++ b/package.json@@ -87,6 +87,7 @@"check:plugin-tree": "bash scripts/check-plugin-tree.sh","check:wasm": "bash scripts/check-wasm-embedded.sh","check:pglite-embedded": "bash scripts/check-pglite-embedded.sh",+ "check:skills-embedded": "bash scripts/check-skills-embedded.sh","check:image-decoders": "bash scripts/check-image-decoders-embedded.sh","check:newlines": "bash scripts/check-trailing-newline.sh","test:compile-smoke": "bun test test/binary-self-update-compiled.serial.test.ts",diff --git a/scripts/check-skills-embedded.sh b/scripts/check-skills-embedded.shnew file mode 100755index 0000000000..102ccf055a--- /dev/null+++ b/scripts/check-skills-embedded.sh@@ -0,0 +1,58 @@+#!/usr/bin/env bash+# CI guard (GBRA-194): a `bun build --compile` binary serves gbrain's bundled+# skills byte-identical to skills/. `gbrain bundled-skill` and the spring-loaded+# skills index read them from src/core/skills/bundled-skills.generated.ts, so a+# compiled binary must carry every file as text: no host skills/ dir exists+# beside a release binary. Fails when compile fails, a file is missing or not+# text, or any file's bytes differ from the source tree.+# Mirrors scripts/check-pglite-embedded.sh. Registered in scripts/guards-manifest.tsv.++set -euo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+cd "$REPO_ROOT"++BUILD_DIR="$(mktemp -d /tmp/gbrain-skills-check.XXXXXX)"+OUT_BIN="$BUILD_DIR/skills-embedded-smoketest"+trap 'rm -rf "$BUILD_DIR"' EXIT+mkdir -p "$BUILD_DIR/scripts"+cp -R "$REPO_ROOT/src" "$BUILD_DIR/src"+cp -R "$REPO_ROOT/skills" "$BUILD_DIR/skills"+cp "$REPO_ROOT/package.json" "$BUILD_DIR/package.json"+cp "$REPO_ROOT/scripts/skills-embedded-smoketest.ts" "$BUILD_DIR/scripts/skills-embedded-smoketest.ts"+ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"++if ! (cd "$BUILD_DIR" && bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/skills-embedded-smoketest.ts >"$BUILD_DIR/compile.log" 2>&1); then+ if grep -qiE 'not (found|available)|permission denied|Could not download|ETIMEDOUT|network' "$BUILD_DIR/compile.log"; then+ echo "[check-skills-embedded] SKIP: bun build --compile unavailable in this sandbox." >&2+ echo "GBRAIN_CHECK_SKIPPED: bun build --compile unavailable"+ exit 0+ fi+ echo "[check-skills-embedded] FAIL: bun could not compile the smoketest binary." >&2+ sed -n '1,40p' "$BUILD_DIR/compile.log" >&2 || true+ exit 1+fi++# Run it away from the checkout and the build copy: the binary must not need skills/.+rm -rf "$BUILD_DIR/skills" "$BUILD_DIR/src"+if ! (cd / && HOME="$BUILD_DIR" "$OUT_BIN" >"$BUILD_DIR/embedded.tsv" 2>"$BUILD_DIR/run.log"); then+ echo "[check-skills-embedded] FAIL: compiled binary could not read its embedded skills." >&2+ cat "$BUILD_DIR/embedded.tsv" "$BUILD_DIR/run.log" >&2 || true+ exit 1+fi++: >"$BUILD_DIR/expected.tsv"+while IFS=$'\t' read -r path _; do+ printf '%s\t%s\n' "$path" "$(sha256sum "$REPO_ROOT/skills/$path" | cut -d' ' -f1)" >>"$BUILD_DIR/expected.tsv"+done <"$BUILD_DIR/embedded.tsv"++COUNT="$(wc -l <"$BUILD_DIR/embedded.tsv" | tr -d ' ')"+if [ "$COUNT" -lt 50 ]; then+ echo "[check-skills-embedded] FAIL: only $COUNT embedded skill files." >&2+ exit 1+fi+if ! diff -u "$BUILD_DIR/expected.tsv" "$BUILD_DIR/embedded.tsv" >&2; then+ echo "[check-skills-embedded] FAIL: compiled binary's skill files differ from skills/ (see diff above)." >&2+ exit 1+fi+echo "[check-skills-embedded] OK — compiled binary serves $COUNT bundled skill files byte-identical to skills/."diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex b8baae764d..940cdd1202 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -56,6 +56,7 @@ check-eval-glossary-fresh.sh buildfresh exempt regenerates + diffscheck-fuzz-purity.sh buildfresh exempt executes fuzz corpuscheck-image-decoders-embedded.sh buildfresh exempt binary embed check; in verify CHECKS (check:image-decoders); its smoketest compile bundles a handful of modules (~0.6s)check-pglite-embedded.sh buildfresh exempt binary embed check+check-skills-embedded.sh buildfresh exempt binary embed checkcheck-skills-manifest-fresh.sh buildfresh exempt regenerates + diffscheck-tool-catalog-fresh.sh buildfresh exempt regenerates + diffscheck-wasm-embedded.sh buildfresh exempt binary embed checkdiff --git a/scripts/skills-embedded-smoketest.ts b/scripts/skills-embedded-smoketest.tsnew file mode 100644index 0000000000..88cc6eb9a8--- /dev/null+++ b/scripts/skills-embedded-smoketest.ts@@ -0,0 +1,19 @@+// Compiled-binary smoketest for gbrain's bundled skills (GBRA-194): prints+// one line per embedded file, "<path>\t<sha256>", from inside a+// `bun build --compile` binary. scripts/check-skills-embedded.sh compares the+// lines with skills/ so a compiled gbrain is proven to serve the same skill+// text and files the source tree has (a .json text import, for one, comes+// back parsed in a compiled binary).+import { createHash } from 'node:crypto';+import { BUNDLED_SKILL_FILES } from '../src/core/skills/bundled-skills.generated.ts';++const lines: string[] = [];+for (const path of Object.keys(BUNDLED_SKILL_FILES).sort()) {+ const text = BUNDLED_SKILL_FILES[path];+ if (typeof text !== 'string') {+ console.log(`NOT_TEXT\t${path}\t${typeof text}`);+ process.exit(1);+ }+ lines.push(`${path}\t${createHash('sha256').update(text).digest('hex')}`);+}+console.log(lines.join('\n'));diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 37aa0b1cf7..a9f63fea77 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -384,6 +384,7 @@ test/snapshot-shape-guard.test.ts (file-level) 10 readFileSynctest/sources-webhook.test.ts Webhook sync job extraction contract 1 source-surface-helpertest/spec-drain-lease-constants.test.ts the TLA+ workflow runs when anything a mutant names changes 1 readFileSynctest/spend-off-switch.test.ts reindex / onboard off-switch dispatch (regression guards) 3 bun-file+test/spring-skill-index.test.ts spring-loaded skill index 9 readFileSynctest/supervisor.test.ts recovery hook timeout bound (structural) 1 source-surface-helpertest/sync-failures.test.ts #4543 blocked output names failing files 4 doctor-source-helper,source-surface-helpertest/sync-failures.test.ts Bug 9 — doctor surfaces sync failures 2 doctor-source-helperdiff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex 3bf78efe9e..eb7959100c 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -24,7 +24,7 @@* Doctor seeds nothing; the only file it removes is a status marker whose* process is gone.*/-import type { SkillsBlockState, SkillsIndexView } from '../../../core/setup/skills-block.ts';+import type { SkillsIndexState, SkillsIndexView } from '../../../core/setup/skills-block.ts';import { existsSync, readFileSync } from 'node:fs';import { homedir } from 'node:os';import { basename, dirname, isAbsolute, join } from 'node:path';@@ -410,7 +410,8 @@ export function withInstructionBlocks(check: Check, views: InstructionBlockView[return { name: check.name, status: 'warn', message, details, fix };}-const SKILLS_INDEX_PROBLEM: Record<Exclude<SkillsBlockState, 'current'>, string> = {+const SKILLS_INDEX_PROBLEM: Record<Exclude<SkillsIndexState, 'current'>, string> = {+ launcher_missing: 'names a gbrain that is no longer there, so every skill load fails',stale: 'indexes an older set of bundled skills',absent: 'is gone from the file',no_file: 'is gone (the file was deleted)',@@ -428,7 +429,7 @@ export function withSkillsIndex(check: Check, views: SkillsIndexView[]): Check {const details = { ...(check.details ?? {}), skills_index: views };const off = views.filter((v) => v.state !== 'current');if (off.length === 0) return { ...check, details };- const notes = off.map((v) => `the ${v.harness} skills index in ${v.path} ${SKILLS_INDEX_PROBLEM[v.state as Exclude<SkillsBlockState, 'current'>]}; refresh with \`${v.refresh}\``);+ const notes = off.map((v) => `the ${v.harness} skills index in ${v.path} ${SKILLS_INDEX_PROBLEM[v.state as Exclude<SkillsIndexState, 'current'>]}; refresh with \`${v.refresh}\``);return { ...check, message: `${check.message} Skills index: ${notes.join('; ')}.`, details };}diff --git a/src/core/bootstrap/harness-skills-index.ts b/src/core/bootstrap/harness-skills-index.tsindex 769fbeb944..d87075f990 100644--- a/src/core/bootstrap/harness-skills-index.ts+++ b/src/core/bootstrap/harness-skills-index.ts@@ -4,7 +4,8 @@* harness-brain-first.ts writes for each confirmed host. Selected like* setup's: --skill-loading, GBRAIN_SKILL_LOADING, the recorded choice, off.* A bootstrap install runs on the brain host, so the index lists every- * bundled skill. Removal strips only the indexes this lane recorded.+ * bundled skill. Removal strips only the indexes this lane recorded, and+ * leaves one whose file still holds another connection's brain-first block.*/import { brainFirstTargetAt, codexInstructionFile, readBrainFirstLedger } from '../setup/brain-first.ts';import { describeSkillsBlockOutcome, installerSkillsBlock, removeSkillsBlocksBy, skillsOutcomeFailed, type SkillLoading, type SkillsBlockOutcome } from '../setup/skills-block.ts';@@ -13,22 +14,25 @@ import type { BrainFirstHost, HarnessInstructionPaths } from './harness-brain-ficonst WRITER = 'gbrain bootstrap harness';-export function writeHarnessSkillsIndex(opts: { hosts: readonly BrainFirstHost[]; launcher: string; optOut: boolean; skillLoading?: SkillLoading; paths: HarnessInstructionPaths; log: (line: string) => void }): SkillsBlockOutcome[] {+export function writeHarnessSkillsIndex(opts: { hosts: readonly BrainFirstHost[]; launcher: string; optOut: boolean; skillLoading?: SkillLoading; paths: HarnessInstructionPaths; settingsPath: string; log: (line: string) => void }): SkillsBlockOutcome[] {const { paths } = opts;return opts.hosts.map((host) => {const path = host === 'claude-code' ? paths.claudeMemoryPath: host === 'codex' ? codexInstructionFile(paths.codexAgentsOverride, paths.codexAgentsPath): paths.opencodeAgentsPath;const declined = opts.optOut || readBrainFirstLedger().find((e) => e.harness === host && e.path === path)?.status === 'declined';- const o = installerSkillsBlock({ target: brainFirstTargetAt(host, path), launcher: opts.launcher, writer: WRITER, brainFirstDeclined: declined, skillLoading: opts.skillLoading, audience: 'owner' });+ const o = installerSkillsBlock({ target: brainFirstTargetAt(host, path), launcher: opts.launcher, writer: WRITER, brainFirstDeclined: declined, skillLoading: opts.skillLoading, audience: 'owner', settingsPath: opts.settingsPath });if (o.decision.value === 'spring' || o.action !== 'skip') opts.log(describeSkillsBlockOutcome(o, false).trim());if (skillsOutcomeFailed(o)) setCliExitVerdict(1);return o;});}-export function removeHarnessSkillsIndex(log: (line: string) => void): void {- for (const o of removeSkillsBlocksBy(WRITER)) {+/** Runs after brain-first removal: an index whose file still holds another connection's brain-first block stays with it. */+export function removeHarnessSkillsIndex(server: string, log: (line: string) => void): void {+ const keptFor = (harness: string, path: string) => readBrainFirstLedger().some((b) => b.harness === harness && b.path === path && b.writer === WRITER+ && b.status === 'installed' && b.access.kind === 'mcp' && b.access.server !== server);+ for (const o of removeSkillsBlocksBy(WRITER, { keep: (e) => keptFor(e.harness, e.path) })) {log(describeSkillsBlockOutcome(o, false).trim());if (skillsOutcomeFailed(o)) setCliExitVerdict(1);}diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex c510ec7365..d749406c8b 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -1995,7 +1995,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Pconst instructionHosts = hosts.filter((h) => targets.some((t) => t.host === h && t.kind === 'mcp' && t.state === 'confirmed'));writeHarnessBrainFirst({ hosts: instructionHosts, server: flags.name, optOut: flags.noInstructions === true, paths: d, log: d.log });writeHarnessSkillsIndex({ hosts: instructionHosts, launcher: flags.gbrainBin ?? d.gbrainBin ?? 'gbrain', optOut: flags.noInstructions === true,- skillLoading: flags.skillLoading, paths: d, log: d.log });+ skillLoading: flags.skillLoading, paths: d, settingsPath: d.userSettingsPath, log: d.log });// 11. Degradation + skew honesty.if (health.engine === 'postgres') {@@ -2273,7 +2273,7 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):}removeHarnessBrainFirst(flags.name, d.log);- removeHarnessSkillsIndex(d.log);+ removeHarnessSkillsIndex(flags.name, d.log);if (remaining.length === 0 && tokenDone && skillsDone) {deleteHarnessReceipt(d.gbrainHome);diff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.tsindex 6290192ae7..c2871c4c0f 100644--- a/src/core/setup/skills-block.ts+++ b/src/core/setup/skills-block.ts@@ -20,7 +20,7 @@* through either block, so whichever block is removed last deletes a file* nothing else was written into.*/-import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';+import { accessSync, constants as fsConstants, existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';import { basename, isAbsolute, join } from 'node:path';import { resolveGbrainBin } from '../gbrain-bin.ts';import { addPermissionsAllowEntry, removePermissionsAllowEntry } from '../bootstrap/hooks.ts';@@ -31,7 +31,8 @@ import { configDir } from '../config.ts';import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';import { ensureGitExcluded } from '../context/compiled-core.ts';import { bundledCatalogId, bundledSkills, type SkillAudience } from '../skills/bundled.ts';-import { renderSkillIndexBlock, shellWord, SKILL_INDEX_VERSION, SkillIndexTooLarge, skillIndexCatalog } from '../skills/spring-index.ts';+import { shellQuote } from '../shell-quote.ts';+import { renderSkillIndexBlock, SKILL_INDEX_VERSION, SkillIndexTooLarge, skillIndexCatalog } from '../skills/spring-index.ts';import { BRAIN_FIRST_END, brainFirstTargetAt, CURSOR_HEAD, direntExists, readBrainFirstLedger, writeUnlessChanged, type BrainFirstHarness, type BrainFirstTarget } from './brain-first.ts';export const SKILLS_BLOCK_BEGIN = '<!-- gbrain:skills:begin -->';@@ -67,8 +68,18 @@ export function indexLauncher(): string | null {* from the ones indexed (another install earlier on PATH, a stale* --gbrain-bin). Engine-free and read-only on the launcher's side.*/+const servedCatalogs = new Map<string, { catalog: string } | { error: string }>();+export function launcherCatalog(launcher: string): { catalog: string } | { error: string } {if (!isAbsolute(launcher)) return { error: `${launcher} is not an absolute path (GUI-launched harnesses inherit no PATH)` };+ const known = servedCatalogs.get(launcher);+ if (known) return known;+ const served = askLauncher(launcher);+ servedCatalogs.set(launcher, served);+ return served;+}++function askLauncher(launcher: string): { catalog: string } | { error: string } {const r = spawnSync(launcher, ['bundled-skill', '--json'], { encoding: 'utf8', timeout: 20_000 }) as { status: number | null; stdout?: string; stderr?: string; error?: Error };if (r.status !== 0) return { error: `${launcher} bundled-skill --json failed: ${(r.error?.message ?? r.stderr ?? '').trim().split('\n')[0] || `exit ${r.status}`}` };try {@@ -105,9 +116,12 @@ export interface SkillLoadingLedgerEntry {catalog?: string;launcher?: string;audience?: SkillAudience;- /** Claude Code: the permissions.allow rule that lets sessions run the loader, and whether gbrain added it. */+ /** Claude Code: the permissions.allow rule that lets sessions run the loader, the settings file it is in, and whether gbrain added it. */allow_rule?: string;+ allow_settings?: string;allow_owned?: boolean;+ /** The user removed the rule gbrain added; it is not added again until an explicit --skill-loading spring. */+ allow_declined?: boolean;writer: string;created_file: boolean;updated_at: string;@@ -161,32 +175,66 @@ export function priorSkillLoading(harness: string, path: string): SkillLoadingLe* runs deny it, so a spring index on Claude Code comes with one narrow rule* in the user settings: the recorded launcher's `bundled-skill` subcommand* only, written exactly as the index writes the command. Ownership lives in- * the ledger (allow_owned): gbrain removes the rule only when it added it and- * no other recorded index still uses it.+ * the ledger (allow_owned): every index that uses a rule gbrain added shares+ * that ownership, and gbrain removes the rule only when the last of them goes.*/export function loaderAllowRule(launcher: string): string {- return `Bash(${shellWord(launcher)} bundled-skill:*)`;+ return `Bash(${shellQuote(launcher)} bundled-skill:*)`;}-type Grant = Pick<SkillLoadingLedgerEntry, 'allow_rule' | 'allow_owned'>;+type Grant = Pick<SkillLoadingLedgerEntry, 'allow_rule' | 'allow_settings' | 'allow_owned' | 'allow_declined'>;++const ruleSettings = (e: Grant) => e.allow_settings ?? claudeUserSettingsPath();-/** Add the rule after the block is in place; returns the ownership to record. Throws when settings cannot be updated. */-function grantLoader(harness: string, launcher: string, prior: SkillLoadingLedgerEntry | undefined): Grant {- if (harness !== 'claude-code') return {};+/** Whether the settings file lists the rule; undefined when the file cannot be read as JSON. */+function loaderRulePresent(settings: string, rule: string): boolean | undefined {+ if (!existsSync(settings)) return false;+ try {+ const allow = (JSON.parse(readFileSync(settings, 'utf8')) as { permissions?: { allow?: unknown } })?.permissions?.allow;+ return Array.isArray(allow) && allow.includes(rule);+ } catch {+ return undefined;+ }+}++/**+ * Add the rule after the block is in place; returns the ownership to record,+ * whether this call added it, and whether it stayed out because the user+ * removed the rule gbrain added (only an explicit --skill-loading spring adds+ * it back). Throws when settings cannot be updated.+ */+function grantLoader(harness: string, launcher: string, settings: string, prior: SkillLoadingLedgerEntry | undefined, regrant: boolean): { grant: Grant; added: boolean; declined: boolean } {+ if (harness !== 'claude-code') return { grant: {}, added: false, declined: false };const rule = loaderAllowRule(launcher);- const added = addPermissionsAllowEntry(claudeUserSettingsPath(), rule).added === true;- return { allow_rule: rule, allow_owned: added || (prior?.allow_rule === rule && prior.allow_owned === true) };+ const same = prior?.allow_rule === rule && ruleSettings(prior) === settings;+ const userRemoved = same && (prior.allow_declined === true || (prior.allow_owned === true && loaderRulePresent(settings, rule) === false));+ if (userRemoved && !regrant) return { grant: { allow_rule: rule, allow_settings: settings, allow_owned: false, allow_declined: true }, added: false, declined: true };+ const added = addPermissionsAllowEntry(settings, rule).added === true;+ const shared = readSkillLoadingLedger().some((e) => e.allow_rule === rule && ruleSettings(e) === settings && e.allow_owned === true);+ return { grant: { allow_rule: rule, allow_settings: settings, allow_owned: added || shared }, added, declined: false };}-/** Remove a rule gbrain owns once nothing else uses it. Returns why it could not, or undefined when done (or nothing to do). */-function revokeLoader(entry: SkillLoadingLedgerEntry | undefined, keepRule?: string): string | undefined {- if (!entry?.allow_rule || entry.allow_owned !== true || entry.allow_rule === keepRule) return undefined;- const stillUsed = readSkillLoadingLedger().some((e) => e.mode === 'spring' && e.allow_rule === entry.allow_rule && !(e.harness === entry.harness && e.path === entry.path));- if (stillUsed) return undefined;- const settings = claudeUserSettingsPath();- const r = removePermissionsAllowEntry(settings, entry.allow_rule);- const warning = r.notes.find((n) => n.startsWith('WARNING'));- return warning ? `the Claude Code permission rule ${entry.allow_rule} that gbrain added is still in ${settings}: ${warning}` : undefined;+/**+ * Remove a rule gbrain owns once no other recorded index uses it. Never+ * throws: `problem` says why the rule is still there, `removed` names the+ * rule when this call took it out of the settings.+ */+function revokeLoader(entry: SkillLoadingLedgerEntry | undefined, keep?: { rule?: string; settings: string }): { removed?: { rule: string; settings: string }; problem?: string } {+ if (!entry?.allow_rule || entry.allow_owned !== true) return {};+ const rule = entry.allow_rule;+ const settings = ruleSettings(entry);+ if (keep && rule === keep.rule && settings === keep.settings) return {};+ const stuck = (why: string) => ({ problem: `the Claude Code permission rule ${rule} that gbrain added is still in ${settings}: ${why}` });+ try {+ const stillUsed = readSkillLoadingLedger().some((e) => e.mode === 'spring' && e.allow_rule === rule && ruleSettings(e) === settings && !(e.harness === entry.harness && e.path === entry.path));+ if (stillUsed) return {};+ const r = removePermissionsAllowEntry(settings, rule);+ const warning = r.notes.find((n) => n.startsWith('WARNING'));+ if (warning) return stuck(warning);+ return (r.removed ?? 0) > 0 ? { removed: { rule, settings } } : {};+ } catch (e) {+ return stuck(message(e));+ }}// ── Decision, inspection, sync, removal ───────────────────────────────────@@ -273,8 +321,9 @@ const message = (e: unknown) => (e instanceof Error ? e.message : String(e));* outcome with a reason, and the file is left as it was unless the detail* says otherwise.*/-export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; verifyLauncher?: boolean }): SkillsBlockOutcome {+export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: string; decision: SkillLoadingDecision; writer: string; dryRun: boolean; audience?: SkillAudience; verifyLauncher?: boolean; settingsPath?: string }): SkillsBlockOutcome {const { target, launcher, decision } = opts;+ const settings = opts.settingsPath ?? claudeUserSettingsPath();const audience = opts.audience ?? 'owner';let body: string | undefined;let tooLarge: SkillIndexTooLarge | undefined;@@ -298,21 +347,17 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: striif (mode === 'off' && decision.source === 'default' && !prior) return;upsertLedger({ harness: target.harness, path: target.path, mode, block_version: SKILL_INDEX_VERSION, ...(mode === 'spring' ? { catalog: bundledCatalogId(), launcher, audience, ...grant } : {}), writer: opts.writer, created_file: created, updated_at: new Date().toISOString() });};- const revoked = (rule: string | undefined): Partial<SkillsBlockOutcome> =>- rule ? { permission: { rule, settings: claudeUserSettingsPath(), change: 'removed' } } : {};if (before.state === 'damaged') {return out('preserve', `the skills markers in ${target.path} were hand-edited (duplicate, orphan or out of order); fix or delete them, then re-run`, { reason: 'damaged_markers' });}if (decision.value === 'off') {- if (!opts.dryRun) {- const stuck = revokeLoader(prior);- if (stuck) return out('preserve', `${stuck}; remove it by hand, then re-run. ${target.path} was left as it was`, { reason: 'permission_update_failed' });- }- const ownedRule = prior?.allow_owned ? prior.allow_rule : undefined;+ const revocation = opts.dryRun ? {} : revokeLoader(prior);+ if (revocation.problem) return out('preserve', `${revocation.problem}; fix that, then re-run. ${target.path} was left as it was`, { reason: 'permission_update_failed' });+ const revoked: Partial<SkillsBlockOutcome> = revocation.removed ? { permission: { ...revocation.removed, change: 'removed' } } : {};if (before.state === 'no_file' || before.state === 'absent') {try { record('off', false); } catch (e) { return out('preserve', `recording the opt-out failed: ${message(e)}`, { reason: 'write_failed' }); }- return out('skip', `skill loading off: no skills index in ${target.path}`, revoked(ownedRule));+ return out('skip', `skill loading off: no skills index in ${target.path}`, revoked);}try {const existing = readFileSync(target.path, 'utf8');@@ -327,7 +372,7 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stritry { record('off', false); } catch (e) {return out('preserve', `the skills index was removed from ${target.path}, but recording the opt-out in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it`, { reason: 'recorded_partially' });}- return out('remove', `skills index from ${target.path}`, revoked(ownedRule));+ return out('remove', `skills index from ${target.path}`, revoked);}if (body === undefined) return out('preserve', `${tooLarge!.message}; ${target.path} was left as it was`, { reason: 'index_too_large' });@@ -359,22 +404,31 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stri? out('keep', `skills index in ${target.path} is current`): out('write', `skills index ${before.state === 'stale' ? 'refreshed in' : created ? 'in new file' : 'added to'} ${target.path}`);if (opts.dryRun) return done;- let grant: Grant = {};- let permissionProblem: string | undefined;- try {- grant = grantLoader(target.harness, launcher, prior);- permissionProblem = revokeLoader(prior, grant.allow_rule);- } catch (e) {- permissionProblem = `the Claude Code permission rule ${loaderAllowRule(launcher)} could not be added to ${claudeUserSettingsPath()} (${message(e)}), so Claude Code will ask before each skill load`;+ const priorGrant: Grant = prior?.allow_rule+ ? { allow_rule: prior.allow_rule, allow_settings: prior.allow_settings, allow_owned: prior.allow_owned, ...(prior.allow_declined ? { allow_declined: true } : {}) }+ : {};+ const rule = target.harness === 'claude-code' ? loaderAllowRule(launcher) : undefined;+ let grant: Grant = priorGrant;+ const replaced = revokeLoader(prior, { rule, settings });+ let permissionProblem = replaced.problem;+ let added = false;+ let declined = false;+ if (!permissionProblem) {+ try {+ ({ grant, added, declined } = grantLoader(target.harness, launcher, settings, prior, decision.source === 'flag'));+ } catch (e) {+ grant = priorGrant.allow_rule === rule && ruleSettings(priorGrant) === settings ? priorGrant : {};+ permissionProblem = `the Claude Code permission rule ${rule} could not be added to ${settings} (${message(e)}), so Claude Code will ask before each skill load`;+ }}try {record('spring', createdFile, grant);} catch (e) {- return out('preserve', `the skills index is in ${target.path}, but recording it in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it${grant.allow_owned ? ` (gbrain also added ${grant.allow_rule} to ${claudeUserSettingsPath()})` : ''}`, { reason: 'recorded_partially' });+ return out('preserve', `the skills index is in ${target.path}, but recording it in ${skillLoadingLedgerPath()} failed (${message(e)}); re-run to record it${added ? ` (gbrain also added ${grant.allow_rule} to ${settings})` : ''}`, { reason: 'recorded_partially' });}if (permissionProblem) return { ...done, action: 'preserve', detail: `${done.detail}; ${permissionProblem}`, reason: 'permission_update_failed' };- const added = grant.allow_rule && grant.allow_owned && prior?.allow_rule !== grant.allow_rule;- return added ? { ...done, detail: `${done.detail}; Claude Code may now run ${grant.allow_rule}`, permission: { rule: grant.allow_rule!, settings: claudeUserSettingsPath(), change: 'added' } } : done;+ if (declined) return { ...done, detail: `${done.detail}; the Claude Code rule ${rule} was removed from ${settings} after gbrain added it, so gbrain left it out and Claude Code will ask before each skill load (re-run with --skill-loading spring to add it again)` };+ return added && grant.allow_rule ? { ...done, detail: `${done.detail}; Claude Code may now run ${grant.allow_rule}`, permission: { rule: grant.allow_rule, settings, change: 'added' } } : done;}/** The uninstall path: strip the block, delete the file only when gbrain created it and nothing else is left, forget the record. */@@ -391,9 +445,9 @@ export function removeSkillsBlock(opts: { harness: string; path: string; dryRun:}if (before.state === 'damaged') return out('preserve', `the skills markers in ${opts.path} were hand-edited; remove the block by hand`, { reason: 'damaged_markers' });if (opts.dryRun) return before.state === 'no_file' || before.state === 'absent' ? out('skip', `no skills index in ${opts.path}`) : out('remove', `skills index from ${opts.path}`);- const stuck = revokeLoader(prior);- if (stuck) return out('preserve', `${stuck}; remove it by hand, then re-run. ${opts.path} was left as it was`, { reason: 'permission_update_failed' });- const permission: Partial<SkillsBlockOutcome> = prior?.allow_owned && prior.allow_rule ? { permission: { rule: prior.allow_rule, settings: claudeUserSettingsPath(), change: 'removed' } } : {};+ const revocation = revokeLoader(prior);+ if (revocation.problem) return out('preserve', `${revocation.problem}; fix that, then re-run. ${opts.path} was left as it was`, { reason: 'permission_update_failed' });+ const permission: Partial<SkillsBlockOutcome> = revocation.removed ? { permission: { ...revocation.removed, change: 'removed' } } : {};let deleteFile = false;if (before.state !== 'no_file' && before.state !== 'absent') {try {@@ -428,7 +482,7 @@ export function describeSkillsBlockOutcome(o: SkillsBlockOutcome, dryRun: boolea*/export function installerSkillsBlock(opts: {target: BrainFirstTarget; launcher: string; writer: string; brainFirstDeclined: boolean;- skillLoading?: SkillLoading; audience?: SkillAudience; remove?: boolean; dryRun?: boolean;+ skillLoading?: SkillLoading; audience?: SkillAudience; remove?: boolean; dryRun?: boolean; settingsPath?: string;}): SkillsBlockOutcome {if (opts.remove) return removeSkillsBlock({ harness: opts.target.harness, path: opts.target.path, dryRun: opts.dryRun ?? false });let decision: SkillLoadingDecision;@@ -440,7 +494,7 @@ export function installerSkillsBlock(opts: {const reason: SkillsBlockReason = e instanceof InvalidSkillLoadingEnv ? 'invalid_env' : 'ledger_unreadable';return { harness: opts.target.harness, path: opts.target.path, decision: { value: 'off', source: 'flag' }, action: 'preserve', state_before: inspectSkillsBlock(opts.target.path).state, detail: `${message(e)}; ${opts.target.path} was left as it was`, reason };}- return syncSkillsBlock({ target: opts.target, launcher: opts.launcher, decision, writer: opts.writer, dryRun: opts.dryRun ?? false, audience: opts.audience });+ return syncSkillsBlock({ target: opts.target, launcher: opts.launcher, decision, writer: opts.writer, dryRun: opts.dryRun ?? false, audience: opts.audience, settingsPath: opts.settingsPath });}/** A preserve outcome when the ledger cannot be read, else undefined. */@@ -453,14 +507,26 @@ function ledgerProblem(): SkillsBlockOutcome | undefined {}}-/** Removal for a lane that records its writer: strip every index that writer wrote. */-export function removeSkillsBlocksBy(writer: string, dryRun = false): SkillsBlockOutcome[] {+/** Removal for a lane that records its writer: strip every index that writer wrote, except those `keep` claims. */+export function removeSkillsBlocksBy(writer: string, opts: { dryRun?: boolean; keep?: (e: SkillLoadingLedgerEntry) => boolean } = {}): SkillsBlockOutcome[] {const unreadable = ledgerProblem();if (unreadable) return [unreadable];- return readSkillLoadingLedger().filter((e) => e.writer === writer && e.mode === 'spring').map((e) => removeSkillsBlock({ harness: e.harness, path: e.path, dryRun }));+ const dryRun = opts.dryRun ?? false;+ return readSkillLoadingLedger().filter((e) => e.writer === writer && e.mode === 'spring' && !opts.keep?.(e)).map((e) => removeSkillsBlock({ harness: e.harness, path: e.path, dryRun }));}-export interface SkillsIndexView { harness: string; path: string; state: SkillsBlockState; refresh: string }+/** launcher_missing: the block is in place but the gbrain it names is gone, so every load fails. */+export type SkillsIndexState = SkillsBlockState | 'launcher_missing';+export interface SkillsIndexView { harness: string; path: string; state: SkillsIndexState; refresh: string }++function launcherRuns(launcher: string): boolean {+ try {+ accessSync(launcher, fsConstants.X_OK);+ return true;+ } catch {+ return false;+ }+}/*** Doctor's read of every index the ledger says is on: current, stale (an@@ -470,9 +536,13 @@ export interface SkillsIndexView { harness: string; path: string; state: SkillsB*/export function skillsIndexViews(): SkillsIndexView[] {if (ledgerProblem()) return [{ harness: '*', path: skillLoadingLedgerPath(), state: 'damaged', refresh: `fix the JSON in ${skillLoadingLedgerPath()} or move it aside, then re-run gbrain setup <harness> --skill-loading spring` }];- return readSkillLoadingLedger().filter((e) => e.mode === 'spring').map((e) => ({- harness: e.harness, path: e.path, state: inspectSkillsBlock(e.path).state, refresh: skillsRefreshCommand(e.harness),- }));+ return readSkillLoadingLedger().filter((e) => e.mode === 'spring').map((e) => {+ const state = inspectSkillsBlock(e.path).state;+ if (state === 'current' && e.launcher && isAbsolute(e.launcher) && !launcherRuns(e.launcher)) {+ return { harness: e.harness, path: e.path, state: 'launcher_missing', refresh: `${skillsRefreshCommand(e.harness)} --gbrain-bin <absolute path of gbrain>` };+ }+ return { harness: e.harness, path: e.path, state, refresh: skillsRefreshCommand(e.harness) };+ });}diff --git a/src/core/skills/spring-index.ts b/src/core/skills/spring-index.tsindex f54d2da9d3..9b299b9d90 100644--- a/src/core/skills/spring-index.ts+++ b/src/core/skills/spring-index.ts@@ -17,6 +17,7 @@* does not fit, rendering refuses (SkillIndexTooLarge) and the caller leaves* the instruction file as it was.*/+import { shellQuote } from '../shell-quote.ts';import { bundledCatalogId, bundledSkillTriggers, type BundledSkill } from './bundled.ts';export const SKILL_INDEX_VERSION = 1;@@ -53,13 +54,8 @@ function distinctTriggers(skill: BundledSkill): string[] {const line = (name: string, triggers: string[]) => (triggers.length ? `- ${name}: ${triggers.join('; ')}` : `- ${name}`);-/** The launcher as one shell word: as-is when it is plain, else single-quoted. */-export function shellWord(s: string): string {- return /^[A-Za-z0-9_\/.,:@%+=-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\''")}'`;-}-export function skillIndexHeader(launcher: string, refresh: string, optOut: string): string[] {- const run = shellWord(launcher);+ const run = shellQuote(launcher);return [`<!-- gbrain skills v${SKILL_INDEX_VERSION} catalog ${bundledCatalogId()}: managed by gbrain; edit outside these markers. Refresh: ${refresh}. Opt out: ${optOut} -->`,'## GBrain skills: load on demand',diff --git a/test/skill-loading-lanes.test.ts b/test/skill-loading-lanes.test.tsindex 63b6e6a78a..8285e3b048 100644--- a/test/skill-loading-lanes.test.ts+++ b/test/skill-loading-lanes.test.ts@@ -13,12 +13,13 @@* --no-instructions, or doctor warns on (or hides) a stale index.*/import { afterAll, describe, expect, test } from 'bun:test';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { withEnv } from './helpers/with-env.ts';import { BRAIN_FIRST_END, brainFirstTargetAt } from '../src/core/setup/brain-first.ts';-import { installerSkillsBlock, loaderAllowRule, readSkillLoadingLedger, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';+import { installerSkillsBlock, loaderAllowRule, readSkillLoadingLedger, skillsIndexViews, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';+import { removeHarnessBrainFirst, writeHarnessBrainFirst } from '../src/core/bootstrap/harness-brain-first.ts';import { installHarnessConnection } from '../src/core/harness/install.ts';import { removeHarnessSkillsIndex, writeHarnessSkillsIndex } from '../src/core/bootstrap/harness-skills-index.ts';import { withSkillsIndex } from '../src/commands/doctor/checks/harness-wiring.ts';@@ -115,22 +116,43 @@ describe('bootstrap harness', () => {const paths = { claudeMemoryPath: join(b.home, '.claude', 'CLAUDE.md'), codexAgentsPath: join(b.home, '.codex', 'AGENTS.md'),codexAgentsOverride: join(b.home, '.codex', 'AGENTS.override.md'), opencodeAgentsPath: join(b.home, '.config', 'opencode', 'AGENTS.md') };const log: string[] = [];- const off = writeHarnessSkillsIndex({ hosts: ['claude-code'], launcher: LAUNCHER, optOut: false, paths, log: (l) => log.push(l) });+ const settingsPath = join(b.home, '.claude', 'settings.json');+ const off = writeHarnessSkillsIndex({ hosts: ['claude-code'], launcher: LAUNCHER, optOut: false, paths, settingsPath, log: (l) => log.push(l) });expect(off[0].action).toBe('skip');expect(log).toEqual([]);- const on = writeHarnessSkillsIndex({ hosts: ['claude-code', 'codex'], launcher: LAUNCHER, optOut: false, skillLoading: 'spring', paths, log: (l) => log.push(l) });+ const on = writeHarnessSkillsIndex({ hosts: ['claude-code', 'codex'], launcher: LAUNCHER, optOut: false, skillLoading: 'spring', paths, settingsPath, log: (l) => log.push(l) });expect(on.map(o => o.action)).toEqual(['write', 'write']);expect(indexed(read(paths.claudeMemoryPath))).toEqual(bundledSkills('owner').map(s => s.name));expect(read(paths.codexAgentsPath)).toContain('\`' + LAUNCHER + ' bundled-skill <name>\`');const other = join(b.home, 'other', 'AGENTS.md');installerSkillsBlock({ target: brainFirstTargetAt('opencode', other), launcher: LAUNCHER, writer: 'gbrain setup opencode', brainFirstDeclined: false, skillLoading: 'spring' });- removeHarnessSkillsIndex(() => {});+ removeHarnessSkillsIndex('gbrain', () => {});expect(existsSync(paths.claudeMemoryPath)).toBe(false);expect(read(other)).toContain(SKILLS_BLOCK_BEGIN);expect(readSkillLoadingLedger().map(e => e.writer)).toEqual(['gbrain setup opencode']);});});++ test('removing one connection leaves the index in a file whose brain-first block belongs to another connection', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const paths = { claudeMemoryPath: join(b.home, '.claude', 'CLAUDE.md'), codexAgentsPath: join(b.home, '.codex', 'AGENTS.md'),+ codexAgentsOverride: join(b.home, '.codex', 'AGENTS.override.md'), opencodeAgentsPath: join(b.home, '.config', 'opencode', 'AGENTS.md') };+ const settingsPath = join(b.home, '.claude', 'settings.json');+ const quiet = () => {};+ writeHarnessBrainFirst({ hosts: ['codex'], server: 'conn-b', optOut: false, paths, log: quiet });+ writeHarnessSkillsIndex({ hosts: ['codex'], launcher: LAUNCHER, optOut: false, skillLoading: 'spring', paths, settingsPath, log: quiet });+ removeHarnessBrainFirst('conn-a', quiet);+ removeHarnessSkillsIndex('conn-a', quiet);+ expect(read(paths.codexAgentsPath)).toContain(SKILLS_BLOCK_BEGIN);+ expect(readSkillLoadingLedger()).toHaveLength(1);+ removeHarnessBrainFirst('conn-b', quiet);+ removeHarnessSkillsIndex('conn-b', quiet);+ expect(existsSync(paths.codexAgentsPath) ? read(paths.codexAgentsPath) : '').not.toContain(SKILLS_BLOCK_BEGIN);+ expect(readSkillLoadingLedger()).toEqual([]);+ });+ });});describe('installer decision', () => {@@ -165,6 +187,24 @@ describe('doctor: skills index', () => {const warn = withSkillsIndex({ ...check, status: 'warn' as any }, [{ harness: 'cursor', path: '/p/.cursor/rules/x.mdc', state: 'absent', refresh: 'gbrain setup cursor --instructions-only' }]);expect(warn.status).toBe('warn');});+ test('an index whose recorded gbrain is gone reports launcher_missing with a --gbrain-bin refresh', async () => {+ const b = box();+ const moved = join(b.root, 'old-install', 'gbrain');+ mkdirSync(dirname(moved), { recursive: true });+ copyFileSync(LAUNCHER, moved);+ chmodSync(moved, 0o755);+ await withEnv(b.env, async () => {+ installerSkillsBlock({ target: brainFirstTargetAt('opencode', join(b.home, 'agents', 'AGENTS.md')), launcher: moved, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });+ expect(skillsIndexViews().map(v => v.state)).toEqual(['current']);+ rmSync(moved);+ const views = skillsIndexViews();+ expect(views).toMatchObject([{ state: 'launcher_missing' }]);+ expect(views[0].refresh).toContain('--gbrain-bin');+ const out = withSkillsIndex(check, views);+ expect(out.status).toBe('ok');+ expect(out.message).toContain('no longer there');+ });+ });test('no index on: the check is returned unchanged; all current: only details are added', () => {expect(withSkillsIndex(check, [])).toBe(check);const cur = withSkillsIndex(check, [{ harness: 'codex', path: '/x', state: 'current', refresh: 'r' }]);@@ -172,6 +212,113 @@ describe('doctor: skills index', () => {});});+describe('Claude Code loader rule', () => {+ const allowList = (settings: string): string[] => (existsSync(settings) ? JSON.parse(read(settings)).permissions?.allow ?? [] : []);+ const setup = (b: ReturnType<typeof box>) => {+ const settings = join(b.home, '.claude', 'settings.json');+ const user = brainFirstTargetAt('claude-code', join(b.home, '.claude', 'CLAUDE.md'));+ const project = brainFirstTargetAt('claude-code', join(b.root, 'repo', 'CLAUDE.md'));+ mkdirSync(dirname(project.path), { recursive: true });+ const spring = (target: typeof user, extra: Record<string, unknown> = { skillLoading: 'spring' }) =>+ installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, ...extra });+ const remove = (target: typeof user) => spring(target, { remove: true });+ return { settings, user, project, spring, remove, rule: loaderAllowRule(LAUNCHER) };+ };++ for (const order of ['user first', 'project first'] as const) {+ test(`two indexes sharing one rule: it stays until the last is removed (${order}), and only the real removal reports it`, async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const s = setup(b);+ expect(s.spring(s.user).permission).toMatchObject({ change: 'added', rule: s.rule });+ expect(s.spring(s.project).permission).toBeUndefined();+ const [first, second] = order === 'user first' ? [s.user, s.project] : [s.project, s.user];+ const r1 = s.remove(first);+ expect(r1.action).toBe('remove');+ expect(r1.permission).toBeUndefined();+ expect(allowList(s.settings)).toContain(s.rule);+ const r2 = s.remove(second);+ expect(r2.permission).toMatchObject({ change: 'removed', rule: s.rule, settings: s.settings });+ expect(allowList(s.settings)).not.toContain(s.rule);+ expect(readSkillLoadingLedger()).toEqual([]);+ });+ });+ }++ test('a rule the user had before gbrain is never taken out', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const s = setup(b);+ mkdirSync(dirname(s.settings), { recursive: true });+ writeFileSync(s.settings, JSON.stringify({ permissions: { allow: [s.rule] } }));+ expect(s.spring(s.user).permission).toBeUndefined();+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_rule: s.rule, allow_owned: false });+ expect(s.remove(s.user).permission).toBeUndefined();+ expect(allowList(s.settings)).toEqual([s.rule]);+ });+ });++ test('a rule the user removed is not added back by a remembered choice, only by an explicit --skill-loading spring', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const s = setup(b);+ s.spring(s.user);+ writeFileSync(s.settings, JSON.stringify({ permissions: { allow: [] } }));+ const again = s.spring(s.user, {});+ expect(again).toMatchObject({ action: 'keep', decision: { source: 'prior' } });+ expect(again.detail).toContain('--skill-loading spring');+ expect(allowList(s.settings)).toEqual([]);+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_owned: false, allow_declined: true });+ expect(s.spring(s.user, {}).permission).toBeUndefined();+ expect(allowList(s.settings)).toEqual([]);+ expect(s.spring(s.user).permission).toMatchObject({ change: 'added', rule: s.rule });+ expect(allowList(s.settings)).toEqual([s.rule]);+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_owned: true });+ expect(readSkillLoadingLedger()[0].allow_declined).toBeUndefined();+ });+ });++ test('a failed grant keeps the recorded ownership, so the rule still comes out after the settings are repaired', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const s = setup(b);+ s.spring(s.user);+ const good = read(s.settings);+ writeFileSync(s.settings, '{broken');+ const failed = s.spring(s.user);+ expect(failed).toMatchObject({ action: 'preserve', reason: 'permission_update_failed' });+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_rule: s.rule, allow_owned: true });+ writeFileSync(s.settings, good);+ expect(s.spring(s.user).action).toBe('keep');+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_owned: true });+ expect(s.spring(s.user, { skillLoading: 'off' }).permission).toMatchObject({ change: 'removed', rule: s.rule });+ expect(allowList(s.settings)).not.toContain(s.rule);+ });+ });++ for (const how of ['off', 'remove'] as const) {+ test(`a settings write that fails during ${how} is a typed refusal that keeps the index and the record`, async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const s = setup(b);+ s.spring(s.user);+ const dir = dirname(s.settings);+ chmodSync(dir, 0o500);+ try {+ const o = how === 'off' ? s.spring(s.user, { skillLoading: 'off' }) : s.remove(s.user);+ expect(o).toMatchObject({ action: 'preserve', reason: 'permission_update_failed' });+ expect(o.detail).toContain(s.rule);+ } finally {+ chmodSync(dir, 0o755);+ }+ expect(read(s.user.path)).toContain(SKILLS_BLOCK_BEGIN);+ expect(readSkillLoadingLedger()[0]).toMatchObject({ mode: 'spring', allow_owned: true });+ expect(allowList(s.settings)).toContain(s.rule);+ });+ });+ }+});+describe('refusals keep everything as it was', () => {test('an invalid GBRAIN_SKILL_LOADING is refused with the allowed values, before any write', async () => {const b = box();diff --git a/test/spring-skill-index.test.ts b/test/spring-skill-index.test.tsindex 7eab9b46a0..8c9d15e712 100644--- a/test/spring-skill-index.test.ts+++ b/test/spring-skill-index.test.ts@@ -20,6 +20,8 @@ import { BUNDLED_SKILL_FILES } from '../src/core/skills/bundled-skills.generatedimport { bundledCatalogId, bundledSkills, bundledSkillTriggers } from '../src/core/skills/bundled.ts';import { renderSkillIndexBlock, SKILL_INDEX_BUDGET_BYTES, SkillIndexTooLarge, skillIndexCatalog } from '../src/core/skills/spring-index.ts';import { renderBundledSkillsModule } from '../scripts/generate-bundled-skills.ts';+import { loaderAllowRule } from '../src/core/setup/skills-block.ts';+import { spawnSync } from 'node:child_process';const OPTS = { refresh: 'gbrain setup claude-code --instructions-only', optOut: 'gbrain setup claude-code --instructions-only --skill-loading off' };const LAUNCHER = '/home/alice-example/.bun/bin/gbrain';@@ -28,6 +30,17 @@ const entries = (block: string) => block.split('\n').filter(l => l.startsWith('-const SKILLS_DIR = join(import.meta.dir, '..', 'skills');describe('spring-loaded skill index', () => {+ test('a launcher path with spaces, an apostrophe or shell characters prints as one shell word the index and the loader rule share', () => {+ for (const launcher of ["/home/alice-example/o'brien dir/gbrain", '/opt/a b/$(x)/gbrain', '/opt/semi;colon/gbrain']) {+ const block = renderSkillIndexBlock(bundledSkills('owner'), launcher, OPTS);+ const word = /`(.+) bundled-skill <name>`/.exec(block)![1];+ const echoed = spawnSync('sh', ['-c', `printf %s ${word}`], { encoding: 'utf8' });+ expect(echoed.status).toBe(0);+ expect(echoed.stdout).toBe(launcher);+ expect(loaderAllowRule(launcher)).toBe(`Bash(${word} bundled-skill:*)`);+ }+ });+for (const audience of ['owner', 'downstream'] as const) {test(`${audience}: under budget, every skill on its own line, loads through bundled-skill`, () => {const skills = bundledSkills(audience);