Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
skills: bootstrap exit codes and --json carry skills outcomes; strict ledger validation; ledger-write rollback; explicit refresh re-grant; dry-run permission preview; doctor warns on launcher_missing/ledger_unreadable; thin-client index in doctor
garrytan2bbfcded9583
diff --git a/src/cli/commands/bundled-skill.ts b/src/cli/commands/bundled-skill.tsindex a006ab1270..470a7dd210 100644--- a/src/cli/commands/bundled-skill.ts+++ b/src/cli/commands/bundled-skill.ts@@ -76,7 +76,7 @@ export async function run(args: string[]): Promise<void> {if (!skill) {const nearest = suggestNearest(name, bundledSkills(audience).map(s => s.name));exitCliError(opError('skill_not_found', `gbrain ${VERSION} has no bundled skill named ${name}${audience === 'downstream' ? ' for this thin-client install' : ''}.${nearest ? ` Did you mean "${nearest}"?` : ''}`,- 'Run the same command with no name to list them. A skills index from another gbrain version may name a renamed skill; refresh it with `gbrain setup <harness> --skills-index-only`.'), 'bundled-skill');+ `Run the same command with no name to list them. A skills index from another gbrain version may name a renamed skill; refresh it with ${audience === 'downstream' ? 'the gbrain connect … --install command in the index header (it rewrites GBRAIN-INSTRUCTIONS.md)' : '`gbrain setup <harness> --skills-index-only`'}.`), 'bundled-skill');}if (asset !== undefined) {diff --git a/src/commands/doctor/checks/harness-wiring.ts b/src/commands/doctor/checks/harness-wiring.tsindex eb7959100c..f5377098f7 100644--- a/src/commands/doctor/checks/harness-wiring.ts+++ b/src/commands/doctor/checks/harness-wiring.ts@@ -412,6 +412,7 @@ export function withInstructionBlocks(check: Check, views: InstructionBlockView[const SKILLS_INDEX_PROBLEM: Record<Exclude<SkillsIndexState, 'current'>, string> = {launcher_missing: 'names a gbrain that is no longer there, so every skill load fails',+ ledger_unreadable: 'record cannot be read',stale: 'indexes an older set of bundled skills',absent: 'is gone from the file',no_file: 'is gone (the file was deleted)',@@ -421,16 +422,31 @@ const SKILLS_INDEX_PROBLEM: Record<Exclude<SkillsIndexState, 'current'>, string>/*** GBRA-194 sibling of withInstructionBlocks: the spring-loaded skills index* (src/core/setup/skills-block.ts) for every harness the ledger has it on.- * Informational: a stale index still loads skills by name, so the status is- * never changed; the message names the exact refresh command.+ * A stale, absent or damaged index is informational (a stale index still+ * loads skills by name), so the message names the refresh command and the+ * status is unchanged. Two states break every load or every later change and+ * turn `ok` into a warn with a fix: the recorded launcher is gone, or the+ * ledger cannot be read.*/export function withSkillsIndex(check: Check, views: SkillsIndexView[]): Check {if (views.length === 0) return 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<SkillsIndexState, 'current'>]}; refresh with \`${v.refresh}\``);- return { ...check, message: `${check.message} Skills index: ${notes.join('; ')}.`, details };+ const notes = off.map((v) => v.state === 'ledger_unreadable'+ ? `the skills index ${SKILLS_INDEX_PROBLEM.ledger_unreadable}: ${v.refresh}`+ : `the ${v.harness} skills index in ${v.path} ${SKILLS_INDEX_PROBLEM[v.state as Exclude<SkillsIndexState, 'current'>]}; refresh with \`${v.refresh}\``);+ const message = `${check.message} Skills index: ${notes.join('; ')}.`;+ const broken = off.find((v) => v.state === 'launcher_missing' || v.state === 'ledger_unreadable');+ if (!broken || check.status !== 'ok') return { ...check, message, details };+ const fix: Action = broken.state === 'ledger_unreadable'+ ? { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME),+ why: 'gbrain will not guess which skills indexes and permission rules it owns from a ledger it cannot read.',+ user_message: `The gbrain skills record cannot be read: ${broken.refresh}` }+ : { consent: [], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME),+ why: `The skills index in ${broken.path} names a gbrain that is no longer there, so the agent cannot load any skill it lists.`,+ user_message: `The ${broken.harness} skills index points at a gbrain that was moved or uninstalled. Run: ${broken.refresh}, with the absolute path of the gbrain you use now.` };+ return { name: check.name, status: 'warn', message, details, fix };}/** The setup command that rewrites exactly this block: same file, same connection name and surface. A project file needs its own directory, so the user runs it there. */diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.tsindex b025ce150e..21c5adf68f 100644--- a/src/commands/harness-connect.ts+++ b/src/commands/harness-connect.ts@@ -39,8 +39,11 @@ export async function runHarnessConnect(args: string[]): Promise<void> {console.error(`If it was exposed: ${token.if_exposed.steps.join(' Then: ')} See ${token.if_exposed.docs_url}.`);if (token.token_warning) console.error(`WARNING: ${token.token_warning}`);}- if (skillsOutcomeFailed((result as { skills?: SkillsBlockOutcome }).skills)) setCliExitVerdict(1);- else if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);+ const skills = (result as { skills?: SkillsBlockOutcome }).skills;+ if (skillsOutcomeFailed(skills)) {+ console.error(`skills index: ${skills!.detail}${'remote_membership_pending' in result && result.remote_membership_pending ? ' (remote membership deactivation is also pending; exit 1 outranks its exit 2)' : ''}`);+ setCliExitVerdict(1);+ } else if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);} catch (error) {console.log(JSON.stringify({ status: 'error', reason: 'connection_setup_failed', message: error instanceof Error ? error.message : 'Connection setup failed' }));setCliExitVerdict(1);diff --git a/src/commands/setup.ts b/src/commands/setup.tsindex 47f6d6a764..b5e2b60c87 100644--- a/src/commands/setup.ts+++ b/src/commands/setup.ts@@ -800,7 +800,7 @@ async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number>if (!isBrainFirstHarness(harness)) {return refuse(opError('invalid_params', `--skills-index-only needs a harness with an instruction file: ${BRAIN_FIRST_HARNESSES.join(', ')}`, 'Pass the harness whose skills index to refresh, e.g. gbrain setup claude-code --skills-index-only.'), out);}- const outcomes = refreshSkillsIndexes(harness, { off: flags.skillLoading === 'off', launcher: flags.gbrainBin, dryRun: flags.dryRun });+ const outcomes = refreshSkillsIndexes(harness, { mode: flags.skillLoading, launcher: flags.gbrainBin, dryRun: flags.dryRun });const code = outcomes.some((o) => o.action === 'preserve') ? 1 : 0;if (out.json) {await writeJsonDocument(`${JSON.stringify({ harness, dry_run: flags.dryRun, skills_index_only: true, skills: outcomes }, null, 2)}\n`, (t) => process.stdout.write(t));diff --git a/src/core/bootstrap/harness-skills-index.ts b/src/core/bootstrap/harness-skills-index.tsindex d87075f990..6f6c122974 100644--- a/src/core/bootstrap/harness-skills-index.ts+++ b/src/core/bootstrap/harness-skills-index.ts@@ -8,8 +8,7 @@* 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';-import { setCliExitVerdict } from '../cli-force-exit.ts';+import { describeSkillsBlockOutcome, installerSkillsBlock, removeSkillsBlocksBy, type SkillLoading, type SkillsBlockOutcome } from '../setup/skills-block.ts';import type { BrainFirstHost, HarnessInstructionPaths } from './harness-brain-first.ts';const WRITER = 'gbrain bootstrap harness';@@ -23,17 +22,15 @@ export function writeHarnessSkillsIndex(opts: { hosts: readonly BrainFirstHost[]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', settingsPath: opts.settingsPath });if (o.decision.value === 'spring' || o.action !== 'skip') opts.log(describeSkillsBlockOutcome(o, false).trim());- if (skillsOutcomeFailed(o)) setCliExitVerdict(1);return o;});}/** 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 {+export function removeHarnessSkillsIndex(server: string, log: (line: string) => void): SkillsBlockOutcome[] {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);- }+ const outcomes = removeSkillsBlocksBy(WRITER, { keep: (e) => keptFor(e.harness, e.path) });+ for (const o of outcomes) log(describeSkillsBlockOutcome(o, false).trim());+ return outcomes;}diff --git a/src/core/bootstrap/harness.ts b/src/core/bootstrap/harness.tsindex d749406c8b..5f457bdba8 100644--- a/src/core/bootstrap/harness.ts+++ b/src/core/bootstrap/harness.ts@@ -61,7 +61,7 @@ import {} from './instructions-block.ts';import { removeHarnessBrainFirst, writeHarnessBrainFirst } from './harness-brain-first.ts';import { removeHarnessSkillsIndex, writeHarnessSkillsIndex } from './harness-skills-index.ts';-import { isSkillLoading, type SkillLoading } from '../setup/skills-block.ts';+import { isSkillLoading, skillsOutcomeFailed, type SkillLoading } from '../setup/skills-block.ts';import { createEngine } from '../engine-factory.ts';import { isValidSourceId } from '../source-id.ts';import { ALL_SOURCES, isResolverUserError, localFederatedSourceIds, resolveSourceWithTier } from '../source-resolver.ts';@@ -1994,8 +1994,10 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P// 10b. Brain-first instructions beside each confirmed MCP entry.const 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,+ const skillsIndex = writeHarnessSkillsIndex({ hosts: instructionHosts, launcher: flags.gbrainBin ?? d.gbrainBin ?? 'gbrain', optOut: flags.noInstructions === true,skillLoading: flags.skillLoading, paths: d, settingsPath: d.userSettingsPath, log: d.log });+ const skillsIndexFailed = skillsIndex.some(skillsOutcomeFailed);+ if (skillsIndexFailed) d.logError('the skills index was not written as asked (see the skills line above); fix that and re-run.');// 11. Degradation + skew honesty.if (health.engine === 'postgres') {@@ -2030,6 +2032,7 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): Pshared_skills: receipt.shared_skills,degraded_per_turn: health.engine === 'postgres',smoke_ok: smokeOk,+ skills_index: skillsIndex,receipt_path: harnessReceiptPath(d.gbrainHome),},null,@@ -2037,7 +2040,8 @@ export async function applyHarness(flags: HarnessFlags, rawDeps: HarnessDeps): P),);}- return pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk ? (cleanup.length ? HARNESS_CLEANUP_PENDING_EXIT_CODE : 0) : 1;+ const code = pendingFix ? HARNESS_PENDING_VERIFY_EXIT_CODE : allConfirmed && smokeOk ? (cleanup.length ? HARNESS_CLEANUP_PENDING_EXIT_CODE : 0) : 1;+ return code === 0 && skillsIndexFailed ? 1 : code;}// ── Remove [C9/F2/C8] ───────────────────────────────────────────────────────@@ -2273,9 +2277,9 @@ export async function removeHarness(flags: HarnessFlags, rawDeps: HarnessDeps):}removeHarnessBrainFirst(flags.name, d.log);- removeHarnessSkillsIndex(flags.name, d.log);+ const skillsIndexDone = !removeHarnessSkillsIndex(flags.name, d.log).some(skillsOutcomeFailed);- if (remaining.length === 0 && tokenDone && skillsDone) {+ if (remaining.length === 0 && tokenDone && skillsDone && skillsIndexDone) {deleteHarnessReceipt(d.gbrainHome);d.log('harness wiring fully removed; receipt consumed.');return 0;diff --git a/src/core/harness/install.ts b/src/core/harness/install.tsindex fa211b9b52..b5a040f4f3 100644--- a/src/core/harness/install.ts+++ b/src/core/harness/install.ts@@ -20,7 +20,7 @@ import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';import { harnessSharedSkillsRoot } from './status.ts';import { gitChildEnv } from '../git-env.ts';import { brainFirstTargetAt, codexInstructionFile, installerBrainFirst, renderBrainFirstSnippet, resolveBrainFirstDecision, type BrainFirstHarness } from '../setup/brain-first.ts';-import { indexLauncher, installerSkillsBlock, isSkillLoading, renderSkillsSnippet, resolveSkillLoading, type SkillLoading } from '../setup/skills-block.ts';+import { indexLauncher, installerSkillsBlock, isSkillLoading, renderSkillsSnippet, resolveSkillLoading, skillsOutcomeFailed, type SkillLoading } from '../setup/skills-block.ts';export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean;@@ -182,19 +182,22 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Instwriter: `gbrain connect --harness ${adapter.id} --install`, instructions: opts.instructions, remove: opts.remove });const skills = installerSkillsBlock({ target: brainFirstTargetAt(beside.harness, beside.path), launcher: opts.gbrainBin ?? indexLauncher() ?? 'gbrain',writer: `gbrain connect --harness ${adapter.id} --install`, brainFirstDeclined: instructions.decision.value === 'declined', skillLoading: opts.skillLoading, audience: 'downstream', remove: opts.remove });+ const skillsProblem = skillsOutcomeFailed(skills) ? `The skills index step did not finish: ${skills.detail}. Fix that, then re-run this command (the skills record is kept, so a re-run finishes it).` : undefined;if (opts.remove) {if (existsSync(receiptPath)) unlinkSync(receiptPath);const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });const pending = 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true;+ const next = pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'+ : 'The client configuration was removed. Revoke the grant on the brain host if access should end.';return { ...common, status: 'removed', config_path: configPath, shared_skills, remote_membership_pending: pending, instructions, skills,- next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'- : 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };+ ...(skillsProblem ? { skills_failed: true } : {}), next_action: skillsProblem ? `${skillsProblem} ${next}` : next };}const nextReceipt = { ...common, entry_hash: ownedEntryHash(nativeEntry(configPath, adapter.connection, name), adapter.connection), status: 'installed',...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });- return { ...nextReceipt, shared_skills, instructions, skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };+ return { ...nextReceipt, shared_skills, instructions, skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true,+ ...(skillsProblem ? { skills_failed: true, next_action: `${skillsProblem} ${nextReceipt.next_action}` } : {}) };} finally { lock.release(); }}diff --git a/src/core/setup/skills-block.ts b/src/core/setup/skills-block.tsindex c2871c4c0f..160823b315 100644--- a/src/core/setup/skills-block.ts+++ b/src/core/setup/skills-block.ts@@ -131,8 +131,13 @@ export function skillLoadingLedgerPath(): string { return join(configDir(), LEDG/** A ledger gbrain cannot read: ownership is unknown, so nothing that depends on it is changed. */export class SkillLedgerUnreadable extends Error {- constructor(readonly path: string, why: string) {- super(`${path} is unreadable (${why}); gbrain will not guess which skills indexes and permission rules it owns. Fix the JSON or move the file aside, then re-run`);+ constructor(readonly path: string, why: string, raw = '') {+ const newer = /"version"\s*:\s*(\d+)/.exec(raw);+ const rules = [...new Set([...raw.matchAll(/"allow_rule"\s*:\s*"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1]!.replace(/\\(.)/g, '$1')))];+ const rulesNote = rules.length ? ` and the Claude Code permission rule${rules.length > 1 ? 's' : ''} it names (${rules.join(', ')}, normally in ${claudeUserSettingsPath()})` : '';+ super(newer && Number(newer[1]) > 1+ ? `${path} was written by a newer gbrain (ledger version ${newer[1]}); upgrade gbrain, then re-run`+ : `${path} is unreadable (${why}); ownership is unknown, so no skills index or permission rule was changed. Restore a valid copy or fix that entry, then re-run once. Starting over without it would leave whatever it recorded behind: if you must, first remove the gbrain:skills blocks${rulesNote} by hand`);}}@@ -140,14 +145,39 @@ export class SkillLedgerUnreadable extends Error {export function readSkillLoadingLedger(): SkillLoadingLedgerEntry[] {const path = skillLoadingLedgerPath();if (!existsSync(path)) return [];+ const text = readFileSync(path, 'utf8');let raw: { version?: unknown; entries?: unknown };try {- raw = JSON.parse(readFileSync(path, 'utf8')) as typeof raw;+ raw = JSON.parse(text) as typeof raw;} catch (e) {- throw new SkillLedgerUnreadable(path, e instanceof Error ? e.message : String(e));+ throw new SkillLedgerUnreadable(path, e instanceof Error ? e.message : String(e), text);}- if (raw?.version !== 1 || !Array.isArray(raw.entries)) throw new SkillLedgerUnreadable(path, 'not a version-1 ledger');- return (raw.entries as SkillLoadingLedgerEntry[]).filter((e) => e && typeof e.path === 'string' && typeof e.harness === 'string' && isSkillLoading(e.mode));+ if (raw?.version !== 1 || !Array.isArray(raw.entries)) throw new SkillLedgerUnreadable(path, 'not a version-1 ledger', text);+ const entries = raw.entries as SkillLoadingLedgerEntry[];+ const seen = new Set<string>();+ entries.forEach((e, i) => {+ const bad = invalidLedgerField(e);+ if (bad) throw new SkillLedgerUnreadable(path, `entry ${i} has an invalid ${bad}`, text);+ const key = JSON.stringify([e.harness, e.path]);+ if (seen.has(key)) throw new SkillLedgerUnreadable(path, `entry ${i} repeats ${e.harness} ${e.path}`, text);+ seen.add(key);+ });+ return entries;+}++/** The first field of a ledger entry that is missing or of the wrong type, else undefined. */+function invalidLedgerField(e: SkillLoadingLedgerEntry): string | undefined {+ if (!e || typeof e !== 'object') return 'entry';+ const optional = (v: unknown, type: string) => v !== undefined && typeof v !== type;+ if (typeof e.harness !== 'string') return 'harness';+ if (typeof e.path !== 'string') return 'path';+ if (!isSkillLoading(e.mode)) return 'mode';+ if (typeof e.writer !== 'string') return 'writer';+ if (typeof e.created_file !== 'boolean') return 'created_file';+ if (e.audience !== undefined && e.audience !== 'owner' && e.audience !== 'downstream') return 'audience';+ for (const k of ['catalog', 'launcher', 'allow_rule', 'allow_settings'] as const) if (optional(e[k], 'string')) return k;+ for (const k of ['allow_owned', 'allow_declined'] as const) if (optional(e[k], 'boolean')) return k;+ return undefined;}function writeLedger(entries: SkillLoadingLedgerEntry[]): void {@@ -203,12 +233,16 @@ function loaderRulePresent(settings: string, rule: string): boolean | undefined* removed the rule gbrain added (only an explicit --skill-loading spring adds* it back). Throws when settings cannot be updated.*/+/** The recorded rule is this one and the user took it out after gbrain added it (or declined it before). */+function userRemovedRule(prior: SkillLoadingLedgerEntry | undefined, rule: string, settings: string): boolean {+ if (prior?.allow_rule !== rule || ruleSettings(prior) !== settings) return false;+ return prior.allow_declined === true || (prior.allow_owned === true && loaderRulePresent(settings, rule) === false);+}+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 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 };+ if (userRemovedRule(prior, rule, settings) && !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 };@@ -219,15 +253,29 @@ function grantLoader(harness: string, launcher: string, settings: string, prior:* throws: `problem` says why the rule is still there, `removed` names the* rule when this call took it out of the settings.*/+/** The owned rule revokeLoader would take out for this entry, or undefined when it has none to take or another index still uses it. Throws on an unreadable ledger. */+function revocableRule(entry: SkillLoadingLedgerEntry | undefined, keep?: { rule?: string; settings: string }): { rule: string; settings: string } | undefined {+ if (!entry?.allow_rule || entry.allow_owned !== true) return undefined;+ const rule = entry.allow_rule;+ const settings = ruleSettings(entry);+ if (keep && rule === keep.rule && settings === keep.settings) return undefined;+ const stillUsed = readSkillLoadingLedger().some((e) => e.mode === 'spring' && e.allow_rule === rule && ruleSettings(e) === settings && !(e.harness === entry.harness && e.path === entry.path));+ return stillUsed ? undefined : { rule, settings };+}++/** What --dry-run reports for the loader rule: the change a real run would make. */+function plannedPermission(change: 'would_add' | 'would_remove', target: { rule: string; settings: string } | undefined): Partial<SkillsBlockOutcome> {+ if (!target || loaderRulePresent(target.settings, target.rule) === (change === 'would_add')) return {};+ return { permission: { ...target, change } };+}+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 {};+ if (!revocableRule(entry, keep)) return {};const r = removePermissionsAllowEntry(settings, rule);const warning = r.notes.find((n) => n.startsWith('WARNING'));if (warning) return stuck(warning);@@ -239,7 +287,8 @@ function revokeLoader(entry: SkillLoadingLedgerEntry | undefined, keep?: { rule?// ── Decision, inspection, sync, removal ───────────────────────────────────-export type SkillLoadingSource = 'flag' | 'env' | 'prior' | 'default' | 'instructions_off';+/** unresolved: the choice could not be read (an unreadable ledger, an invalid GBRAIN_SKILL_LOADING). */+export type SkillLoadingSource = 'flag' | 'env' | 'prior' | 'default' | 'instructions_off' | 'unresolved';export interface SkillLoadingDecision { value: SkillLoading; source: SkillLoadingSource }/** GBRAIN_SKILL_LOADING holds something other than off or spring. */@@ -292,12 +341,19 @@ export interface SkillsBlockOutcome {detail: string;reason?: SkillsBlockReason;/** Claude Code: the loader rule this run added to (or removed from) the user settings. */- permission?: { rule: string; settings: string; change: 'added' | 'removed' };+ permission?: { rule: string; settings: string; change: 'added' | 'removed' | 'would_add' | 'would_remove' };}-/** A spring request (or an explicit off) that left the surface unchanged: the install did not do what was asked. */-export const skillsOutcomeFailed = (o: SkillsBlockOutcome | null | undefined): boolean =>- !!o && o.action === 'preserve' && (o.decision.value === 'spring' || o.decision.source !== 'default');+/**+ * The install did not do what was asked: a spring request (or an explicit+ * off) left the surface unchanged, or an explicit spring was skipped for a+ * reason the user has to fix (Hermes without SOUL.md).+ */+export const skillsOutcomeFailed = (o: SkillsBlockOutcome | null | undefined): boolean => {+ if (!o) return false;+ if (o.action === 'preserve') return o.decision.value === 'spring' || o.decision.source !== 'default';+ return o.action === 'skip' && o.reason !== undefined && o.decision.value === 'spring' && (o.decision.source === 'flag' || o.decision.source === 'env');+};function ownedEmptyFile(createdFile: boolean, path: string, stripped: string): boolean {return createdFile && !lstatSync(path).isSymbolicLink() && (stripped.trim() === '' || stripped === CURSOR_HEAD);@@ -354,7 +410,8 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: striif (decision.value === 'off') {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' } } : {};+ const revoked: Partial<SkillsBlockOutcome> = revocation.removed ? { permission: { ...revocation.removed, change: 'removed' } }+ : opts.dryRun ? plannedPermission('would_remove', revocableRule(prior)) : {};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);@@ -389,10 +446,13 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: striconst brainFirstCreated = readBrainFirstLedger().find((e) => e.harness === target.harness && e.path === target.path)?.created_file ?? false;const created = before.state === 'no_file' && !direntExists(target.path);const createdFile = created || (prior?.created_file ?? false) || brainFirstCreated;+ let written: { before: string | null; after: string } | undefined;if (before.state !== 'current' && !opts.dryRun) {try {const existing = before.state === 'no_file' ? (created && target.harness === 'cursor' ? CURSOR_HEAD : '') : readFileSync(target.path, 'utf8');- writeUnlessChanged(target.path, existing, before.state === 'no_file', placeSkillsBlock(existing, body));+ const next = placeSkillsBlock(existing, body);+ writeUnlessChanged(target.path, existing, before.state === 'no_file', next);+ written = { before: before.state === 'no_file' ? null : existing, after: next };if (created && target.project) {try { ensureGitExcluded(target.path); } catch { /* a project file outside git stays as written */ }}@@ -403,7 +463,12 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: striconst done = before.state === 'current'? 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;+ if (opts.dryRun) {+ if (target.harness !== 'claude-code') return done;+ const rule = loaderAllowRule(launcher);+ if (userRemovedRule(prior, rule, settings) && decision.source !== 'flag') return done;+ return { ...done, ...plannedPermission('would_add', { rule, settings }) };+ }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 } : {}) }: {};@@ -424,13 +489,44 @@ export function syncSkillsBlock(opts: { target: BrainFirstTarget; launcher: stritry {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${added ? ` (gbrain also added ${grant.allow_rule} to ${settings})` : ''}`, { reason: 'recorded_partially' });+ const left = undoUnrecorded({ path: target.path, written, rule: added ? grant.allow_rule : undefined, settings });+ if (left.length === 0) return out('preserve', `recording the skills index in ${skillLoadingLedgerPath()} failed (${message(e)}), so this run's changes were undone and nothing changed; fix that, then re-run`, { reason: 'write_failed' });+ return out('preserve', `recording the skills index in ${skillLoadingLedgerPath()} failed (${message(e)}), and gbrain could not undo ${left.join(' and ')}; remove ${left.length > 1 ? 'them' : 'it'} by hand before re-running, because a re-run would take ${left.length > 1 ? 'them' : 'it'} for yours`, { reason: 'recorded_partially' });}- if (permissionProblem) return { ...done, action: 'preserve', detail: `${done.detail}; ${permissionProblem}`, reason: 'permission_update_failed' };+ if (permissionProblem) return { ...done, action: 'preserve', detail: `${done.detail} (the index is in place; the permission step did not finish): ${permissionProblem}`, reason: 'permission_update_failed' };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;}+/**+ * A run whose ledger write failed takes back what it changed, so no rule or+ * file is left that the ledger does not know gbrain wrote. Returns what could+ * not be undone.+ */+function undoUnrecorded(opts: { path: string; written?: { before: string | null; after: string }; rule?: string; settings: string }): string[] {+ const left: string[] = [];+ if (opts.rule) {+ try {+ if (removePermissionsAllowEntry(opts.settings, opts.rule).notes.some((n) => n.startsWith('WARNING'))) left.push(`the rule ${opts.rule} in ${opts.settings}`);+ } catch {+ left.push(`the rule ${opts.rule} in ${opts.settings}`);+ }+ }+ if (opts.written) {+ try {+ if (opts.written.before === null) {+ if (readFileSync(opts.path, 'utf8') !== opts.written.after) throw new Error('changed');+ unlinkSync(opts.path);+ } else {+ writeUnlessChanged(opts.path, opts.written.after, false, opts.written.before);+ }+ } catch {+ left.push(`the skills block in ${opts.path}`);+ }+ }+ return left;+}+/** The uninstall path: strip the block, delete the file only when gbrain created it and nothing else is left, forget the record. */export function removeSkillsBlock(opts: { harness: string; path: string; dryRun: boolean }): SkillsBlockOutcome {const before = inspectSkillsBlock(opts.path);@@ -444,7 +540,10 @@ export function removeSkillsBlock(opts: { harness: string; path: string; dryRun:return out('preserve', `${message(e)}; ${opts.path} was left as it was`, { reason: 'ledger_unreadable' });}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}`);+ if (opts.dryRun) {+ const planned = plannedPermission('would_remove', revocableRule(prior));+ return before.state === 'no_file' || before.state === 'absent' ? out('skip', `no skills index in ${opts.path}`, planned) : out('remove', `skills index from ${opts.path}`, planned);+ }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' } } : {};@@ -471,7 +570,8 @@ export function removeSkillsBlock(opts: { harness: string; path: string; dryRun:/** One human line per outcome, matching setup's step lines. */export function describeSkillsBlockOutcome(o: SkillsBlockOutcome, dryRun: boolean): string {const how = o.decision.value === 'spring' ? 'turn off with --skill-loading off' : 'turn on with --skill-loading spring';- return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'skills'.padEnd(7)} ${o.detail} [${o.decision.source}; ${how}]`;+ const tag = o.decision.source === 'unresolved' ? '' : ` [${o.decision.source}; ${how}]`;+ return ` ${(dryRun && o.action !== 'keep' && o.action !== 'skip' ? `would ${o.action}` : o.action).padEnd(8)} ${'skills'.padEnd(7)} ${o.detail}${tag}`;}/**@@ -492,7 +592,7 @@ export function installerSkillsBlock(opts: {: resolveSkillLoading(opts.skillLoading, priorSkillLoading(opts.target.harness, opts.target.path));} catch (e) {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 { harness: opts.target.harness, path: opts.target.path, decision: { value: 'off', source: 'unresolved' }, 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, settingsPath: opts.settingsPath });}@@ -503,7 +603,7 @@ function ledgerProblem(): SkillsBlockOutcome | undefined {readSkillLoadingLedger();return undefined;} catch (e) {- return { harness: '*', path: skillLoadingLedgerPath(), decision: { value: 'off', source: 'flag' }, action: 'preserve', state_before: 'damaged', detail: message(e), reason: 'ledger_unreadable' };+ return { harness: '*', path: skillLoadingLedgerPath(), decision: { value: 'off', source: 'unresolved' }, action: 'preserve', state_before: 'damaged', detail: message(e), reason: 'ledger_unreadable' };}}@@ -515,8 +615,8 @@ export function removeSkillsBlocksBy(writer: string, opts: { dryRun?: boolean; kreturn readSkillLoadingLedger().filter((e) => e.writer === writer && e.mode === 'spring' && !opts.keep?.(e)).map((e) => removeSkillsBlock({ harness: e.harness, path: e.path, dryRun }));}-/** launcher_missing: the block is in place but the gbrain it names is gone, so every load fails. */-export type SkillsIndexState = SkillsBlockState | 'launcher_missing';+/** launcher_missing: the block is in place but the gbrain it names is gone, so every load fails. ledger_unreadable: gbrain cannot tell which indexes it wrote. */+export type SkillsIndexState = SkillsBlockState | 'launcher_missing' | 'ledger_unreadable';export interface SkillsIndexView { harness: string; path: string; state: SkillsIndexState; refresh: string }function launcherRuns(launcher: string): boolean {@@ -535,14 +635,37 @@ function launcherRuns(launcher: string): boolean {* by name, so doctor names the refresh command and never warns on it.*/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) => {+ const unreadable = ledgerProblem();+ if (unreadable) return [{ harness: '*', path: skillLoadingLedgerPath(), state: 'ledger_unreadable', refresh: unreadable.detail }];+ return [...readSkillLoadingLedger().filter((e) => e.mode === 'spring').map((e): SkillsIndexView => {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) };- });+ }), ...thinClientIndexView()];+}++/**+ * A thin-client install (`gbrain connect --harness … --root`) writes its index+ * into GBRAIN-INSTRUCTIONS.md, a file the connection owns whole, so it is+ * recorded in the connection receipt rather than the ledger, and refreshed by+ * re-running that install.+ */+function thinClientIndexView(): SkillsIndexView[] {+ const receiptPath = join(configDir(), 'harness-connection.json');+ if (!existsSync(receiptPath)) return [];+ let receipt: { status?: unknown; skill_loading?: unknown; root?: unknown; mcp_url?: unknown; harness?: unknown };+ try {+ receipt = JSON.parse(readFileSync(receiptPath, 'utf8')) as typeof receipt;+ } catch {+ return [];+ }+ if (receipt.status !== 'installed' || receipt.skill_loading !== 'spring' || typeof receipt.root !== 'string') return [];+ const harness = typeof receipt.harness === 'string' ? receipt.harness : 'generic';+ const path = join(receipt.root, 'GBRAIN-INSTRUCTIONS.md');+ const rerun = `gbrain connect ${shellQuote(String(receipt.mcp_url ?? '<mcp-url>'))} --harness ${shellQuote(harness)} --credentials-file <private-handoff-file> --root ${shellQuote(receipt.root)} --install`;+ return [{ harness, path, state: inspectSkillsBlock(path).state, refresh: rerun }];}@@ -551,16 +674,19 @@ export function skillsIndexViews(): SkillsIndexView[] {* and doctor name): re-render every index the ledger records for the* harness, in its recorded file, with its recorded launcher (or* --gbrain-bin), audience and writer. Brain-first and every other file are- * left alone. `off` strips them all and records the opt-out.+ * left alone. `off` strips them all and records the opt-out; an explicit+ * `spring` is a flag-sourced choice, so it adds back a loader rule the user+ * removed, which a plain refresh does not.*/-export function refreshSkillsIndexes(harness: BrainFirstHarness, opts: { off: boolean; launcher?: string; dryRun: boolean }): SkillsBlockOutcome[] {+export function refreshSkillsIndexes(harness: BrainFirstHarness, opts: { mode?: SkillLoading; launcher?: string; dryRun: boolean }): SkillsBlockOutcome[] {const unreadable = ledgerProblem();if (unreadable) return [unreadable];- return readSkillLoadingLedger().filter((e) => e.harness === harness && (opts.off || e.mode === 'spring')).map((e) => syncSkillsBlock({+ const off = opts.mode === 'off';+ return readSkillLoadingLedger().filter((e) => e.harness === harness && (off || e.mode === 'spring')).map((e) => syncSkillsBlock({target: brainFirstTargetAt(harness, e.path),launcher: opts.launcher ?? e.launcher ?? indexLauncher() ?? 'gbrain',audience: e.audience ?? 'owner',- decision: opts.off ? { value: 'off', source: 'flag' } : { value: 'spring', source: 'prior' },+ decision: off ? { value: 'off', source: 'flag' } : { value: 'spring', source: opts.mode === 'spring' ? 'flag' : 'prior' },writer: e.writer,dryRun: opts.dryRun,}));diff --git a/test/bootstrap-harness.serial.test.ts b/test/bootstrap-harness.serial.test.tsindex 292f07d06d..9cb73772d2 100644--- a/test/bootstrap-harness.serial.test.ts+++ b/test/bootstrap-harness.serial.test.ts@@ -513,6 +513,34 @@ describe('full apply', () => {});});+describe('skills index exit codes (GBRA-194)', () => {+ test('a requested skills index that is not written makes apply exit 1 and lands in --json', async () => {+ const f = makeFake();+ await withEnv({ GBRAIN_HOME: dirname(f.home), GBRAIN_SKILL_LOADING: undefined }, async () => {+ const code = await applyHarness(flags(['--harness', 'claude-code', '--skill-loading', 'spring', '--json']), f.deps);+ expect(code).toBe(1);+ expect(f.err.join('\n')).toContain('skills index was not written');+ const doc = JSON.parse(f.out.filter(l => l.trim().startsWith('{')).join('\n') || '{}') as { skills_index?: Array<{ action: string; reason?: string }> };+ expect(doc.skills_index?.[0]).toMatchObject({ action: 'preserve', reason: 'launcher_unusable' });+ });+ });++ test('a skills index that cannot be removed makes --remove exit 1 and keeps the receipt', async () => {+ const f = makeFake();+ await withEnv({ GBRAIN_HOME: dirname(f.home), GBRAIN_SKILL_LOADING: undefined }, async () => {+ expect(await applyHarness(flags(['--harness', 'claude-code']), f.deps)).toBe(0);+ writeFileSync(join(f.home, 'skill-loading.json'), '{not json');+ const removeDeps: HarnessDeps = {+ ...f.deps,+ runner: async (argv: string[]) => (argv[0] === 'claude' && argv[2] === 'get' ? { code: 0, stdout: `Type: http\nURL: ${URL}`, stderr: '' } : { code: 0, stdout: '', stderr: '' }),+ };+ expect(await removeHarness(parseHarnessArgs(['--remove', '--yes']), removeDeps)).toBe(1);+ expect(readHarnessReceiptState(f.home).state).not.toBe('absent');+ expect(readFileSync(join(f.home, 'skill-loading.json'), 'utf8')).toBe('{not json');+ });+ });+});+describe('--remove', () => {test('full remove: ours-by-url removed, token revoked by id, receipt consumed; foreign entries survive', async () => {const f = makeFake();diff --git a/test/skill-loading-lanes.test.ts b/test/skill-loading-lanes.test.tsindex 8285e3b048..eef936eda3 100644--- a/test/skill-loading-lanes.test.ts+++ b/test/skill-loading-lanes.test.ts@@ -18,7 +18,7 @@ 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, skillsIndexViews, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END } from '../src/core/setup/skills-block.ts';+import { installerSkillsBlock, loaderAllowRule, readSkillLoadingLedger, refreshSkillsIndexes, skillsIndexViews, skillsOutcomeFailed, SKILLS_BLOCK_BEGIN, SKILLS_BLOCK_END, type SkillsBlockOutcome } 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';@@ -88,6 +88,17 @@ describe('connect --harness --install', () => {});}+ test('a requested index that is not written is flagged in the result and its next_action', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const configPath = join(b.home, '.codex', 'config.toml');+ const r = await installHarnessConnection(credentials, { harness: 'codex', configPath, skillLoading: 'spring', gbrainBin: join(b.root, 'missing', 'gbrain') }) as any;+ expect(r.skills).toMatchObject({ action: 'preserve', reason: 'launcher_unusable' });+ expect(r.skills_failed).toBe(true);+ expect(r.next_action).toContain('skills index step did not finish');+ });+ });+test('thin client: GBRAIN-INSTRUCTIONS.md carries the index after brain-first with the root launcher; the choice is kept', async () => {const b = box();const root = join(b.root, 'thin');@@ -103,6 +114,10 @@ describe('connect --harness --install', () => {expect(indexed(text)).toEqual(bundledSkills('downstream').map(s => s.name));await installHarnessConnection(credentials, { harness: 'openclaw', root });expect(read(join(root, 'GBRAIN-INSTRUCTIONS.md'))).toBe(text);+ await withEnv({ GBRAIN_HOME: root }, async () => {+ expect(skillsIndexViews()).toMatchObject([{ harness: 'openclaw', path: join(root, 'GBRAIN-INSTRUCTIONS.md'), state: 'current' }]);+ expect(skillsIndexViews()[0].refresh).toContain('gbrain connect');+ });await installHarnessConnection(credentials, { harness: 'openclaw', root, instructions: false });expect(read(join(root, 'GBRAIN-INSTRUCTIONS.md'))).not.toContain(SKILLS_BLOCK_BEGIN);});@@ -201,8 +216,21 @@ describe('doctor: skills index', () => {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.status).toBe('warn');expect(out.message).toContain('no longer there');+ expect((out as any).fix.user_message).toContain('--gbrain-bin');+ });+ });+ test('an unreadable ledger warns with a fix that says to restore it, not to start over', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ mkdirSync(join(b.home, '.gbrain'), { recursive: true });+ writeFileSync(join(b.home, '.gbrain', 'skill-loading.json'), '{not json');+ const views = skillsIndexViews();+ expect(views).toMatchObject([{ state: 'ledger_unreadable' }]);+ const out = withSkillsIndex(check, views);+ expect(out.status).toBe('warn');+ expect((out as any).fix.user_message).toContain('Restore a valid copy');});});test('no index on: the check is returned unchanged; all current: only details are added', () => {@@ -319,6 +347,107 @@ describe('Claude Code loader rule', () => {}});+describe('Claude Code loader rule: refresh, dry-run, ledger failures', () => {+ const allowList = (settings: string): string[] => (existsSync(settings) ? JSON.parse(read(settings)).permissions?.allow ?? [] : []);+ const ctx = (b: ReturnType<typeof box>) => {+ const settings = join(b.home, '.claude', 'settings.json');+ const target = brainFirstTargetAt('claude-code', join(b.home, '.claude', 'CLAUDE.md'));+ const run = (extra: Record<string, unknown> = { skillLoading: 'spring' }) => installerSkillsBlock({ target, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, ...extra });+ return { settings, target, run, rule: loaderAllowRule(LAUNCHER) };+ };++ test('--skills-index-only respects a deleted rule; with an explicit --skill-loading spring it adds it back', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const c = ctx(b);+ c.run();+ writeFileSync(c.settings, JSON.stringify({ permissions: { allow: [] } }));+ expect(refreshSkillsIndexes('claude-code', { dryRun: false })[0].permission).toBeUndefined();+ expect(allowList(c.settings)).toEqual([]);+ const explicit = refreshSkillsIndexes('claude-code', { mode: 'spring', dryRun: false })[0];+ expect(explicit).toMatchObject({ decision: { source: 'flag' }, permission: { change: 'added', rule: c.rule } });+ expect(allowList(c.settings)).toEqual([c.rule]);+ });+ });++ test('--dry-run reports the rule a real run would add or remove, and nothing for a rule another index still uses', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const c = ctx(b);+ expect(c.run({ skillLoading: 'spring', dryRun: true }).permission).toMatchObject({ change: 'would_add', rule: c.rule, settings: c.settings });+ expect(allowList(c.settings)).toEqual([]);+ c.run();+ expect(c.run({ skillLoading: 'off', dryRun: true }).permission).toMatchObject({ change: 'would_remove', rule: c.rule });+ expect(c.run({ remove: true, dryRun: true }).permission).toMatchObject({ change: 'would_remove', rule: c.rule });+ const project = brainFirstTargetAt('claude-code', join(b.root, 'repo', 'CLAUDE.md'));+ mkdirSync(dirname(project.path), { recursive: true });+ installerSkillsBlock({ target: project, launcher: LAUNCHER, writer: 'test', brainFirstDeclined: false, skillLoading: 'spring' });+ expect(c.run({ skillLoading: 'off', dryRun: true }).permission).toBeUndefined();+ expect(allowList(c.settings)).toEqual([c.rule]);+ });+ });++ test('a ledger row with an invalid field refuses every change instead of being dropped', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const c = ctx(b);+ c.run();+ const ledger = join(b.home, '.gbrain', 'skill-loading.json');+ const bytes = read(ledger).replace('"mode": "spring"', '"mode": "sprng"');+ writeFileSync(ledger, bytes);+ const off = c.run({ skillLoading: 'off' });+ expect(off).toMatchObject({ action: 'preserve', reason: 'ledger_unreadable' });+ expect(off.detail).toContain('entry 0 has an invalid mode');+ expect(off.detail).toContain(c.rule);+ expect(read(ledger)).toBe(bytes);+ expect(allowList(c.settings)).toEqual([c.rule]);+ expect(read(c.target.path)).toContain(SKILLS_BLOCK_BEGIN);+ });+ });++ test('a ledger written by a newer gbrain says to upgrade', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ mkdirSync(join(b.home, '.gbrain'), { recursive: true });+ writeFileSync(join(b.home, '.gbrain', 'skill-loading.json'), JSON.stringify({ version: 2, entries: [] }));+ expect(ctx(b).run().detail).toContain('newer gbrain');+ });+ });++ test('a ledger write that fails undoes the block and the rule, so a retry and opt-out leave nothing behind', async () => {+ const b = box();+ await withEnv(b.env, async () => {+ const c = ctx(b);+ const dir = join(b.home, '.gbrain');+ mkdirSync(dir, { recursive: true });+ chmodSync(dir, 0o500);+ let failed: SkillsBlockOutcome;+ try {+ failed = c.run();+ } finally {+ chmodSync(dir, 0o755);+ }+ expect(failed).toMatchObject({ action: 'preserve', reason: 'write_failed' });+ expect(failed.detail).toContain('undone');+ expect(existsSync(c.target.path)).toBe(false);+ expect(allowList(c.settings)).toEqual([]);+ expect(c.run().permission).toMatchObject({ change: 'added' });+ expect(readSkillLoadingLedger()[0]).toMatchObject({ allow_owned: true, created_file: true });+ expect(c.run({ skillLoading: 'off' }).permission).toMatchObject({ change: 'removed' });+ expect(existsSync(c.target.path)).toBe(false);+ expect(allowList(c.settings)).toEqual([]);+ });+ });++ test('an explicit spring skipped for a reason the user must fix counts as failed; a remembered one does not', () => {+ const base = { harness: 'hermes', path: '/home/alice-example/.hermes/SOUL.md', action: 'skip', state_before: 'no_file', detail: 'x', reason: 'hermes_soul_missing' } as const;+ expect(skillsOutcomeFailed({ ...base, decision: { value: 'spring', source: 'flag' } })).toBe(true);+ expect(skillsOutcomeFailed({ ...base, decision: { value: 'spring', source: 'env' } })).toBe(true);+ expect(skillsOutcomeFailed({ ...base, decision: { value: 'spring', source: 'prior' } })).toBe(false);+ expect(skillsOutcomeFailed({ ...base, reason: undefined, decision: { value: 'off', source: 'default' } })).toBe(false);+ });+});+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();