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): close built-in skill review gaps

xd-bobo5fc3c533e655
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 6435861ff8..8e86b45f80 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
@@ -202,6 +202,78 @@ def _parse_flow_collection(value):
return {} if is_mapping else []
+def _quoted_scalar_is_closed(value, quote):
+ index = 1
+ while index < len(value):
+ char = value[index]
+ if quote == '"':
+ if char == "\\":
+ index += 2
+ continue
+ if char == '"':
+ return True
+ elif char == "'":
+ if index + 1 < len(value) and value[index + 1] == "'":
+ index += 2
+ continue
+ return True
+ index += 1
+ return False
+
+
+def _ends_with_unescaped_backslash(value):
+ count = 0
+ for char in reversed(value):
+ if char != "\\":
+ break
+ count += 1
+ return count % 2 == 1
+
+
+def _fold_quoted_scalar_lines(parts, quote):
+ value = parts[0].strip()
+ blank_lines = 0
+ for part in parts[1:]:
+ content = part.strip()
+ if not content:
+ blank_lines += 1
+ continue
+ if quote == '"' and _ends_with_unescaped_backslash(value):
+ value = value[:-1] + content
+ elif blank_lines:
+ # YAML folds one ordinary physical line break to a space and keeps
+ # each intervening empty line as a newline. JSON needs the escaped
+ # spelling while the single-quoted parser accepts the character.
+ newline = "\\n" if quote == '"' else "\n"
+ value += newline * blank_lines + content
+ else:
+ value += " " + content
+ blank_lines = 0
+ return value
+
+
+def _collect_quoted_scalar(lines, start, raw_value):
+ value = raw_value.strip()
+ quote = value[0]
+ parts = [value]
+ cursor = start + 1
+ while not _quoted_scalar_is_closed("\n".join(parts), quote):
+ if cursor >= len(lines):
+ raise FrontmatterError("Unterminated quoted scalar")
+ line = lines[cursor]
+ if line.strip() and not line[:1].isspace():
+ raise FrontmatterError(
+ f"Quoted scalar continuation must be indented on line {cursor + 1}"
+ )
+ if line.startswith("\t"):
+ raise FrontmatterError(
+ f"Quoted scalar continuation must use space indentation on line {cursor + 1}"
+ )
+ parts.append(line)
+ cursor += 1
+ return _fold_quoted_scalar_lines(parts, quote), cursor
+
+
def _parse_scalar(raw, in_flow=False):
value = _strip_plain_comment(raw)
if value.startswith('"'):
@@ -490,6 +562,11 @@ def parse_frontmatter(frontmatter_text):
result[key] = value
continue
+ if raw_value.lstrip().startswith(('"', "'")):
+ raw_value, index = _collect_quoted_scalar(lines, index, raw_value)
+ result[key] = _parse_scalar(raw_value)
+ continue
+
result[key] = _parse_scalar(raw_value)
index += 1
return result
diff --git a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
index 1bc8d53d42..e822715775 100644
--- a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
+++ b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
@@ -6,6 +6,19 @@ import {
} from '../invocationGrant.js';
describe('Learn invocation grant', () => {
+ const createPersistentConsumer = (
+ readLatest: () => Promise<{ messageId: string; text: string }>,
+ consumed = new Set<string>(),
+ ) => createLearnInvocationGrantConsumer(
+ readLatest,
+ async (sessionId, messageId) => {
+ const key = `${sessionId}\0${messageId}`;
+ if (consumed.has(key)) return false;
+ consumed.add(key);
+ return true;
+ },
+ );
+
it.each([
['/learn', { input: '', sourceKind: 'session' }],
['/learn release flow', { input: 'release flow', sourceKind: 'freetext' }],
@@ -27,7 +40,7 @@ describe('Learn invocation grant', () => {
messageId: 'message-1',
text: '/learn hub:market:release-notes keep checks',
}));
- const consume = createLearnInvocationGrantConsumer(readLatest);
+ const consume = createPersistentConsumer(readLatest);
await expect(consume({
callerSessionId: 'session-1',
@@ -51,7 +64,7 @@ describe('Learn invocation grant', () => {
});
it('consumes each persisted user invocation only once', async () => {
- const consume = createLearnInvocationGrantConsumer(async () => ({
+ const consume = createPersistentConsumer(async () => ({
messageId: 'message-1',
text: '/learn release flow',
}));
@@ -67,4 +80,25 @@ describe('Learn invocation grant', () => {
errorCode: 'USER_REQUEST_REQUIRED',
});
});
+
+ it('rejects a persisted invocation after the consumer is recreated', async () => {
+ const consumed = new Set<string>();
+ const readLatest = async () => ({
+ messageId: 'message-1',
+ text: '/learn release flow',
+ });
+ const request = {
+ callerSessionId: 'session-1',
+ input: 'release flow',
+ sourceKind: 'freetext' as const,
+ };
+
+ await expect(createPersistentConsumer(readLatest, consumed)(request)).resolves.toEqual({
+ ok: true,
+ });
+ await expect(createPersistentConsumer(readLatest, consumed)(request)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'USER_REQUEST_REQUIRED',
+ });
+ });
});
diff --git a/apps/desktop/src/main/learn-host/invocationGrant.ts b/apps/desktop/src/main/learn-host/invocationGrant.ts
index 7d5977243a..c4146dac85 100644
--- a/apps/desktop/src/main/learn-host/invocationGrant.ts
+++ b/apps/desktop/src/main/learn-host/invocationGrant.ts
@@ -25,8 +25,12 @@ type ReadLatestUserInvocation = (
sessionId: string,
) => Promise<LatestUserInvocation | null>;
+type ConsumeUserInvocation = (
+ sessionId: string,
+ messageId: string,
+) => Promise<boolean>;
+
const messageRowid = sql<number>`"messages"."rowid"`;
-const MAX_CONSUMED_INVOCATIONS = 2_048;
function normalizeInput(value: string): string {
return value.trim().replace(/\s+/g, ' ');
@@ -69,10 +73,8 @@ function matchesInvocation(
export function createLearnInvocationGrantConsumer(
readLatestUserInvocation: ReadLatestUserInvocation,
+ consumeUserInvocation: ConsumeUserInvocation,
): (request: StartSkillLearningParams) => Promise<LearnInvocationGrantResult> {
- const consumed = new Set<string>();
- const consumptionOrder: string[] = [];
-
return async (request) => {
let latest: LatestUserInvocation | null;
try {
@@ -92,20 +94,26 @@ export function createLearnInvocationGrantConsumer(
message: 'Start Learn by invoking /learn directly in the current task.',
};
}
- const consumptionKey = `${request.callerSessionId}\0${latest.messageId}`;
- if (consumed.has(consumptionKey)) {
+ let consumed: boolean;
+ try {
+ consumed = await consumeUserInvocation(
+ request.callerSessionId,
+ latest.messageId,
+ );
+ } catch (error) {
+ return {
+ ok: false,
+ errorCode: isDbClientNotReadyError(error) ? 'HOST_NOT_READY' : 'INTERNAL',
+ message: 'Cindy could not record the current /learn request.',
+ };
+ }
+ if (!consumed) {
return {
ok: false,
errorCode: 'USER_REQUEST_REQUIRED',
message: 'This /learn request has already been used.',
};
}
-
- consumed.add(consumptionKey);
- consumptionOrder.push(consumptionKey);
- if (consumptionOrder.length > MAX_CONSUMED_INVOCATIONS) {
- consumed.delete(consumptionOrder.shift()!);
- }
return { ok: true };
};
}
@@ -139,6 +147,38 @@ async function readLatestUserInvocation(
};
}
+async function consumeUserInvocation(
+ sessionId: string,
+ messageId: string,
+): Promise<boolean> {
+ const dbClient = tryGetDbClient();
+ if (!dbClient) {
+ throw Object.assign(new Error('DbClient not ready'), { code: 'HOST_NOT_READY' });
+ }
+ // Claim the exact persisted user message with one compare-and-update. Keeping
+ // the marker in agent_meta makes the one-shot grant survive app restarts;
+ // JSON object metadata is preserved, while malformed/non-object metadata
+ // fails closed instead of being overwritten.
+ const result = await dbClient.exec(
+ `UPDATE messages
+ SET agent_meta = json_set(COALESCE(agent_meta, '{}'), '$.cindyLearnInvocationConsumed', 1)
+ WHERE id = ?
+ AND session_id = ?
+ AND role = 'user'
+ AND rewind_at IS NULL
+ AND CASE
+ WHEN agent_meta IS NULL THEN 1
+ WHEN json_valid(agent_meta) THEN
+ json_type(agent_meta) = 'object'
+ AND json_type(agent_meta, '$.cindyLearnInvocationConsumed') IS NULL
+ ELSE 0
+ END`,
+ [messageId, sessionId],
+ );
+ return result.changes === 1;
+}
+
export const consumeLearnInvocationGrant = createLearnInvocationGrantConsumer(
readLatestUserInvocation,
+ consumeUserInvocation,
);
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 5aef4e65e4..6116f47911 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: 5 });
+ const updated = await prepareAndProjectBuiltInSkills({ ...input, bundleVersion: 6 });
expect(updated.changed).toBe(true);
expect(fs.readFileSync(path.join(descriptor.absolutePath, 'SKILL.md'), 'utf8')).toContain(
'Updated',
@@ -206,12 +206,12 @@ describe('built-in Skills', () => {
path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
);
- const partial = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const partial = await prepareBuiltInSkills({ ...input, bundleVersion: 6 });
const manifestPath = path.join(
path.dirname(partial.descriptors[0]!.absolutePath),
'.cindy-system-skills.json',
);
- expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(4);
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(5);
expect(partial.warnings.join('\n')).toContain('missing SKILL.md');
expect(
fs.readFileSync(path.join(partial.descriptors[0]!.absolutePath, 'SKILL.md'), 'utf8'),
@@ -221,9 +221,9 @@ describe('built-in Skills', () => {
path.join(input.bundledRoot, 'learn', 'SKILL.md.missing'),
path.join(input.bundledRoot, 'learn', 'SKILL.md'),
);
- const retried = await prepareBuiltInSkills({ ...input, bundleVersion: 5 });
+ const retried = await prepareBuiltInSkills({ ...input, bundleVersion: 6 });
expect(retried.warnings).toEqual([]);
- expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(5);
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).bundleVersion).toBe(6);
expect(
fs.readFileSync(
path.join(
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 c2712cfe23..c85ff55ed0 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -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 = 4;
+export const BUILT_IN_SKILLS_BUNDLE_VERSION = 5;
export interface BuiltInSkillDescriptor {
name: string;
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 83fc6231f6..b9ae55b77d 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -802,25 +802,90 @@ describe('registerSkillhubIpc usage handlers', () => {
});
it('passes readable SKILL.md content and path into diagnosis context', async () => {
+ const sender = { id: 31, on: vi.fn(), once: vi.fn() };
+ const mdPath = '/repo/.pi/skills/authorized/demo/SKILL.md';
+ scanAllSkills.mockResolvedValueOnce({
+ skills: [{
+ absolutePath: '/physical/demo',
+ discoveredPath: '/repo/.pi/skills/authorized/demo',
+ scope: 'project',
+ projectRoot: '/repo',
+ }],
+ sources: [],
+ });
readSkillRawFile.mockResolvedValueOnce({ success: true, content: 'skill body' });
getLocalSkillUsageDiagnosisContext.mockResolvedValueOnce({
success: true,
context: { prompt: 'diagnose' },
});
+ await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
const handler = handlers.get('skillhub:get-usage-diagnosis-context');
- const result = await handler?.({}, { name: 'word-doc', mdPath: 'C:\\skills\\word-doc\\SKILL.md' });
+ const result = await handler?.({ sender }, { name: 'word-doc', mdPath });
- expect(readSkillRawFile).toHaveBeenCalledWith({ filePath: 'C:\\skills\\word-doc\\SKILL.md' });
+ expect(readSkillRawFile).toHaveBeenCalledWith({ filePath: mdPath });
expect(getLocalSkillUsageDiagnosisContext).toHaveBeenCalledWith({
skillName: 'word-doc',
currentSkillContent: 'skill body',
- skillPath: 'C:\\skills\\word-doc\\SKILL.md',
+ skillPath: mdPath,
client: defaultDbClient,
});
expect(result).toEqual({ success: true, context: { prompt: 'diagnose' } });
});
+ it('reads built-in Skill usage through the attested scan root', async () => {
+ const builtInRoot = path.join(fixtureRoot, 'system-skills', 'cindy-skill-creator');
+ const mdPath = path.join(builtInRoot, 'SKILL.md');
+ fs.mkdirSync(builtInRoot, { recursive: true });
+ fs.writeFileSync(mdPath, '# Built in\n');
+ const { registerSkillhubIpc } = await import('../registerIpc');
+ registerSkillhubIpc({
+ getMaker: () => ({ listAgentSkills }) as never,
+ getManagedSkillRoots,
+ getBuiltInSkills: () => [{
+ name: 'cindy-skill-creator',
+ absolutePath: builtInRoot,
+ nativeClaudePath: '/tmp/claude-home/skills/cindy-skill-creator',
+ }],
+ getAllowedProjectRoots,
+ marketService: marketService as never,
+ publishService: { publish, cancel } as never,
+ });
+ scanAllSkills.mockResolvedValueOnce({
+ skills: [{
+ absolutePath: builtInRoot,
+ discoveredPath: builtInRoot,
+ scope: 'user',
+ kind: 'skill',
+ }],
+ sources: [],
+ });
+ readSkillRawFile.mockResolvedValueOnce({ success: true, content: 'built-in body' });
+ getLocalSkillUsageSummary.mockResolvedValueOnce({
+ success: true,
+ summary: { totalUseCount: 1 },
+ refreshing: false,
+ });
+ const sender = { id: 32, on: vi.fn(), once: vi.fn() };
+ await handlers.get('skillhub:scan')?.({ sender }, { projects: [] });
+
+ const result = await handlers.get('skillhub:get-usage-summary')?.(
+ { sender },
+ { name: 'cindy-skill-creator', mdPath },
+ );
+
+ expect(readSkillRawFile).toHaveBeenCalledWith({
+ filePath: mdPath,
+ attestedRoot: fs.realpathSync(builtInRoot),
+ });
+ expect(getLocalSkillUsageSummary).toHaveBeenCalledWith({
+ skillName: 'cindy-skill-creator',
+ currentSkillContent: 'built-in body',
+ client: defaultDbClient,
+ });
+ expect(result).toMatchObject({ success: true });
+ });
+
it('drops internal autoSync flag from renderer install params', async () => {
installServiceMocks.install.mockResolvedValueOnce({
success: true,
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 5f03964873..e40607ab5f 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -331,6 +331,18 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
success: false as const,
error: 'path was not granted by this renderer\'s latest SkillHub scan',
});
+ const readScannedSkillRawContent = async (
+ event: Electron.IpcMainInvokeEvent,
+ filePath: string,
+ ): Promise<string | null> => {
+ const grant = await findScannedSkillGrant(event, filePath);
+ if (!grant) return null;
+ const raw = await readSkillRawFile({
+ filePath,
+ ...(grant.builtIn ? { attestedRoot: grant.root } : {}),
+ });
+ return raw.success ? raw.content ?? null : null;
+ };
const normalizePathForCompare = (value: string): string => {
const withoutWindowsNamespace = process.platform === 'win32'
? value.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')
@@ -907,13 +919,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// Claude/Codex 自己的 JSONL 文件里,不复制进 Cindy DB。
ipcMain.handle(
'skillhub:get-usage-summary',
- async (_event, { name, mdPath }: { name: string; mdPath?: string }) => {
+ async (event, { name, mdPath }: { name: string; mdPath?: string }) => {
try {
- let currentSkillContent: string | null = null;
- if (mdPath) {
- const raw = await readSkillRawFile({ filePath: mdPath });
- if (raw.success) currentSkillContent = raw.content ?? null;
- }
+ const currentSkillContent = mdPath
+ ? await readScannedSkillRawContent(event, mdPath)
+ : null;
const readSummary = async () => {
const snapshot = captureUsageDbSnapshot();
scheduleUsageAnalyticsRefresh(snapshot);
@@ -944,13 +954,11 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
// 生成 skill 诊断会话首条消息。只返回统计摘要和 transcript 索引,不复制原始对话内容。
ipcMain.handle(
'skillhub:get-usage-diagnosis-context',
- async (_event, { name, mdPath }: { name: string; mdPath?: string }) => {
+ async (event, { name, mdPath }: { name: string; mdPath?: string }) => {
try {
- let currentSkillContent: string | null = null;
- if (mdPath) {
- const raw = await readSkillRawFile({ filePath: mdPath });
- if (raw.success) currentSkillContent = raw.content ?? null;
- }
+ const currentSkillContent = mdPath
+ ? await readScannedSkillRawContent(event, mdPath)
+ : null;
const readDiagnosisContext = async () => {
const snapshot = captureUsageDbSnapshot();
const result = await getLocalSkillUsageDiagnosisContext({