@winspan/claude-forge 8.51.1 → 8.53.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CLAUDE.md +5 -5
  2. package/dist/cli/commands/skills.d.ts.map +1 -1
  3. package/dist/cli/commands/skills.js +115 -0
  4. package/dist/cli/commands/skills.js.map +1 -1
  5. package/dist/core/constants.d.ts +2 -0
  6. package/dist/core/constants.d.ts.map +1 -1
  7. package/dist/core/constants.js +4 -0
  8. package/dist/core/constants.js.map +1 -1
  9. package/dist/daemon/index.d.ts.map +1 -1
  10. package/dist/daemon/index.js +11 -1
  11. package/dist/daemon/index.js.map +1 -1
  12. package/dist/daemon/skill-sync.d.ts +21 -0
  13. package/dist/daemon/skill-sync.d.ts.map +1 -0
  14. package/dist/daemon/skill-sync.js +75 -0
  15. package/dist/daemon/skill-sync.js.map +1 -0
  16. package/dist/hooks/notification.sh +1 -1
  17. package/dist/hooks/post-tool-use.sh +1 -1
  18. package/dist/hooks/pre-tool-use.sh +1 -1
  19. package/dist/hooks/stop.sh +1 -1
  20. package/dist/hooks/user-prompt-submit.sh +1 -1
  21. package/dist/skills/official/code-simplifier.md +37 -1
  22. package/dist/skills/official/find-skills.md +120 -1
  23. package/dist/skills/official/official-api-design.md +14 -1
  24. package/dist/skills/official/official-architecture-decision.md +22 -1
  25. package/dist/skills/official/official-db-schema-design.md +19 -1
  26. package/dist/skills/official/official-debug.md +9 -1
  27. package/dist/skills/official/official-pr-review.md +1 -1
  28. package/dist/skills/official/official-security-hardening.md +7 -1
  29. package/dist/skills/official/planning-with-files.md +206 -2
  30. package/dist/skills/official/ui-ux-pro-max.md +88 -1
  31. package/dist/skills/official/webapp-testing.md +85 -1
  32. package/dist/skills/registry.d.ts +1 -1
  33. package/dist/skills/registry.d.ts.map +1 -1
  34. package/dist/skills/registry.js +2 -2
  35. package/dist/skills/registry.js.map +1 -1
  36. package/dist/skills/semantic-matcher.d.ts +2 -1
  37. package/dist/skills/semantic-matcher.d.ts.map +1 -1
  38. package/dist/skills/semantic-matcher.js +6 -3
  39. package/dist/skills/semantic-matcher.js.map +1 -1
  40. package/dist/skills/upgrade-engine.d.ts +91 -0
  41. package/dist/skills/upgrade-engine.d.ts.map +1 -0
  42. package/dist/skills/upgrade-engine.js +436 -0
  43. package/dist/skills/upgrade-engine.js.map +1 -0
  44. package/dist/skills/upgrade-prompt.d.ts +20 -0
  45. package/dist/skills/upgrade-prompt.d.ts.map +1 -0
  46. package/dist/skills/upgrade-prompt.js +75 -0
  47. package/dist/skills/upgrade-prompt.js.map +1 -0
  48. package/docs/design/skill-ai-upgrade-spec-20260518-1930.md +297 -0
  49. package/docs/implementation/daemon-skill-sync-changelog-20260518-2000.md +22 -0
  50. package/docs/implementation/skill-ai-upgrade-changelog-20260518-1930.md +49 -0
  51. package/package.json +1 -1
  52. package/src/cli/commands/skills.ts +143 -0
  53. package/src/core/constants.ts +5 -0
  54. package/src/daemon/index.ts +11 -1
  55. package/src/daemon/skill-sync.ts +88 -0
  56. package/src/hooks/notification.sh +1 -1
  57. package/src/hooks/post-tool-use.sh +1 -1
  58. package/src/hooks/pre-tool-use.sh +1 -1
  59. package/src/hooks/stop.sh +1 -1
  60. package/src/hooks/user-prompt-submit.sh +1 -1
  61. package/src/skills/official/code-simplifier.md +37 -1
  62. package/src/skills/official/find-skills.md +120 -1
  63. package/src/skills/official/official-api-design.md +14 -1
  64. package/src/skills/official/official-architecture-decision.md +22 -1
  65. package/src/skills/official/official-db-schema-design.md +19 -1
  66. package/src/skills/official/official-debug.md +9 -1
  67. package/src/skills/official/official-pr-review.md +1 -1
  68. package/src/skills/official/official-security-hardening.md +7 -1
  69. package/src/skills/official/planning-with-files.md +206 -2
  70. package/src/skills/official/ui-ux-pro-max.md +88 -1
  71. package/src/skills/official/webapp-testing.md +85 -1
  72. package/src/skills/registry.ts +2 -2
  73. package/src/skills/semantic-matcher.ts +6 -3
  74. package/src/skills/upgrade-engine.ts +541 -0
  75. package/src/skills/upgrade-prompt.ts +84 -0
  76. package/tests/unit/daemon/skill-sync.test.ts +75 -0
  77. package/tests/unit/skills/upgrade-engine-parse.test.ts +138 -0
  78. package/tests/unit/skills/upgrade-engine.test.ts +401 -0
  79. package/tests/unit/skills/upgrade-prompt.test.ts +89 -0
