metame-cli 1.5.11 → 1.5.13

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 (55) hide show
  1. package/index.js +64 -7
  2. package/package.json +3 -2
  3. package/scripts/daemon-agent-commands.js +6 -2
  4. package/scripts/daemon-bridges.js +23 -9
  5. package/scripts/daemon-claude-engine.js +81 -28
  6. package/scripts/daemon-command-router.js +16 -0
  7. package/scripts/daemon-command-session-route.js +3 -1
  8. package/scripts/daemon-engine-runtime.js +1 -5
  9. package/scripts/daemon-message-pipeline.js +113 -44
  10. package/scripts/daemon-reactive-lifecycle.js +405 -9
  11. package/scripts/daemon-session-commands.js +3 -2
  12. package/scripts/daemon-session-store.js +82 -27
  13. package/scripts/daemon-team-dispatch.js +21 -5
  14. package/scripts/daemon-utils.js +3 -1
  15. package/scripts/daemon.js +1 -0
  16. package/scripts/docs/file-transfer.md +1 -0
  17. package/scripts/hooks/intent-file-transfer.js +2 -1
  18. package/scripts/hooks/intent-perpetual.js +109 -0
  19. package/scripts/hooks/intent-research.js +112 -0
  20. package/scripts/intent-registry.js +4 -0
  21. package/scripts/ops-mission-queue.js +258 -0
  22. package/scripts/ops-verifier.js +197 -0
  23. package/skills/agent-browser/SKILL.md +153 -0
  24. package/skills/agent-reach/SKILL.md +66 -0
  25. package/skills/agent-reach/evolution.json +13 -0
  26. package/skills/deep-research/SKILL.md +77 -0
  27. package/skills/find-skills/SKILL.md +133 -0
  28. package/skills/heartbeat-task-manager/SKILL.md +63 -0
  29. package/skills/macos-local-orchestrator/SKILL.md +192 -0
  30. package/skills/macos-local-orchestrator/agents/openai.yaml +4 -0
  31. package/skills/macos-local-orchestrator/references/tooling-landscape.md +70 -0
  32. package/skills/macos-mail-calendar/SKILL.md +394 -0
  33. package/skills/mcp-installer/SKILL.md +138 -0
  34. package/skills/skill-creator/LICENSE.txt +202 -0
  35. package/skills/skill-creator/README.md +72 -0
  36. package/skills/skill-creator/SKILL.md +96 -0
  37. package/skills/skill-creator/evolution.json +6 -0
  38. package/skills/skill-creator/references/creation-guide.md +116 -0
  39. package/skills/skill-creator/references/evolution-guide.md +74 -0
  40. package/skills/skill-creator/references/output-patterns.md +82 -0
  41. package/skills/skill-creator/references/workflows.md +28 -0
  42. package/skills/skill-creator/scripts/align_all.py +32 -0
  43. package/skills/skill-creator/scripts/auto_evolve_hook.js +247 -0
  44. package/skills/skill-creator/scripts/init_skill.py +303 -0
  45. package/skills/skill-creator/scripts/merge_evolution.py +70 -0
  46. package/skills/skill-creator/scripts/package_skill.py +110 -0
  47. package/skills/skill-creator/scripts/quick_validate.py +103 -0
  48. package/skills/skill-creator/scripts/setup.py +141 -0
  49. package/skills/skill-creator/scripts/smart_stitch.py +82 -0
  50. package/skills/skill-manager/SKILL.md +112 -0
  51. package/skills/skill-manager/scripts/delete_skill.py +31 -0
  52. package/skills/skill-manager/scripts/list_skills.py +61 -0
  53. package/skills/skill-manager/scripts/scan_and_check.py +125 -0
  54. package/skills/skill-manager/scripts/sync_index.py +144 -0
  55. package/skills/skill-manager/scripts/update_helper.py +39 -0
