Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): make built-in skill updates fail closed

xd-bobob0f257c57cdc
diff --git a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
index 1e7204a006..6435861ff8 100644
--- a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
+++ b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
@@ -261,7 +261,7 @@ def _parse_scalar(raw, in_flow=False):
def _block_value(lines, start, style, indent_indicator=None):
cursor = start
captured = []
- minimum_indent = None
+ content_indent = indent_indicator
while cursor < len(lines):
line = lines[cursor]
if line.strip() and not line[:1].isspace():
@@ -270,14 +270,18 @@ def _block_value(lines, start, style, indent_indicator=None):
indent = len(line) - len(line.lstrip(" "))
if indent == 0 or line.startswith("\t"):
raise FrontmatterError("Block scalars must use space indentation")
- if indent_indicator is not None and indent < indent_indicator:
+ if content_indent is None:
+ # YAML fixes an implicit block scalar's indentation from its
+ # first non-empty content line; later lines may be deeper but
+ # never shallower.
+ content_indent = indent
+ elif indent < content_indent:
raise FrontmatterError(
- f"Block scalar content must be indented at least {indent_indicator} spaces"
+ f"Block scalar content must be indented at least {content_indent} spaces"
)
- minimum_indent = indent if minimum_indent is None else min(minimum_indent, indent)
captured.append(line)
cursor += 1
- indent = indent_indicator if indent_indicator is not None else minimum_indent or 0
+ indent = content_indent or 0
values = [line[indent:] if line.strip() else "" for line in captured]
if style == "|":
return "\n".join(values).rstrip("\n"), cursor
diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
index 36de879305..5aef4e65e4 100644
--- a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
@@ -105,7 +105,7 @@ describe('built-in Skills', () => {
);
fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nUpdated\n');
- const updated = await prepareAndProjectBuiltInSkills({ ...input, bundleVersion: 4 });
+ const updated = await prepareAndProjectBuiltInSkills({ ...input, bundleVersion: 5 });
expect(updated.changed).toBe(true);
expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
'Updated',
@@ -133,6 +133,69 @@ describe('built-in Skills', () => {
expect(conflicting.warnings.join('\n')).toContain('bundle version 2 was reused');
});
+ it('fails closed when an existing bundle manifest is corrupt', async () => {
+ const input = fixture();
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const descriptor = newer.descriptors[0]!;
+ const manifestPath = path.join(
+ path.dirname(descriptor.absolutePath),
+ '.cindy-system-skills.json',
+ );
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+ fs.writeFileSync(manifestPath, '{ invalid json');
+ fs.writeFileSync(
+ path.join(input.source, 'SKILL.md'),
+ '---\nname: cindy-skill-creator\ndescription: Old bundle\n---\n\n# Old\n',
+ );
+
+ const older = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(older.changed).toBe(false);
+ expect(older.warnings.join('\n')).toContain('manifest is unavailable');
+ });
+
+ it('does not infer a first install when the manifest is missing beside existing Skills', async () => {
+ const input = fixture();
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const descriptor = newer.descriptors[0]!;
+ const manifestPath = path.join(
+ path.dirname(descriptor.absolutePath),
+ '.cindy-system-skills.json',
+ );
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+ fs.unlinkSync(manifestPath);
+
+ const retried = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(retried.changed).toBe(false);
+ expect(retried.warnings.join('\n')).toContain('manifest is unavailable');
+ });
+
+ it('restores the atomic manifest backup before applying version ordering', async () => {
+ const input = fixture();
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const descriptor = newer.descriptors[0]!;
+ const manifestPath = path.join(
+ path.dirname(descriptor.absolutePath),
+ '.cindy-system-skills.json',
+ );
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+ fs.renameSync(manifestPath, `${manifestPath}.bak`);
+ fs.writeFileSync(
+ path.join(input.source, 'SKILL.md'),
+ '---\nname: cindy-skill-creator\ndescription: Old bundle\n---\n\n# Old\n',
+ );
+
+ const older = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+
+ expect(fs.existsSync(manifestPath)).toBe(true);
+ expect(fs.existsSync(`${manifestPath}.bak`)).toBe(false);
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(older.warnings.join('\n')).toContain('only carries older bundle 4');
+ });
+
it('advances the bundle version only after every Skill is ready and retries partial upgrades', async () => {
const input = fixture();
await prepareBuiltInSkills(input);
@@ -143,25 +206,33 @@ describe('built-in Skills', () => {
path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
);
- const partial = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+ const partial = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
const manifestPath = path.join(
path.dirname(partial.descriptors[0]!.absolutePath),
'.cindy-system-skills.json',
);
- expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(3);
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(4);
expect(partial.warnings.join('\n')).toContain('missing SKILL.md');
+ expect(
+ fs.readFileSync(path.join(partial.descriptors[0]!.absolutePath, 'SKILL.md'), 'utf8'),
+ ).not.toContain('Creator v2');
fs.renameSync(
path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
path.join(input.bundledRoot, 'learn', 'SKILL.md'),
);
- const retried = await prepareBuiltInSkills({ ...input, bundleVersion: 4 });
+ const retried = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
expect(retried.warnings).toEqual([]);
- expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(4);
- expect(fs.readFileSync(path.join(
- retried.descriptors.find((descriptor) => descriptor.name === 'learn')!.absolutePath,
- 'SKILL.md',
- ), 'utf8')).toBe('Learn v2\n');
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(5);
+ expect(
+ fs.readFileSync(
+ path.join(
+ retried.descriptors.find((descriptor) => descriptor.name === 'learn')!.absolutePath,
+ 'SKILL.md',
+ ),
+ 'utf8',
+ ),
+ ).toBe('Learn v2\n');
});
it('keeps a user-owned same-name Skill while retaining the Cindy copy', async () => {
diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts
index 04d81d23dd..c2712cfe23 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -9,7 +9,7 @@ import {
CINDY_SKILL_CREATOR_NAME,
} from '../../shared/cindyBuiltInSkills';
import { withSkillMutation } from '../skillhub/sharedMutationLease';
-import { atomicWriteFileSync } from '../utils/atomicWriteFile';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
export const BUILT_IN_SKILL_CREATOR_NAME = CINDY_SKILL_CREATOR_NAME;
export const BUILT_IN_LEARN_SKILL_NAME = CINDY_LEARN_NAME;
@@ -18,7 +18,7 @@ const BUILT_IN_SKILL_NAMES = [BUILT_IN_SKILL_CREATOR_NAME, BUILT_IN_LEARN_SKILL_
const MANIFEST_FILE = '.cindy-system-skills.json';
const BUILT_IN_SKILL_MUTATION_WAIT_MS = 5_000;
/** Increment whenever shipped built-in Skill bytes change between releases. */
-export const BUILT_IN_SKILLS_BUNDLE_VERSION = 3;
+export const BUILT_IN_SKILLS_BUNDLE_VERSION = 4;
export interface BuiltInSkillDescriptor {
name: string;
@@ -120,17 +120,56 @@ async function hashDirectory(root: string): Promise<string> {
return hash.digest('hex');
}
-async function readManifest(root: string): Promise<MaterializationManifest> {
+function emptyManifest(): MaterializationManifest {
+ return { schemaVersion: 2, bundleVersion: 0, fingerprints: {} };
+}
+
+async function hasExistingMaterializedSkill(
+ descriptors: readonly BuiltInSkillDescriptor[],
+): Promise<boolean> {
+ for (const descriptor of descriptors) {
+ try {
+ await fsp.lstat(descriptor.absolutePath);
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ return false;
+}
+
+async function readManifest(
+ root: string,
+ descriptors: readonly BuiltInSkillDescriptor[],
+): Promise<MaterializationManifest> {
+ const manifestPath = path.join(root, MANIFEST_FILE);
+ const hasInstalledSkills = await hasExistingMaterializedSkill(descriptors);
+ let raw: string | null;
+ try {
+ raw = readAtomicFileSync(manifestPath);
+ } catch (error) {
+ throw new Error(
+ `could not read built-in Skill manifest without risking a downgrade: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ if (raw === null) {
+ if (hasInstalledSkills) {
+ throw new Error('built-in Skill manifest is missing while materialized Skills still exist');
+ }
+ return emptyManifest();
+ }
+
try {
- const parsed = JSON.parse(
- await fsp.readFile(path.join(root, MANIFEST_FILE), 'utf8'),
- ) as Partial<MaterializationManifest>;
+ const parsed = JSON.parse(raw) as Partial<MaterializationManifest>;
if (
parsed.schemaVersion === 2 &&
Number.isSafeInteger(parsed.bundleVersion) &&
(parsed.bundleVersion ?? 0) >= 0 &&
parsed.fingerprints &&
- typeof parsed.fingerprints === 'object'
+ typeof parsed.fingerprints === 'object' &&
+ !Array.isArray(parsed.fingerprints) &&
+ Object.values(parsed.fingerprints).every((value) => typeof value === 'string')
) {
return {
schemaVersion: 2,
@@ -138,10 +177,21 @@ async function readManifest(root: string): Promise<MaterializationManifest> {
fingerprints: parsed.fingerprints,
};
}
- } catch {
- // Missing or unreadable app-owned metadata is repaired from bundled bytes.
+ } catch (error) {
+ if (hasInstalledSkills) {
+ throw new Error(
+ `built-in Skill manifest is invalid while materialized Skills still exist: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ return emptyManifest();
}
- return { schemaVersion: 2, bundleVersion: 0, fingerprints: {} };
+ if (hasInstalledSkills) {
+ throw new Error(
+ 'built-in Skill manifest has an invalid shape while materialized Skills still exist',
+ );
+ }
+ return emptyManifest();
}
async function writeManifest(root: string, manifest: MaterializationManifest): Promise<void> {
@@ -494,56 +544,100 @@ export async function prepareBuiltInSkills(
const mutate = options.withSharedMutation ?? withSkillMutation;
const locked = await mutate(BUILT_IN_SKILL_NAMES, async () => {
await fsp.mkdir(root, { recursive: true });
- const manifest = await readManifest(root);
+ let manifest: MaterializationManifest;
+ try {
+ manifest = await readManifest(root, descriptors);
+ } catch (error) {
+ warnings.push(
+ `kept existing built-in Skills because their manifest is unavailable: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ return true;
+ }
const newerBundleIsInstalled = manifest.bundleVersion > bundleVersion;
- let bundleReady = true;
if (newerBundleIsInstalled) {
warnings.push(
`kept built-in Skill bundle ${manifest.bundleVersion}; this build only carries older bundle ${bundleVersion}`,
);
+ return true;
}
+ const plans: Array<{
+ descriptor: BuiltInSkillDescriptor;
+ source: string;
+ fingerprint: string;
+ installedFingerprint: string | null;
+ }> = [];
for (const descriptor of descriptors) {
const source = path.join(options.bundledRoot, descriptor.name);
try {
+ if (!(await fsp.stat(path.join(source, 'SKILL.md')).catch(() => null))?.isFile()) {
+ throw new Error(`bundled Skill is missing SKILL.md: ${source}`);
+ }
const fingerprint = await hashDirectory(source);
- const installedFingerprint = await hashDirectory(descriptor.absolutePath).catch(() => null);
+ const installedFingerprint = await hashDirectory(descriptor.absolutePath).catch(
+ () => null,
+ );
const recordedFingerprint = manifest.fingerprints[descriptor.name];
- const sameVersionConflict = (
+ const sameVersionConflict =
manifest.bundleVersion === bundleVersion &&
recordedFingerprint !== undefined &&
- recordedFingerprint !== fingerprint
- );
+ recordedFingerprint !== fingerprint;
if (sameVersionConflict) {
- bundleReady = false;
warnings.push(
`kept built-in Skill ${descriptor.name} because bundle version ${bundleVersion} was reused for different bytes`,
);
- } else if (
- !newerBundleIsInstalled &&
- (installedFingerprint !== fingerprint || recordedFingerprint !== fingerprint)
- ) {
- changed = (await materializeSkill(source, descriptor.absolutePath, fingerprint)) || changed;
- manifest.fingerprints[descriptor.name] = fingerprint;
+ continue;
}
+ plans.push({ descriptor, source, fingerprint, installedFingerprint });
} catch (error) {
- bundleReady = false;
warnings.push(
`could not materialize built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,
);
- continue;
}
-
}
- if (!newerBundleIsInstalled) {
- if (bundleReady) manifest.bundleVersion = bundleVersion;
+ if (plans.length !== descriptors.length) return true;
+
+ const nextManifest: MaterializationManifest = {
+ schemaVersion: 2,
+ bundleVersion,
+ fingerprints: Object.fromEntries(
+ plans.map(({ descriptor, fingerprint }) => [descriptor.name, fingerprint]),
+ ),
+ };
+ const manifestNeedsUpdate =
+ manifest.bundleVersion !== bundleVersion ||
+ plans.some(
+ ({ descriptor, fingerprint }) => manifest.fingerprints[descriptor.name] !== fingerprint,
+ );
+ if (manifestNeedsUpdate) {
try {
- await writeManifest(root, manifest);
+ // Commit the version/fingerprints before swapping any directories. If a
+ // later materialization is interrupted, old builds see the newer version
+ // and cannot downgrade the bytes; this build repairs them on its next run.
+ await writeManifest(root, nextManifest);
+ manifest = nextManifest;
+ changed = true;
} catch (error) {
warnings.push(
`could not save built-in Skill manifest: ${error instanceof Error ? error.message : String(error)}`,
);
+ return true;
+ }
+ }
+
+ for (const { descriptor, source, fingerprint, installedFingerprint } of plans) {
+ if (
+ installedFingerprint === fingerprint &&
+ manifest.fingerprints[descriptor.name] === fingerprint
+ ) continue;
+ try {
+ changed =
+ (await materializeSkill(source, descriptor.absolutePath, fingerprint)) || changed;
+ } catch (error) {
+ warnings.push(
+ `could not materialize built-in Skill ${descriptor.name}: ${error instanceof Error ? error.message : String(error)}`,
+ );
}
}
return true;