@@ -0,0 +1,541 @@
1
+ /**
2
+ * upgrade-engine.ts
3
+ *
4
+ * Orchestrates the AI-assisted official skill upgrade pipeline.
5
+ * Does NOT contain AI prompt strings — those live in upgrade-prompt.ts.
6
+ */
7
+
8
+ import { execSync, exec } from 'node:child_process';
9
+ import { promises as fs, readFileSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { promisify } from 'node:util';
12
+ import matter from 'gray-matter';
13
+ import type { OfficialSkill } from './official-skills.js';
14
+ import { buildEvaluationPrompt } from './upgrade-prompt.js';
15
+ import type { ClaudeProvider } from '../core/ai/provider.js';
16
+ import { logger } from '../core/utils/logger.js';
17
+
18
+ const execAsync = promisify(exec);
19
+
20
+ // ── Public types ────────────────────────────────────────────────────────────
21
+
22
+ export interface CandidateSkill {
23
+ id: string;
24
+ source: string; // 'agent-skills' | 'superpowers'
25
+ filePath: string;
26
+ name: string;
27
+ description: string;
28
+ keywords: string[];
29
+ content: string;
30
+ }
31
+
32
+ export interface MatchResult {
33
+ officialId: string;
34
+ score: number; // 0-100
35
+ }
36
+
37
+ export type UpgradeAction = 'upgrade' | 'merge' | 'skip';
38
+
39
+ export interface UpgradeDecision {
40
+ action: UpgradeAction;
41
+ confidence: number; // 0-100
42
+ reasoning: string;
43
+ merged_content: string | null;
44
+ }
45
+
46
+ export interface ReportEntry {
47
+ officialId: string;
48
+ candidateId: string;
49
+ candidateSource: string;
50
+ action: UpgradeAction | 'error' | 'needs_review';
51
+ confidence: number;
52
+ reasoning: string;
53
+ candidateFilePath: string;
54
+ merged_content: string | null;
55
+ }
56
+
57
+ // ── Default candidate sources ───────────────────────────────────────────────
58
+
59
+ export const DEFAULT_SOURCES: Array<{ name: string; url: string }> = [
60
+ { name: 'agent-skills', url: 'https://github.com/addyosmani/agent-skills.git' },
61
+ { name: 'superpowers', url: 'https://github.com/obra/superpowers.git' },
62
+ ];
63
+
64
+ // ── Helpers ─────────────────────────────────────────────────────────────────
65
+
66
+ /**
67
+ * Parse a .md file into a CandidateSkill.
68
+ * If frontmatter is missing, falls back to filename-based id.
69
+ */
70
+ function parseCandidateFile(filePath: string, sourceName: string): CandidateSkill | null {
71
+ try {
72
+ const raw = readFileSync(filePath, 'utf-8');
73
+ const parsed = matter(raw);
74
+ const { data } = parsed;
75
+
76
+ const fileName = path.basename(filePath, '.md');
77
+ const id = typeof data.name === 'string' ? data.name : fileName;
78
+ const name = typeof data.name === 'string' ? data.name : fileName;
79
+ const description = typeof data.description === 'string' ? data.description : '';
80
+
81
+ const rawKeywords: unknown = data.keywords ?? data.tags;
82
+ const keywords: string[] = Array.isArray(rawKeywords)
83
+ ? rawKeywords.filter((k): k is string => typeof k === 'string')
84
+ : [];
85
+
86
+ return {
87
+ id,
88
+ source: sourceName,
89
+ filePath,
90
+ name,
91
+ description,
92
+ keywords,
93
+ content: raw,
94
+ };
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Recursively scan a directory for .md files.
102
+ * Supports both directory/SKILL.md format (agent-skills) and flat *.md format.
103
+ */
104
+ async function scanMdFiles(dir: string): Promise<string[]> {
105
+ const results: string[] = [];
106
+
107
+ async function walk(current: string): Promise<void> {
108
+ let entries: import('node:fs').Dirent[];
109
+ try {
110
+ entries = await fs.readdir(current, { withFileTypes: true });
111
+ } catch {
112
+ return;
113
+ }
114
+
115
+ for (const entry of entries) {
116
+ const fullPath = path.join(current, entry.name);
117
+ if (entry.isDirectory()) {
118
+ // Check for SKILL.md inside this directory (agent-skills format)
119
+ const skillMd = path.join(fullPath, 'SKILL.md');
120
+ try {
121
+ await fs.access(skillMd);
122
+ results.push(skillMd);
123
+ } catch {
124
+ // Recurse into sub-directories that don't have SKILL.md directly
125
+ await walk(fullPath);
126
+ }
127
+ } else if (entry.isFile() && entry.name.endsWith('.md') && entry.name !== 'README.md') {
128
+ results.push(fullPath);
129
+ }
130
+ }
131
+ }
132
+
133
+ await walk(dir);
134
+ return results;
135
+ }
136
+
137
+ // ── Exported pipeline functions ─────────────────────────────────────────────
138
+
139
+ /**
140
+ * Clone or pull each source into `candidatesDir/<source.name>/`, then scan
141
+ * all .md files and parse them into CandidateSkill objects.
142
+ * Individual source failures are caught and logged; they do not abort the run.
143
+ */
144
+ export async function pullCandidates(
145
+ sources: Array<{ name: string; url: string }>,
146
+ candidatesDir: string,
147
+ ): Promise<CandidateSkill[]> {
148
+ await fs.mkdir(candidatesDir, { recursive: true });
149
+
150
+ const candidates: CandidateSkill[] = [];
151
+
152
+ for (const source of sources) {
153
+ const targetDir = path.join(candidatesDir, source.name);
154
+
155
+ let exists = false;
156
+ try {
157
+ await fs.access(targetDir);
158
+ exists = true;
159
+ } catch { /* not exists */ }
160
+
161
+ // Try pull/clone, but don't abort scan if pull fails on existing dir
162
+ try {
163
+ if (exists) {
164
+ logger.info(`[upgrade] Pulling ${source.name}...`);
165
+ await execAsync(`git -C "${targetDir}" pull --ff-only`, { timeout: 60_000 });
166
+ } else {
167
+ logger.info(`[upgrade] Cloning ${source.name}...`);
168
+ await execAsync(`git clone --depth=1 "${source.url}" "${targetDir}"`, { timeout: 120_000 });
169
+ }
170
+ } catch (err) {
171
+ const msg = err instanceof Error ? err.message : String(err);
172
+ if (exists) {
173
+ logger.warn(`[upgrade] ${source.name} pull failed (using existing checkout): ${msg}`);
174
+ } else {
175
+ logger.warn(`[upgrade] ${source.name} clone failed, skipping: ${msg}`);
176
+ continue;
177
+ }
178
+ }
179
+
180
+ // Always scan if dir exists (even when pull fails — old checkout is better than nothing)
181
+ try {
182
+ const mdFiles = await scanMdFiles(targetDir);
183
+ for (const filePath of mdFiles) {
184
+ const candidate = parseCandidateFile(filePath, source.name);
185
+ if (candidate) {
186
+ candidates.push(candidate);
187
+ }
188
+ }
189
+ logger.info(`[upgrade] ${source.name}: ${mdFiles.length} .md files found`);
190
+ } catch (err) {
191
+ const msg = err instanceof Error ? err.message : String(err);
192
+ logger.warn(`[upgrade] Skipping source ${source.name}: ${msg}`);
193
+ }
194
+ }
195
+
196
+ return candidates;
197
+ }
198
+
199
+ /**
200
+ * Match a candidate skill to the best official skill using keyword + name token
201
+ * overlap. Returns null if the best score is below the 30-point threshold.
202
+ */
203
+ export function matchToOfficial(
204
+ candidate: CandidateSkill,
205
+ officialSkills: OfficialSkill[],
206
+ ): MatchResult | null {
207
+ /** Tokenise a string into lowercase words / tokens. */
208
+ function tokenise(text: string): Set<string> {
209
+ return new Set(
210
+ text
211
+ .toLowerCase()
212
+ .replace(/[^a-z0-9一-鿿\s-]/g, ' ')
213
+ .split(/[\s-]+/)
214
+ .filter((t) => t.length > 1),
215
+ );
216
+ }
217
+
218
+ /** Jaccard-like overlap score (0–100). */
219
+ function overlapScore(aSet: Set<string>, bSet: Set<string>): number {
220
+ if (aSet.size === 0 && bSet.size === 0) return 0;
221
+ let intersection = 0;
222
+ for (const t of aSet) {
223
+ if (bSet.has(t)) intersection++;
224
+ }
225
+ const union = new Set([...aSet, ...bSet]).size;
226
+ return union === 0 ? 0 : Math.round((intersection / union) * 100);
227
+ }
228
+
229
+ const candidateKeywordTokens = tokenise(candidate.keywords.join(' '));
230
+ const candidateNameTokens = tokenise(candidate.name + ' ' + candidate.description);
231
+
232
+ let best: MatchResult | null = null;
233
+
234
+ for (const official of officialSkills) {
235
+ const officialKeywordTokens = tokenise(official.keywords.join(' '));
236
+ const officialNameTokens = tokenise(official.name + ' ' + official.description);
237
+
238
+ // keyword overlap (weight 60) + name/description token overlap (weight 40)
239
+ const keywordScore = overlapScore(candidateKeywordTokens, officialKeywordTokens);
240
+ const nameScore = overlapScore(candidateNameTokens, officialNameTokens);
241
+ let combined = Math.round(keywordScore * 0.6 + nameScore * 0.4);
242
+
243
+ // Substring boost: candidate id/name contains official keyword (or vice versa)
244
+ // helps with English↔中文 token mismatch (e.g. "debugging" ↔ "debug"/"调试")
245
+ const candidateText = (candidate.id + ' ' + candidate.name + ' ' + candidate.description).toLowerCase();
246
+ const officialText = (official.name + ' ' + official.description).toLowerCase();
247
+ for (const kw of official.keywords) {
248
+ const kwLower = kw.toLowerCase();
249
+ if (kwLower.length >= 3 && candidateText.includes(kwLower)) {
250
+ combined = Math.max(combined, 50);
251
+ break;
252
+ }
253
+ }
254
+ for (const kw of candidate.keywords) {
255
+ const kwLower = kw.toLowerCase();
256
+ if (kwLower.length >= 3 && officialText.includes(kwLower)) {
257
+ combined = Math.max(combined, 50);
258
+ break;
259
+ }
260
+ }
261
+
262
+ if (combined >= 15) {
263
+ if (!best || combined > best.score) {
264
+ best = { officialId: official.name, score: combined };
265
+ }
266
+ }
267
+ }
268
+
269
+ return best;
270
+ }
271
+
272
+ /**
273
+ * Ask the AI provider to evaluate whether a candidate should upgrade / merge /
274
+ * skip the matched official skill. Returns a parsed UpgradeDecision.
275
+ *
276
+ * On JSON parse failure → returns { action: 'skip', confidence: 0, reasoning:
277
+ * 'AI response could not be parsed', merged_content: null } with needs_review=true
278
+ * embedded in the reasoning (caller promotes to needs_review).
279
+ */
280
+ export async function evaluateWithAI(
281
+ candidate: CandidateSkill,
282
+ official: OfficialSkill,
283
+ aiProvider: ClaudeProvider,
284
+ ): Promise<UpgradeDecision & { needs_review?: boolean }> {
285
+ const { system, user } = buildEvaluationPrompt(candidate, official);
286
+
287
+ let raw: string;
288
+ try {
289
+ raw = await aiProvider.complete(user, {
290
+ system,
291
+ maxTokens: 1200,
292
+ timeoutMs: 45_000,
293
+ maxRetries: 2,
294
+ });
295
+ } catch (err) {
296
+ const msg = err instanceof Error ? err.message : String(err);
297
+ return {
298
+ action: 'skip',
299
+ confidence: 0,
300
+ reasoning: `AI 调用失败: ${msg}`,
301
+ merged_content: null,
302
+ needs_review: true,
303
+ };
304
+ }
305
+
306
+ // Strip markdown code fences if model wrapped the JSON
307
+ const stripped = raw
308
+ .replace(/^```(?:json)?\s*/im, '')
309
+ .replace(/\s*```$/im, '')
310
+ .trim();
311
+
312
+ try {
313
+ const parsed = JSON.parse(stripped) as Record<string, unknown>;
314
+
315
+ const validActions = new Set<string>(['upgrade', 'merge', 'skip']);
316
+ const action = typeof parsed.action === 'string' && validActions.has(parsed.action)
317
+ ? (parsed.action as UpgradeAction)
318
+ : 'skip';
319
+
320
+ const confidence =
321
+ typeof parsed.confidence === 'number'
322
+ ? Math.max(0, Math.min(100, parsed.confidence))
323
+ : 0;
324
+
325
+ const reasoning =
326
+ typeof parsed.reasoning === 'string' ? parsed.reasoning : '';
327
+
328
+ const merged_content =
329
+ typeof parsed.merged_content === 'string' ? parsed.merged_content : null;
330
+
331
+ return { action, confidence, reasoning, merged_content };
332
+ } catch {
333
+ return {
334
+ action: 'skip',
335
+ confidence: 0,
336
+ reasoning: `AI 返回内容无法解析为 JSON,需人工审核。原始响应片段: ${stripped.slice(0, 200)}`,
337
+ merged_content: null,
338
+ needs_review: true,
339
+ };
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Write the upgrade report as a markdown file with embedded HTML comment
345
+ * machine markers for `applyDecisions` to parse.
346
+ */
347
+ export async function generateReport(
348
+ entries: ReportEntry[],
349
+ outputPath: string,
350
+ stats: { total: number; matched: number; unmatched: number },
351
+ ): Promise<void> {
352
+ const now = new Date();
353
+ const timestamp = now.toISOString().replace('T', ' ').slice(0, 16);
354
+
355
+ const actionCounts = { upgrade: 0, merge: 0, skip: 0, error: 0, needs_review: 0 };
356
+ for (const e of entries) {
357
+ if (e.action in actionCounts) {
358
+ actionCounts[e.action as keyof typeof actionCounts]++;
359
+ }
360
+ }
361
+
362
+ const lines: string[] = [
363
+ '# Skill Upgrade Report',
364
+ '',
365
+ `Generated: ${timestamp}`,
366
+ '',
367
+ '## Summary',
368
+ '',
369
+ '| Metric | Count |',
370
+ '|--------|-------|',
371
+ `| Candidates scanned | ${stats.total} |`,
372
+ `| Matched to official | ${stats.matched} |`,
373
+ `| Action: upgrade | ${actionCounts.upgrade} |`,
374
+ `| Action: merge | ${actionCounts.merge} |`,
375
+ `| Action: skip | ${actionCounts.skip} |`,
376
+ `| Needs review | ${actionCounts.needs_review} |`,
377
+ `| Error | ${actionCounts.error} |`,
378
+ `| Unmatched | ${stats.unmatched} |`,
379
+ '',
380
+ '## Per-Skill Decisions',
381
+ '',
382
+ ];
383
+
384
+ for (const entry of entries) {
385
+ lines.push(`### ${entry.officialId}`);
386
+ lines.push(`- **Action**: ${entry.action}`);
387
+ lines.push(`- **Confidence**: ${entry.confidence}%`);
388
+ lines.push(`- **Candidate**: \`${entry.candidateSource}/${entry.candidateId}\``);
389
+ lines.push(`- **Candidate path**: \`${entry.candidateFilePath}\``);
390
+ lines.push(`- **Reasoning**: ${entry.reasoning}`);
391
+
392
+ // Machine-readable marker for applyDecisions
393
+ lines.push('');
394
+ lines.push(`<!-- upgrade-entry: ${entry.officialId} | ${entry.candidateFilePath} | ${entry.action} -->`);
395
+
396
+ if (entry.action === 'merge' && entry.merged_content) {
397
+ lines.push('');
398
+ lines.push('<!-- merged-content-begin -->');
399
+ lines.push(entry.merged_content);
400
+ lines.push('<!-- merged-content-end -->');
401
+ }
402
+
403
+ lines.push('');
404
+ }
405
+
406
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
407
+ await fs.writeFile(outputPath, lines.join('\n'), 'utf-8');
408
+ logger.info(`[upgrade] Report written to ${outputPath}`);
409
+ }
410
+
411
+ /**
412
+ * Apply the decisions recorded in a report file to the official skills directory.
413
+ *
414
+ * Safety checks:
415
+ * 1. `git status --porcelain <officialDir>` must be clean
416
+ * 2. Full backup created in `backupBaseDir/<YYYYMMDD-HHMM>/` (conflict → -2/-3)
417
+ *
418
+ * Returns { applied, skipped, backupPath }.
419
+ */
420
+ export async function applyDecisions(
421
+ reportPath: string,
422
+ officialDir: string,
423
+ backupBaseDir: string,
424
+ ): Promise<{ applied: number; skipped: number; backupPath: string }> {
425
+ // 1. Check git working tree is clean
426
+ try {
427
+ const { stdout } = await execAsync(`git status --porcelain "${officialDir}"`);
428
+ if (stdout.trim().length > 0) {
429
+ throw new Error(
430
+ `Working tree is dirty in ${officialDir}. Commit or stash changes before applying.\n${stdout}`,
431
+ );
432
+ }
433
+ } catch (err) {
434
+ // If git is not available or it's not a repo, rethrow only for dirty-tree errors
435
+ const msg = err instanceof Error ? err.message : String(err);
436
+ if (msg.includes('Working tree is dirty')) throw err;
437
+ logger.warn(`[upgrade] git status check failed (not a git repo?): ${msg}`);
438
+ }
439
+
440
+ // 2. Create timestamped backup directory
441
+ const ts = new Date()
442
+ .toISOString()
443
+ .replace(/[-:]/g, '')
444
+ .replace('T', '-')
445
+ .slice(0, 13); // YYYYMMDD-HHM -> need YYYYMMDD-HHMM format
446
+ const tsFormatted = (() => {
447
+ const d = new Date();
448
+ const YYYY = d.getFullYear();
449
+ const MM = String(d.getMonth() + 1).padStart(2, '0');
450
+ const DD = String(d.getDate()).padStart(2, '0');
451
+ const HH = String(d.getHours()).padStart(2, '0');
452
+ const mm = String(d.getMinutes()).padStart(2, '0');
453
+ return `${YYYY}${MM}${DD}-${HH}${mm}`;
454
+ })();
455
+
456
+ let backupPath = path.join(backupBaseDir, tsFormatted);
457
+ // Handle conflict: try -2, -3, ...
458
+ let suffix = 2;
459
+ while (true) {
460
+ try {
461
+ await fs.access(backupPath);
462
+ // Directory exists — try next suffix
463
+ backupPath = path.join(backupBaseDir, `${tsFormatted}-${suffix}`);
464
+ suffix++;
465
+ } catch {
466
+ break; // doesn't exist, we can use it
467
+ }
468
+ }
469
+ await fs.mkdir(backupPath, { recursive: true });
470
+
471
+ // Copy all .md files from officialDir into backup
472
+ const officialFiles = (await fs.readdir(officialDir)).filter((f) => f.endsWith('.md'));
473
+ for (const file of officialFiles) {
474
+ await fs.copyFile(path.join(officialDir, file), path.join(backupPath, file));
475
+ }
476
+ logger.info(`[upgrade] Backed up ${officialFiles.length} files to ${backupPath}`);
477
+
478
+ // 3. Parse report
479
+ const reportContent = await fs.readFile(reportPath, 'utf-8');
480
+
481
+ // Parse <!-- upgrade-entry: id | path | action --> markers
482
+ const entryPattern = /<!-- upgrade-entry: (.+?) \| (.+?) \| (.+?) -->/g;
483
+ let match: RegExpExecArray | null;
484
+
485
+ const entries: Array<{ officialId: string; candidatePath: string; action: string }> = [];
486
+ while ((match = entryPattern.exec(reportContent)) !== null) {
487
+ entries.push({
488
+ officialId: match[1].trim(),
489
+ candidatePath: match[2].trim(),
490
+ action: match[3].trim(),
491
+ });
492
+ }
493
+
494
+ // Parse merged content blocks
495
+ const mergedContentMap = new Map<string, string>();
496
+ // Associate merged-content blocks with the preceding entry
497
+ const mergedPattern =
498
+ /<!-- upgrade-entry: (.+?) \| (.+?) \| merge -->[\s\S]*?<!-- merged-content-begin -->\n([\s\S]*?)\n<!-- merged-content-end -->/g;
499
+ while ((match = mergedPattern.exec(reportContent)) !== null) {
500
+ mergedContentMap.set(match[1].trim(), match[3]);
501
+ }
502
+
503
+ let applied = 0;
504
+ let skipped = 0;
505
+
506
+ for (const entry of entries) {
507
+ if (entry.action === 'skip' || entry.action === 'error' || entry.action === 'needs_review') {
508
+ skipped++;
509
+ continue;
510
+ }
511
+
512
+ const targetFile = path.join(officialDir, `${entry.officialId}.md`);
513
+
514
+ try {
515
+ if (entry.action === 'upgrade') {
516
+ // Copy candidate file content
517
+ const candidateContent = await fs.readFile(entry.candidatePath, 'utf-8');
518
+ await fs.writeFile(targetFile, candidateContent, 'utf-8');
519
+ applied++;
520
+ logger.info(`[upgrade] Applied upgrade: ${entry.officialId}`);
521
+ } else if (entry.action === 'merge') {
522
+ const mergedContent = mergedContentMap.get(entry.officialId);
523
+ if (mergedContent) {
524
+ await fs.writeFile(targetFile, mergedContent, 'utf-8');
525
+ applied++;
526
+ logger.info(`[upgrade] Applied merge: ${entry.officialId}`);
527
+ } else {
528
+ logger.warn(`[upgrade] Merge entry ${entry.officialId} has no merged content; skipping`);
529
+ skipped++;
530
+ }
531
+ }
532
+ } catch (err) {
533
+ const msg = err instanceof Error ? err.message : String(err);
534
+ logger.error(`[upgrade] Failed to apply ${entry.officialId}: ${msg}`);
535
+ skipped++;
536
+ }
537
+ }
538
+
539
+ logger.info(`[upgrade] Apply complete: ${applied} applied, ${skipped} skipped`);
540
+ return { applied, skipped, backupPath };
541
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * upgrade-prompt.ts
3
+ *
4
+ * Builds the system + user prompts for AI-assisted skill evaluation.
5
+ * Pure functions — no I/O, no side effects.
6
+ */
7
+
8
+ import type { CandidateSkill } from './upgrade-engine.js';
9
+ import type { OfficialSkill } from './official-skills.js';
10
+
11
+ const MAX_CONTENT_CHARS = 2000;
12
+
13
+ /**
14
+ * Truncate content to at most `maxChars` characters, appending an ellipsis
15
+ * marker so the model knows the text was cut.
16
+ */
17
+ function truncate(text: string, maxChars = MAX_CONTENT_CHARS): string {
18
+ if (text.length <= maxChars) return text;
19
+ return text.slice(0, maxChars) + '\n\n...[content truncated]';
20
+ }
21
+
22
+ /**
23
+ * Build system + user prompts for evaluating whether a candidate skill should
24
+ * upgrade, merge with, or skip an official skill.
25
+ *
26
+ * The system prompt defines the decision criteria and output JSON contract.
27
+ * The user prompt contains the two skill bodies (capped at 2000 chars each).
28
+ */
29
+ export function buildEvaluationPrompt(
30
+ candidate: CandidateSkill,
31
+ official: OfficialSkill,
32
+ ): { system: string; user: string } {
33
+ const system = `你是 Claude Code skill 内容评估专家。
34
+
35
+ 你的任务是比较"候选 skill"和"官方 skill",决定如何处理。
36
+
37
+ ## 评估维度
38
+ - **主题重叠度**:两个 skill 覆盖的领域是否高度相关
39
+ - **内容质量**:深度、广度、实例丰富程度、可操作性
40
+ - **互补性**:候选是否包含官方 skill 未涵盖的独特章节
41
+
42
+ ## 决策标准
43
+ - **skip**:主题不重叠,或官方 skill 已完整覆盖候选内容,合并无额外价值
44
+ - **upgrade**:候选覆盖官方 skill 的全部核心要点,且整体质量明显更高(深度/广度提升 ≥30%),用候选直接替换官方版本
45
+ - **merge**:主题相同但各有独特章节,合并后整体价值更高,需要生成合并后完整内容
46
+
47
+ ## 输出格式
48
+ 必须返回严格的 JSON,不含任何其他文本、代码块标记或注释:
49
+ {"action":"upgrade|merge|skip","confidence":0-100,"reasoning":"简短中文说明(<200字)","merged_content":null或合并后完整md字符串}
50
+
51
+ ## merged_content 规则
52
+ - action = merge → 提供合并后的完整 .md 文件内容(含 frontmatter)
53
+ - action = upgrade → null(直接使用候选原文)
54
+ - action = skip → null`;
55
+
56
+ const user = `## 官方 Skill(目标)
57
+
58
+ **ID**: ${official.name}
59
+ **描述**: ${official.description}
60
+ **关键词**: ${official.keywords.join(', ') || '(无)'}
61
+
62
+ \`\`\`markdown
63
+ ${truncate(official.content)}
64
+ \`\`\`
65
+
66
+ ---
67
+
68
+ ## 候选 Skill(来源: ${candidate.source})
69
+
70
+ **ID**: ${candidate.id}
71
+ **名称**: ${candidate.name}
72
+ **描述**: ${candidate.description}
73
+ **关键词**: ${candidate.keywords.join(', ') || '(无)'}
74
+
75
+ \`\`\`markdown
76
+ ${truncate(candidate.content)}
77
+ \`\`\`
78
+
79
+ ---
80
+
81
+ 请评估候选 skill 相对于官方 skill 的升级价值,返回 JSON。`;
82
+
83
+ return { system, user };
84
+ }
@@ -0,0 +1,75 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync, readFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { syncSkills } from '../../../src/daemon/skill-sync.js';
6
+
7
+ describe('syncSkills', () => {
8
+ let tmpRoot: string;
9
+ let sourceDir: string;
10
+ let targetDir: string;
11
+
12
+ beforeEach(() => {
13
+ tmpRoot = mkdtempSync(join(tmpdir(), 'forge-skill-sync-'));
14
+ sourceDir = join(tmpRoot, 'src-skills');
15
+ targetDir = join(tmpRoot, 'target-skills');
16
+ mkdirSync(sourceDir, { recursive: true });
17
+ });
18
+
19
+ afterEach(() => {
20
+ rmSync(tmpRoot, { recursive: true, force: true });
21
+ });
22
+
23
+ it('source dir not found → returns zero counts, does not throw', () => {
24
+ const result = syncSkills({ sourceDir: join(tmpRoot, 'nonexistent'), targetDir });
25
+ expect(result.copied).toBe(0);
26
+ expect(result.checked).toBe(0);
27
+ expect(result.skipped_userOwned).toBe(0);
28
+ });
29
+
30
+ it('source and target identical → copied=0, checked=1', () => {
31
+ const content = '# official-debug skill\nsome content\n';
32
+ writeFileSync(join(sourceDir, 'official-debug.md'), content);
33
+ mkdirSync(targetDir, { recursive: true });
34
+ writeFileSync(join(targetDir, 'official-debug.md'), content);
35
+
36
+ const result = syncSkills({ sourceDir, targetDir });
37
+ expect(result.copied).toBe(0);
38
+ expect(result.checked).toBe(1);
39
+ });
40
+
41
+ it('source and target differ → copied=1, target updated', () => {
42
+ writeFileSync(join(sourceDir, 'official-debug.md'), '# new content\n');
43
+ mkdirSync(targetDir, { recursive: true });
44
+ writeFileSync(join(targetDir, 'official-debug.md'), '# old content\n');
45
+
46
+ const result = syncSkills({ sourceDir, targetDir });
47
+ expect(result.copied).toBe(1);
48
+ expect(result.checked).toBe(1);
49
+ expect(readFileSync(join(targetDir, 'official-debug.md'), 'utf-8')).toContain('new content');
50
+ });
51
+
52
+ it('target missing file → copies it from source', () => {
53
+ writeFileSync(join(sourceDir, 'official-debug.md'), '# official-debug\n');
54
+ mkdirSync(targetDir, { recursive: true });
55
+ // target has no official-debug.md
56
+
57
+ const result = syncSkills({ sourceDir, targetDir });
58
+ expect(result.copied).toBe(1);
59
+ expect(existsSync(join(targetDir, 'official-debug.md'))).toBe(true);
60
+ });
61
+
62
+ it('user-only skill in target (not in source) → untouched', () => {
63
+ // source has one official skill
64
+ writeFileSync(join(sourceDir, 'official-debug.md'), '# official-debug\n');
65
+ mkdirSync(targetDir, { recursive: true });
66
+ // target also has a user-custom skill not present in source
67
+ writeFileSync(join(targetDir, 'my-custom-skill.md'), '# custom\n');
68
+
69
+ syncSkills({ sourceDir, targetDir });
70
+
71
+ // user skill must still exist and be unchanged
72
+ expect(existsSync(join(targetDir, 'my-custom-skill.md'))).toBe(true);
73
+ expect(readFileSync(join(targetDir, 'my-custom-skill.md'), 'utf-8')).toContain('custom');
74
+ });
75
+ });