@@ -0,0 +1,32 @@
1
+ import os
2
+ import sys
3
+ import subprocess
4
+
5
+ def align_all(skills_root):
6
+ if not os.path.exists(skills_root):
7
+ print(f"Error: {skills_root} not found")
8
+ return
9
+
10
+ stitch_script = os.path.join(os.path.dirname(__file__), "smart_stitch.py")
11
+
12
+ count = 0
13
+ for item in os.listdir(skills_root):
14
+ skill_dir = os.path.join(skills_root, item)
15
+ if not os.path.isdir(skill_dir):
16
+ continue
17
+
18
+ evolution_json = os.path.join(skill_dir, "evolution.json")
19
+ if os.path.exists(evolution_json):
20
+ print(f"Aligning {item}...")
21
+ # Run the smart_stitch script for this skill
22
+ subprocess.run([sys.executable, stitch_script, skill_dir])
23
+ count += 1
24
+
25
+ print(f"\nFinished. Aligned {count} skills.")
26
+
27
+ if __name__ == "__main__":
28
+ # Use standard skills path
29
+ skills_path = r"C:\Users\20515\.claude\skills"
30
+ if len(sys.argv) > 1:
31
+ skills_path = sys.argv[1]
32
+ align_all(skills_path)
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * skill-creator Auto-Evolve Hook
5
+ *
6
+ * Runs as a Claude Code "Stop" hook. After each session:
7
+ * 1. Detects which skills were active in this session
8
+ * 2. Extracts tool failures and interaction signals
9
+ * 3. If ANTHROPIC_API_KEY is set: uses Haiku to generate structured insights
10
+ * Otherwise: persists raw failure signals directly
11
+ * 4. Calls merge_evolution.py + smart_stitch.py to persist into each skill's SKILL.md
12
+ *
13
+ * Zero MetaMe dependency. Self-contained.
14
+ * Performance target: <50ms when no skills detected, <3s with Haiku analysis.
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const os = require('os');
22
+ const https = require('https');
23
+ const { execSync } = require('child_process');
24
+
25
+ // Paths derived from __dirname (scripts/) — works regardless of install location
26
+ const SKILL_CREATOR_DIR = path.dirname(__dirname); // scripts/ → skill-creator/
27
+ const SKILLS_DIR = path.dirname(SKILL_CREATOR_DIR); // skill-creator/ → skills/
28
+ const MERGE_SCRIPT = path.join(SKILL_CREATOR_DIR, 'scripts', 'merge_evolution.py');
29
+ const STITCH_SCRIPT = path.join(SKILL_CREATOR_DIR, 'scripts', 'smart_stitch.py');
30
+
31
+ const TAIL_BYTES = 40 * 1024; // 40KB — covers ~15-25 turns
32
+
33
+ const IS_CODEX = process.argv.includes('--codex');
34
+
35
+ let input = '';
36
+ process.stdin.setEncoding('utf8');
37
+ process.stdin.on('data', chunk => { input += chunk; });
38
+ process.stdin.on('end', () => {
39
+ (IS_CODEX ? mainCodex() : mainCC()).catch(() => {}).finally(() => process.exit(0));
40
+ });
41
+
42
+ // ── Claude Code mode: full transcript analysis ────────────────────────────────
43
+
44
+ async function mainCC() {
45
+ let data;
46
+ try { data = JSON.parse(input); } catch { return; }
47
+
48
+ const transcriptPath = data.transcript_path;
49
+ if (!transcriptPath || !fs.existsSync(transcriptPath)) return;
50
+
51
+ const tail = readTail(transcriptPath, TAIL_BYTES);
52
+ if (!tail) return;
53
+
54
+ const installedSkills = getInstalledSkills();
55
+ if (installedSkills.length === 0) return;
56
+
57
+ const activeSkills = detectActiveSkills(tail, installedSkills);
58
+ if (activeSkills.length === 0) return;
59
+
60
+ const failures = extractFailures(tail);
61
+ const apiKey = process.env.ANTHROPIC_API_KEY;
62
+
63
+ for (const skillName of activeSkills) {
64
+ const skillDir = path.join(SKILLS_DIR, skillName);
65
+ if (!fs.existsSync(path.join(skillDir, 'SKILL.md'))) continue;
66
+
67
+ let experience;
68
+ if (apiKey) {
69
+ experience = await analyzeWithHaiku(skillName, tail, failures, apiKey);
70
+ } else {
71
+ experience = buildRawExperience(failures);
72
+ }
73
+
74
+ if (!experience) continue;
75
+ persistExperience(skillDir, experience);
76
+ }
77
+ }
78
+
79
+ // ── Codex CLI mode: per-turn signal capture (no transcript available) ─────────
80
+ // Codex notify fires on agent-turn-complete but passes no stdin data.
81
+ // We can only record a timestamped turn event — no Haiku analysis possible.
82
+
83
+ async function mainCodex() {
84
+ const signalFile = path.join(SKILLS_DIR, '.codex_turn_signals.jsonl');
85
+ const entry = JSON.stringify({ ts: new Date().toISOString(), cwd: process.cwd() }) + '\n';
86
+ try { fs.appendFileSync(signalFile, entry); } catch { /* non-fatal */ }
87
+ // No transcript → nothing to evolve right now.
88
+ // Signals accumulate and can be analyzed manually via /evolve.
89
+ }
90
+
91
+ // ── Transcript utilities ──────────────────────────────────────────────────────
92
+
93
+ function readTail(filePath, maxBytes) {
94
+ try {
95
+ const stat = fs.statSync(filePath);
96
+ if (stat.size === 0) return null;
97
+ const size = Math.min(stat.size, maxBytes);
98
+ const buf = Buffer.alloc(size);
99
+ const fd = fs.openSync(filePath, 'r');
100
+ try { fs.readSync(fd, buf, 0, size, Math.max(0, stat.size - size)); }
101
+ finally { fs.closeSync(fd); }
102
+ const text = buf.toString('utf8');
103
+ // Skip first (possibly truncated) line
104
+ const nl = text.indexOf('\n');
105
+ return nl >= 0 ? text.slice(nl + 1) : text;
106
+ } catch { return null; }
107
+ }
108
+
109
+ function extractFailures(tail) {
110
+ const failures = [];
111
+ for (const line of tail.split('\n')) {
112
+ if (!line.trim()) continue;
113
+ try {
114
+ const entry = JSON.parse(line);
115
+ const content = entry?.message?.content;
116
+ if (!Array.isArray(content)) continue;
117
+ for (const block of content) {
118
+ if (block.type === 'tool_result' && block.is_error === true) {
119
+ const errText = typeof block.content === 'string'
120
+ ? block.content
121
+ : (block.content || []).map(c => c.text || '').join('\n');
122
+ failures.push(errText.slice(0, 300));
123
+ }
124
+ }
125
+ } catch { /* skip */ }
126
+ }
127
+ return failures;
128
+ }
129
+
130
+ // ── Skill detection ───────────────────────────────────────────────────────────
131
+
132
+ function getInstalledSkills() {
133
+ try {
134
+ return fs.readdirSync(SKILLS_DIR).filter(name => {
135
+ const skillMd = path.join(SKILLS_DIR, name, 'SKILL.md');
136
+ return fs.existsSync(skillMd);
137
+ });
138
+ } catch { return []; }
139
+ }
140
+
141
+ function detectActiveSkills(tail, installedSkills) {
142
+ // A skill is "active" if its name appears in the transcript
143
+ // (skill bodies are injected into the system prompt when triggered)
144
+ return installedSkills.filter(name => tail.includes(name));
145
+ }
146
+
147
+ // ── Haiku analysis ────────────────────────────────────────────────────────────
148
+
149
+ async function analyzeWithHaiku(skillName, tail, failures, apiKey) {
150
+ // Build a compact summary for Haiku (avoid sending full transcript)
151
+ const truncatedTail = tail.slice(-8000); // last ~8KB for prompt efficiency
152
+ const failureSummary = failures.length > 0
153
+ ? `Tool failures:\n${failures.slice(0, 5).map((f, i) => `${i + 1}. ${f}`).join('\n')}`
154
+ : 'No tool failures detected.';
155
+
156
+ const prompt = `You are analyzing a Claude Code session to extract experience for improving the "${skillName}" skill.
157
+
158
+ Session tail (last portion of conversation):
159
+ <session>
160
+ ${truncatedTail.slice(0, 6000)}
161
+ </session>
162
+
163
+ ${failureSummary}
164
+
165
+ Extract only concrete, reusable insights about the "${skillName}" skill. Respond with ONLY a JSON object or the string NO_EVOLUTION:
166
+
167
+ {
168
+ "preferences": ["user preference observed, e.g. always use X format"],
169
+ "fixes": ["bug or workaround discovered, e.g. path needs quoting on Windows"],
170
+ "custom_prompts": "persistent instruction to inject, if any (or omit)"
171
+ }
172
+
173
+ Rules:
174
+ - Only include insights directly related to "${skillName}"
175
+ - "preferences": recurring user preferences (omit if none)
176
+ - "fixes": concrete bugs/workarounds (omit if none)
177
+ - "custom_prompts": only if a specific instruction should always apply (omit otherwise)
178
+ - If nothing useful found, respond: NO_EVOLUTION`;
179
+
180
+ try {
181
+ const result = await callHaiku(prompt, apiKey);
182
+ if (!result || result.trim() === 'NO_EVOLUTION') return null;
183
+ const json = result.match(/\{[\s\S]*\}/)?.[0];
184
+ if (!json) return null;
185
+ const parsed = JSON.parse(json);
186
+ // Only return if there's actual content
187
+ const hasContent = (parsed.preferences?.length > 0) ||
188
+ (parsed.fixes?.length > 0) ||
189
+ parsed.custom_prompts;
190
+ return hasContent ? parsed : null;
191
+ } catch { return null; }
192
+ }
193
+
194
+ function callHaiku(prompt, apiKey) {
195
+ return new Promise((resolve, reject) => {
196
+ const body = JSON.stringify({
197
+ model: 'claude-haiku-4-5-20251001',
198
+ max_tokens: 512,
199
+ messages: [{ role: 'user', content: prompt }],
200
+ });
201
+
202
+ const req = https.request({
203
+ hostname: 'api.anthropic.com',
204
+ path: '/v1/messages',
205
+ method: 'POST',
206
+ headers: {
207
+ 'Content-Type': 'application/json',
208
+ 'x-api-key': apiKey,
209
+ 'anthropic-version': '2023-06-01',
210
+ },
211
+ timeout: 10000,
212
+ }, res => {
213
+ let data = '';
214
+ res.on('data', chunk => { data += chunk; });
215
+ res.on('end', () => {
216
+ try {
217
+ const parsed = JSON.parse(data);
218
+ resolve(parsed?.content?.[0]?.text || null);
219
+ } catch { resolve(null); }
220
+ });
221
+ });
222
+
223
+ req.on('error', reject);
224
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
225
+ req.write(body);
226
+ req.end();
227
+ });
228
+ }
229
+
230
+ // ── Fallback: raw failure signals (no API key) ────────────────────────────────
231
+
232
+ function buildRawExperience(failures) {
233
+ if (failures.length === 0) return null;
234
+ return {
235
+ fixes: failures.slice(0, 3).map(f => `[auto-captured] ${f.slice(0, 150)}`),
236
+ };
237
+ }
238
+
239
+ // ── Persist ───────────────────────────────────────────────────────────────────
240
+
241
+ function persistExperience(skillDir, experience) {
242
+ try {
243
+ const jsonStr = JSON.stringify(experience).replace(/'/g, "\\'");
244
+ execSync(`python3 "${MERGE_SCRIPT}" "${skillDir}" '${jsonStr}'`, { stdio: 'ignore' });
245
+ execSync(`python3 "${STITCH_SCRIPT}" "${skillDir}"`, { stdio: 'ignore' });
246
+ } catch { /* non-fatal */ }
247
+ }
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Skill Initializer - Creates a new skill from template
4
+
5
+ Usage:
6
+ init_skill.py <skill-name> --path <path>
7
+
8
+ Examples:
9
+ init_skill.py my-new-skill --path skills/public
10
+ init_skill.py my-api-helper --path skills/private
11
+ init_skill.py custom-skill --path /custom/location
12
+ """
13
+
14
+ import sys
15
+ from pathlib import Path
16
+
17
+
18
+ SKILL_TEMPLATE = """---
19
+ name: {skill_name}
20
+ description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
21
+ ---
22
+
23
+ # {skill_title}
24
+
25
+ ## Overview
26
+
27
+ [TODO: 1-2 sentences explaining what this skill enables]
28
+
29
+ ## Structuring This Skill
30
+
31
+ [TODO: Choose the structure that best fits this skill's purpose. Common patterns:
32
+
33
+ **1. Workflow-Based** (best for sequential processes)
34
+ - Works well when there are clear step-by-step procedures
35
+ - Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"
36
+ - Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...
37
+
38
+ **2. Task-Based** (best for tool collections)
39
+ - Works well when the skill offers different operations/capabilities
40
+ - Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"
41
+ - Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...
42
+
43
+ **3. Reference/Guidelines** (best for standards or specifications)
44
+ - Works well for brand guidelines, coding standards, or requirements
45
+ - Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"
46
+ - Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...
47
+
48
+ **4. Capabilities-Based** (best for integrated systems)
49
+ - Works well when the skill provides multiple interrelated features
50
+ - Example: Product Management with "Core Capabilities" → numbered capability list
51
+ - Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...
52
+
53
+ Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
54
+
55
+ Delete this entire "Structuring This Skill" section when done - it's just guidance.]
56
+
57
+ ## [TODO: Replace with the first main section based on chosen structure]
58
+
59
+ [TODO: Add content here. See examples in existing skills:
60
+ - Code samples for technical skills
61
+ - Decision trees for complex workflows
62
+ - Concrete examples with realistic user requests
63
+ - References to scripts/templates/references as needed]
64
+
65
+ ## Resources
66
+
67
+ This skill includes example resource directories that demonstrate how to organize different types of bundled resources:
68
+
69
+ ### scripts/
70
+ Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
71
+
72
+ **Examples from other skills:**
73
+ - PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
74
+ - DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
75
+
76
+ **Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
77
+
78
+ **Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.
79
+
80
+ ### references/
81
+ Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.
82
+
83
+ **Examples from other skills:**
84
+ - Product management: `communication.md`, `context_building.md` - detailed workflow guides
85
+ - BigQuery: API reference documentation and query examples
86
+ - Finance: Schema documentation, company policies
87
+
88
+ **Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.
89
+
90
+ ### assets/
91
+ Files not intended to be loaded into context, but rather used within the output Claude produces.
92
+
93
+ **Examples from other skills:**
94
+ - Brand styling: PowerPoint template files (.pptx), logo files
95
+ - Frontend builder: HTML/React boilerplate project directories
96
+ - Typography: Font files (.ttf, .woff2)
97
+
98
+ **Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
99
+
100
+ ---
101
+
102
+ **Any unneeded directories can be deleted.** Not every skill requires all three types of resources.
103
+ """
104
+
105
+ EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
106
+ """
107
+ Example helper script for {skill_name}
108
+
109
+ This is a placeholder script that can be executed directly.
110
+ Replace with actual implementation or delete if not needed.
111
+
112
+ Example real scripts from other skills:
113
+ - pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
114
+ - pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
115
+ """
116
+
117
+ def main():
118
+ print("This is an example script for {skill_name}")
119
+ # TODO: Add actual script logic here
120
+ # This could be data processing, file conversion, API calls, etc.
121
+
122
+ if __name__ == "__main__":
123
+ main()
124
+ '''
125
+
126
+ EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
127
+
128
+ This is a placeholder for detailed reference documentation.
129
+ Replace with actual reference content or delete if not needed.
130
+
131
+ Example real reference docs from other skills:
132
+ - product-management/references/communication.md - Comprehensive guide for status updates
133
+ - product-management/references/context_building.md - Deep-dive on gathering context
134
+ - bigquery/references/ - API references and query examples
135
+
136
+ ## When Reference Docs Are Useful
137
+
138
+ Reference docs are ideal for:
139
+ - Comprehensive API documentation
140
+ - Detailed workflow guides
141
+ - Complex multi-step processes
142
+ - Information too lengthy for main SKILL.md
143
+ - Content that's only needed for specific use cases
144
+
145
+ ## Structure Suggestions
146
+
147
+ ### API Reference Example
148
+ - Overview
149
+ - Authentication
150
+ - Endpoints with examples
151
+ - Error codes
152
+ - Rate limits
153
+
154
+ ### Workflow Guide Example
155
+ - Prerequisites
156
+ - Step-by-step instructions
157
+ - Common patterns
158
+ - Troubleshooting
159
+ - Best practices
160
+ """
161
+
162
+ EXAMPLE_ASSET = """# Example Asset File
163
+
164
+ This placeholder represents where asset files would be stored.
165
+ Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
166
+
167
+ Asset files are NOT intended to be loaded into context, but rather used within
168
+ the output Claude produces.
169
+
170
+ Example asset files from other skills:
171
+ - Brand guidelines: logo.png, slides_template.pptx
172
+ - Frontend builder: hello-world/ directory with HTML/React boilerplate
173
+ - Typography: custom-font.ttf, font-family.woff2
174
+ - Data: sample_data.csv, test_dataset.json
175
+
176
+ ## Common Asset Types
177
+
178
+ - Templates: .pptx, .docx, boilerplate directories
179
+ - Images: .png, .jpg, .svg, .gif
180
+ - Fonts: .ttf, .otf, .woff, .woff2
181
+ - Boilerplate code: Project directories, starter files
182
+ - Icons: .ico, .svg
183
+ - Data files: .csv, .json, .xml, .yaml
184
+
185
+ Note: This is a text placeholder. Actual assets can be any file type.
186
+ """
187
+
188
+
189
+ def title_case_skill_name(skill_name):
190
+ """Convert hyphenated skill name to Title Case for display."""
191
+ return ' '.join(word.capitalize() for word in skill_name.split('-'))
192
+
193
+
194
+ def init_skill(skill_name, path):
195
+ """
196
+ Initialize a new skill directory with template SKILL.md.
197
+
198
+ Args:
199
+ skill_name: Name of the skill
200
+ path: Path where the skill directory should be created
201
+
202
+ Returns:
203
+ Path to created skill directory, or None if error
204
+ """
205
+ # Determine skill directory path
206
+ skill_dir = Path(path).resolve() / skill_name
207
+
208
+ # Check if directory already exists
209
+ if skill_dir.exists():
210
+ print(f"❌ Error: Skill directory already exists: {skill_dir}")
211
+ return None
212
+
213
+ # Create skill directory
214
+ try:
215
+ skill_dir.mkdir(parents=True, exist_ok=False)
216
+ print(f"✅ Created skill directory: {skill_dir}")
217
+ except Exception as e:
218
+ print(f"❌ Error creating directory: {e}")
219
+ return None
220
+
221
+ # Create SKILL.md from template
222
+ skill_title = title_case_skill_name(skill_name)
223
+ skill_content = SKILL_TEMPLATE.format(
224
+ skill_name=skill_name,
225
+ skill_title=skill_title
226
+ )
227
+
228
+ skill_md_path = skill_dir / 'SKILL.md'
229
+ try:
230
+ skill_md_path.write_text(skill_content)
231
+ print("✅ Created SKILL.md")
232
+ except Exception as e:
233
+ print(f"❌ Error creating SKILL.md: {e}")
234
+ return None
235
+
236
+ # Create resource directories with example files
237
+ try:
238
+ # Create scripts/ directory with example script
239
+ scripts_dir = skill_dir / 'scripts'
240
+ scripts_dir.mkdir(exist_ok=True)
241
+ example_script = scripts_dir / 'example.py'
242
+ example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
243
+ example_script.chmod(0o755)
244
+ print("✅ Created scripts/example.py")
245
+
246
+ # Create references/ directory with example reference doc
247
+ references_dir = skill_dir / 'references'
248
+ references_dir.mkdir(exist_ok=True)
249
+ example_reference = references_dir / 'api_reference.md'
250
+ example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
251
+ print("✅ Created references/api_reference.md")
252
+
253
+ # Create assets/ directory with example asset placeholder
254
+ assets_dir = skill_dir / 'assets'
255
+ assets_dir.mkdir(exist_ok=True)
256
+ example_asset = assets_dir / 'example_asset.txt'
257
+ example_asset.write_text(EXAMPLE_ASSET)
258
+ print("✅ Created assets/example_asset.txt")
259
+ except Exception as e:
260
+ print(f"❌ Error creating resource directories: {e}")
261
+ return None
262
+
263
+ # Print next steps
264
+ print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}")
265
+ print("\nNext steps:")
266
+ print("1. Edit SKILL.md to complete the TODO items and update the description")
267
+ print("2. Customize or delete the example files in scripts/, references/, and assets/")
268
+ print("3. Run the validator when ready to check the skill structure")
269
+
270
+ return skill_dir
271
+
272
+
273
+ def main():
274
+ if len(sys.argv) < 4 or sys.argv[2] != '--path':
275
+ print("Usage: init_skill.py <skill-name> --path <path>")
276
+ print("\nSkill name requirements:")
277
+ print(" - Kebab-case identifier (e.g., 'my-data-analyzer')")
278
+ print(" - Lowercase letters, digits, and hyphens only")
279
+ print(" - Max 64 characters")
280
+ print(" - Must match directory name exactly")
281
+ print("\nExamples:")
282
+ print(" init_skill.py my-new-skill --path skills/public")
283
+ print(" init_skill.py my-api-helper --path skills/private")
284
+ print(" init_skill.py custom-skill --path /custom/location")
285
+ sys.exit(1)
286
+
287
+ skill_name = sys.argv[1]
288
+ path = sys.argv[3]
289
+
290
+ print(f"🚀 Initializing skill: {skill_name}")
291
+ print(f" Location: {path}")
292
+ print()
293
+
294
+ result = init_skill(skill_name, path)
295
+
296
+ if result:
297
+ sys.exit(0)
298
+ else:
299
+ sys.exit(1)
300
+
301
+
302
+ if __name__ == "__main__":
303
+ main()
@@ -0,0 +1,70 @@
1
+ import os
2
+ import sys
3
+ import json
4
+ import datetime
5
+
6
+ def merge_evolution(skill_dir, new_data_json_str):
7
+ """
8
+ Merges new evolution data into existing evolution.json.
9
+ Deduplicates list items.
10
+ """
11
+ evolution_json_path = os.path.join(skill_dir, "evolution.json")
12
+
13
+ # Load existing or create new
14
+ if os.path.exists(evolution_json_path):
15
+ try:
16
+ with open(evolution_json_path, 'r', encoding='utf-8') as f:
17
+ current_data = json.load(f)
18
+ except Exception:
19
+ current_data = {}
20
+ else:
21
+ current_data = {}
22
+
23
+ try:
24
+ new_data = json.loads(new_data_json_str)
25
+ except json.JSONDecodeError as e:
26
+ print(f"Error decoding new data JSON: {e}", file=sys.stderr)
27
+ return False
28
+
29
+ # Merge logic
30
+ # 1. Update timestamp
31
+ current_data['last_updated'] = datetime.datetime.now().isoformat()
32
+
33
+ # 2. Merge Lists (preferences, fixes, contexts) with deduplication
34
+ for list_key in ['preferences', 'fixes', 'contexts']:
35
+ if list_key in new_data:
36
+ existing_list = current_data.get(list_key, [])
37
+ new_items = new_data[list_key]
38
+ if isinstance(new_items, list):
39
+ # Simple dedupe by string equality
40
+ for item in new_items:
41
+ if item not in existing_list:
42
+ existing_list.append(item)
43
+ current_data[list_key] = existing_list
44
+
45
+ # 3. Overwrite/Append Custom Prompts (Concatenate if exists to preserve history? Or overwrite?)
46
+ # Decision: Overwrite if provided, as prompts usually need to be coherent.
47
+ # Or, the Agent should have read the old one and combined it before sending here.
48
+ # We assume Agent sends the FINAL desired state for custom_prompts if it wants to merge.
49
+ if 'custom_prompts' in new_data:
50
+ current_data['custom_prompts'] = new_data['custom_prompts']
51
+
52
+ # 4. Update last_evolved_hash if provided
53
+ if 'last_evolved_hash' in new_data:
54
+ current_data['last_evolved_hash'] = new_data['last_evolved_hash']
55
+
56
+ # Save back
57
+ with open(evolution_json_path, 'w', encoding='utf-8') as f:
58
+ json.dump(current_data, f, indent=2, ensure_ascii=False)
59
+
60
+ print(f"Successfully merged evolution data for {os.path.basename(skill_dir)}")
61
+ return True
62
+
63
+ if __name__ == "__main__":
64
+ if len(sys.argv) < 3:
65
+ print("Usage: python merge_evolution.py <skill_dir> <json_string>")
66
+ sys.exit(1)
67
+
68
+ skill_dir = sys.argv[1]
69
+ json_str = sys.argv[2]
70
+ merge_evolution(skill_dir, json_str)