Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Keep skill updates and the claude-cli settings flag working when a probe or state save fails

garrytan3f9de0e07624
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index 475b6ffcd5..6050352ebe 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -367,9 +367,10 @@ export function oldClaudeCliMessage(version: string | null): string {
/** `claude --version`'s version number, or null, run like a real call (clean
* cwd, scrubbed env) and killed outright after 5 s. */
-function claudeCliVersion(env: NodeJS.ProcessEnv): string | null {
+function claudeCliVersion(env: NodeJS.ProcessEnv): { version: string | null; settled: boolean } {
const r = spawnSync(claudeBin(), ['--version'], { encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', cwd: ensureCleanCwd(), env });
- return /\d+\.\d+\.\d+/.exec(typeof r.stdout === 'string' ? r.stdout : '')?.[0] ?? null;
+ const version = /\d+\.\d+\.\d+/.exec(typeof r.stdout === 'string' ? r.stdout : '')?.[0] ?? null;
+ return { version, settled: version !== null || r.status === 0 || r.signal !== null };
}
/** Oldest claude CLI that gets `--setting-sources ""` (#8342): 2.1.314 fixed
@@ -380,17 +381,20 @@ export const SETTING_SOURCES_MIN_VERSION = '2.1.314';
const settingSourcesByBin = new Map<string, boolean>();
/** Whether the configured CLI is SETTING_SOURCES_MIN_VERSION or newer: one
- * `claude --version` per binary per process; false when it cannot be read. */
+ * `claude --version` per binary per process, false when it cannot be read.
+ * A probe that failed to start or exited non-zero is not remembered, so the
+ * next call probes again; one that hung to the 5 s kill is, so a stuck CLI
+ * costs that wait once. */
function takesNoSettingSources(env: NodeJS.ProcessEnv): boolean {
const bin = claudeBin();
- let known = settingSourcesByBin.get(bin);
- if (known === undefined) {
- const found = claudeCliVersion(env)?.split('.').map(Number);
- const min = SETTING_SOURCES_MIN_VERSION.split('.').map(Number);
- known = !!found && (found[0]! - min[0]! || found[1]! - min[1]! || found[2]! - min[2]!) >= 0;
- settingSourcesByBin.set(bin, known);
- }
- return known;
+ const known = settingSourcesByBin.get(bin);
+ if (known !== undefined) return known;
+ const { version, settled } = claudeCliVersion(env);
+ const found = version?.split('.').map(Number);
+ const min = SETTING_SOURCES_MIN_VERSION.split('.').map(Number);
+ const takes = !!found && (found[0]! - min[0]! || found[1]! - min[1]! || found[2]! - min[2]!) >= 0;
+ if (settled) settingSourcesByBin.set(bin, takes);
+ return takes;
}
/**
@@ -544,7 +548,7 @@ function runClaude(
// regexes only scan text before the marker (an auth-looking essay in
// stdout must never read as a whole-run auth outage).
const headline = isUnknownOptionError(stderr)
- ? oldClaudeCliMessage(claudeCliVersion(env))
+ ? oldClaudeCliMessage(claudeCliVersion(env).version)
: `claude-cli exited ${code}`;
reject(new ClaudeCliProcessError(
`${headline}\n--- raw ---\n${stderr.trim() || stdout.trim()}`,
diff --git a/src/core/skillpack/safe-update.ts b/src/core/skillpack/safe-update.ts
index 6d728d7bed..845356befa 100644
--- a/src/core/skillpack/safe-update.ts
+++ b/src/core/skillpack/safe-update.ts
@@ -327,7 +327,11 @@ async function applySkill(ctx: ApplyContext, outcome: SkillOutcome, js: JournalS
js.status = 'committed';
writeJournal(ctx.journal, ctx.backups);
const bases = Object.fromEntries(outcome.files.filter(f => !f.sharedDep).map(f => [f.rel, f.post]));
- await updateState(state => ({ state: withSkillBases(state, skillsRoot, { [outcome.slug]: bases }), result: null }), { statePath: ctx.opts.statePath });
+ try {
+ await updateState(state => ({ state: withSkillBases(state, skillsRoot, { [outcome.slug]: bases }), result: null }), { statePath: ctx.opts.statePath });
+ } catch (err) {
+ return { ...outcome, result: 'updated', notes: [...outcome.notes, `files updated; the base record was not saved (${(err as Error).message}), so a later update treats this skill as locally edited and skips it`] };
+ }
return { ...outcome, result: 'updated' };
} finally {
rmSync(stage, { recursive: true, force: true });
diff --git a/test/claude-cli-setting-sources-8342.test.ts b/test/claude-cli-setting-sources-8342.test.ts
index 375d51c28f..04eb8cbd1e 100644
--- a/test/claude-cli-setting-sources-8342.test.ts
+++ b/test/claude-cli-setting-sources-8342.test.ts
@@ -4,7 +4,8 @@
* steer gbrain's background calls. `--setting-sources ""` loads no settings
* source and keeps the subscription login. The child gets it only when
* `claude --version` reports SETTING_SOURCES_MIN_VERSION or newer, probed once
- * per binary; an older or unreadable version keeps today's argv.
+ * per binary; an older or unreadable version keeps today's argv, and a probe
+ * that exited non-zero is tried again on the next call.
*
* A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN plays the CLI and records its
* argv; no live CLI or provider account is used.
@@ -91,6 +92,31 @@ describe('claude-cli keeps the user\'s own settings and CLAUDE.md out of the chi
expect(settingSources(await s.call({ GBRAIN_CLAUDE_CLI_USER_SETTINGS: '0' }))).toBe('');
});
+ test('a --version that exits non-zero is not remembered: the next call probes again and gets --setting-sources ""', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'claude-setting-sources-flaky-'));
+ dirs.push(dir);
+ const bin = join(dir, 'claude');
+ writeFileSync(bin, [
+ '#!/bin/sh',
+ `if [ "$1" = "--version" ]; then echo probe >> "${dir}/probes"; if [ ! -f "${dir}/warm" ]; then : > "${dir}/warm"; exit 1; fi; echo '2.1.316 (Claude Code)'; exit 0; fi`,
+ 'cat > /dev/null',
+ `: > "${dir}/argv"`,
+ `for a in "$@"; do printf '[%s]\\n' "$a" >> "${dir}/argv"; done`,
+ `echo '${JSON.stringify(SUCCESS)}'`,
+ ].join('\n') + '\n');
+ chmodSync(bin, 0o755);
+ const call = async () => {
+ await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin }, () => new ClaudeCliLanguageModel('claude-sonnet-5-5').doGenerate({
+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Reply OK' }] }],
+ } as LanguageModelV2CallOptions));
+ return readFileSync(join(dir, 'argv'), 'utf8').trimEnd().split('\n').map((l) => l.slice(1, -1));
+ };
+ expect(settingSources(await call())).toBeNull();
+ expect(settingSources(await call())).toBe('');
+ expect(settingSources(await call())).toBe('');
+ expect(readFileSync(join(dir, 'probes'), 'utf8').trimEnd().split('\n').length).toBe(2);
+ });
+
test('an older or unreadable version keeps today\'s argv', async () => {
for (const line of ['2.1.313 (Claude Code)', '2.0.60 (Claude Code)', 'not a version']) {
const argv = await stub(line).call();
diff --git a/test/skillpack-safe-update.test.ts b/test/skillpack-safe-update.test.ts
index 87064ef0ec..f9a7f8491e 100644
--- a/test/skillpack-safe-update.test.ts
+++ b/test/skillpack-safe-update.test.ts
@@ -83,6 +83,25 @@ const write = (env: Env, rel: string, body: string) => writeFileSync(join(env.ws
const outcome = (result: Awaited<ReturnType<typeof update>>, slug: string) => result.skills.find(s => s.slug === slug)!;
describe('base recording and whole-skill update', () => {
+ test('a state save that fails after the files land keeps the skill updated and finishes the journal', async () => {
+ const env = setup();
+ await scaffold(env);
+ release(env.gbrainRoot, { ...V1, 'demo/SKILL.md': V2['demo/SKILL.md'] });
+ const breakState = () => {
+ if (existsSync(join(env.statePath, 'blocked'))) return;
+ rmSync(env.statePath, { force: true });
+ mkdirSync(join(env.statePath, 'blocked'), { recursive: true });
+ };
+ const result = await update(env, { hooks: { afterRename: breakState } });
+ expect(result.summary).toMatchObject({ updated: 1, current: 1, failed: 0 });
+ expect(read(env, 'demo/SKILL.md')).toBe(V2['demo/SKILL.md']);
+ expect(outcome(result, 'demo').notes.some(n => n.includes('base record was not saved'))).toBe(true);
+ const [journal] = listJournals(env.backups);
+ expect(journal!.status).toBe('complete');
+ expect(journal!.skills.every(s => s.status === 'committed')).toBe(true);
+ expect(result.restore_command).toBeNull();
+ });
+
test('scaffold records bases; an untouched skill updates whole, journaled; a second run is a no-op (repo-less)', async () => {
const env = setup();
expect(spawnSync('git', ['-C', env.ws, 'rev-parse', '--git-dir']).status).not.toBe(0);