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): prevent built-in skill downgrades

xd-bobo59debbf26965
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 f7dd2e2505..68ab56e9db 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
@@ -24,14 +24,70 @@ def split_frontmatter(content):
def _strip_plain_comment(value):
- for index, char in enumerate(value):
- if char == "#" and index > 0 and value[index - 1].isspace():
+ quote = None
+ escaped = False
+ index = 0
+ while index < len(value):
+ char = value[index]
+ if quote == '"':
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ quote = None
+ elif quote == "'":
+ if char == "'" and index + 1 < len(value) and value[index + 1] == "'":
+ index += 1
+ elif char == "'":
+ quote = None
+ elif char in {'"', "'"}:
+ quote = char
+ elif char == "#" and index > 0 and value[index - 1].isspace():
return value[:index].rstrip()
+ index += 1
return value.strip()
+def _parse_flow_collection(value):
+ stack = []
+ quote = None
+ escaped = False
+ index = 0
+ while index < len(value):
+ char = value[index]
+ if quote == '"':
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ quote = None
+ elif quote == "'":
+ if char == "'" and index + 1 < len(value) and value[index + 1] == "'":
+ index += 1
+ elif char == "'":
+ quote = None
+ elif char in {'"', "'"}:
+ quote = char
+ elif char in "[{":
+ stack.append("]" if char == "[" else "}")
+ elif char in "]}":
+ if not stack or stack.pop() != char:
+ raise FrontmatterError(f"Mismatched flow delimiter '{char}'")
+ if not stack and value[index + 1 :].strip():
+ raise FrontmatterError("Unexpected content after flow collection")
+ index += 1
+
+ if quote is not None or escaped:
+ raise FrontmatterError("Unterminated quoted scalar in flow collection")
+ if stack:
+ raise FrontmatterError(f"Unterminated flow collection, expected '{stack[-1]}'")
+ return [] if value.startswith("[") else {}
+
+
def _parse_scalar(raw):
- value = raw.strip()
+ value = _strip_plain_comment(raw)
if value.startswith('"'):
try:
parsed = json.loads(value)
@@ -43,7 +99,6 @@ def _parse_scalar(raw):
raise FrontmatterError("Invalid single-quoted scalar")
return value[1:-1].replace("''", "'")
- value = _strip_plain_comment(value)
lowered = value.lower()
if lowered in {"null", "~"} or value == "":
return None
@@ -54,14 +109,11 @@ def _parse_scalar(raw):
if re.fullmatch(r"[-+]?(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)", value):
return float(value)
if value.startswith(("[", "{")):
- closing = "]" if value.startswith("[") else "}"
- if not value.endswith(closing):
- raise FrontmatterError(f"Unterminated flow value, expected '{closing}'")
# The bundled tools only inspect scalar name/description values. Keep
# flow collection contents opaque while preserving the collection type,
# so valid YAML bare scalars such as [Read, Grep] and {owner: me} do not
# require PyYAML or JSON syntax.
- return [] if value.startswith("[") else {}
+ return _parse_flow_collection(value)
return value
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 d28e696439..e67d14af98 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
@@ -77,7 +77,7 @@ describe('built-in Skills', () => {
);
fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nUpdated\n');
- const updated = await prepareBuiltInSkills(input);
+ const updated = await prepareBuiltInSkills({ ...input, bundleVersion: 2 });
expect(updated.changed).toBe(true);
expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
'Updated',
@@ -85,6 +85,26 @@ describe('built-in Skills', () => {
expect(fs.realpathSync(link)).toBe(fs.realpathSync(descriptor.absolutePath));
});
+ it('does not let an older or conflicting bundle overwrite newer shared bytes', async () => {
+ const input = fixture();
+ fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nNewer bundle\n');
+ const newer = await prepareBuiltInSkills({ ...input, bundleVersion: 2 });
+ const descriptor = newer.descriptors[0]!;
+ const installed = fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8');
+
+ 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: 1 });
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(older.warnings.join('\n')).toContain('only carries older bundle 1');
+
+ const conflicting = await prepareBuiltInSkills({ ...input, bundleVersion: 2 });
+ expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toBe(installed);
+ expect(conflicting.warnings.join('\n')).toContain('bundle version 2 was reused');
+ });
+
it('keeps a user-owned same-name Skill while retaining the Cindy copy', async () => {
const input = fixture();
const userSkill = path.join(input.homeDir, '.agents', 'skills', 'cindy-skill-creator');
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 ee0fbd4d88..2b99d84abb 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -17,6 +17,8 @@ export const BUILT_IN_LEARN_SKILL_NAME = CINDY_LEARN_NAME;
const BUILT_IN_SKILL_NAMES = [BUILT_IN_SKILL_CREATOR_NAME, BUILT_IN_LEARN_SKILL_NAME] as const;
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 = 1;
export interface BuiltInSkillDescriptor {
name: string;
@@ -29,6 +31,7 @@ export interface PrepareBuiltInSkillsOptions {
userDataDir: string;
appDataDir?: string;
homeDir?: string;
+ bundleVersion?: number;
withSharedMutation?: typeof withSkillMutation;
}
@@ -39,7 +42,8 @@ export interface PrepareBuiltInSkillsResult {
}
interface MaterializationManifest {
- schemaVersion: 1;
+ schemaVersion: 2;
+ bundleVersion: number;
fingerprints: Record<string, string>;
}
@@ -100,16 +104,22 @@ async function readManifest(root: string): Promise<MaterializationManifest> {
await fsp.readFile(path.join(root, MANIFEST_FILE), 'utf8'),
) as Partial<MaterializationManifest>;
if (
- parsed.schemaVersion === 1 &&
+ parsed.schemaVersion === 2 &&
+ Number.isSafeInteger(parsed.bundleVersion) &&
+ (parsed.bundleVersion ?? 0) >= 0 &&
parsed.fingerprints &&
typeof parsed.fingerprints === 'object'
) {
- return { schemaVersion: 1, fingerprints: parsed.fingerprints };
+ return {
+ schemaVersion: 2,
+ bundleVersion: parsed.bundleVersion!,
+ fingerprints: parsed.fingerprints,
+ };
}
} catch {
// Missing or unreadable app-owned metadata is repaired from bundled bytes.
}
- return { schemaVersion: 1, fingerprints: {} };
+ return { schemaVersion: 2, bundleVersion: 0, fingerprints: {} };
}
async function writeManifest(root: string, manifest: MaterializationManifest): Promise<void> {
@@ -318,19 +328,39 @@ export async function prepareBuiltInSkills(
const descriptors = builtInSkillDescriptors(options.userDataDir, options.appDataDir);
const warnings: string[] = [];
let changed = false;
+ const bundleVersion = options.bundleVersion ?? BUILT_IN_SKILLS_BUNDLE_VERSION;
+ if (!Number.isSafeInteger(bundleVersion) || bundleVersion < 1) {
+ throw new Error(`invalid built-in Skill bundle version: ${bundleVersion}`);
+ }
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);
+ const newerBundleIsInstalled = manifest.bundleVersion > bundleVersion;
+ if (newerBundleIsInstalled) {
+ warnings.push(
+ `kept built-in Skill bundle ${manifest.bundleVersion}; this build only carries older bundle ${bundleVersion}`,
+ );
+ }
for (const descriptor of descriptors) {
const source = path.join(options.bundledRoot, descriptor.name);
try {
const fingerprint = await hashDirectory(source);
const installedFingerprint = await hashDirectory(descriptor.absolutePath).catch(() => null);
- if (
- installedFingerprint !== fingerprint ||
- manifest.fingerprints[descriptor.name] !== fingerprint
+ const recordedFingerprint = manifest.fingerprints[descriptor.name];
+ const sameVersionConflict = (
+ manifest.bundleVersion === bundleVersion &&
+ recordedFingerprint !== undefined &&
+ recordedFingerprint !== fingerprint
+ );
+ if (sameVersionConflict) {
+ 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;
@@ -388,12 +418,15 @@ export async function prepareBuiltInSkills(
}
}
- try {
- await writeManifest(root, manifest);
- } catch (error) {
- warnings.push(
- `could not save built-in Skill manifest: ${error instanceof Error ? error.message : String(error)}`,
- );
+ if (!newerBundleIsInstalled) {
+ manifest.bundleVersion = bundleVersion;
+ try {
+ await writeManifest(root, manifest);
+ } catch (error) {
+ warnings.push(
+ `could not save built-in Skill manifest: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
}
return true;
}, { waitMs: BUILT_IN_SKILL_MUTATION_WAIT_MS });