@robosoft/skillhub-cli 0.1.2 → 0.3.3

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 (51) hide show
  1. package/CHANGELOG.md +26 -25
  2. package/README.md +162 -182
  3. package/bin/skillhub.mjs +722 -365
  4. package/docs/skillhub-cli-logic.md +114 -83
  5. package/package.json +8 -5
  6. package/skillhub-registry/CHANGELOG.md +65 -0
  7. package/skillhub-registry/CLAUDE.md +108 -0
  8. package/skillhub-registry/README.md +196 -16
  9. package/skillhub-registry/docs/cheat-sheet.md +272 -0
  10. package/skillhub-registry/docs/contributing.md +166 -0
  11. package/skillhub-registry/docs/cost-hygiene.md +175 -0
  12. package/skillhub-registry/docs/customization.md +321 -0
  13. package/skillhub-registry/docs/exception-process.md +194 -0
  14. package/skillhub-registry/docs/installation.md +277 -0
  15. package/skillhub-registry/domain/api.md +303 -0
  16. package/skillhub-registry/domain/frontend/web-app.md +17 -0
  17. package/skillhub-registry/domain/frontend-app.md +46 -0
  18. package/skillhub-registry/domain/frontend-architecture.md +126 -0
  19. package/skillhub-registry/rules/anti-patterns.md +95 -0
  20. package/skillhub-registry/rules/code-standards.md +182 -0
  21. package/skillhub-registry/rules/frontend/antipattern.md +21 -0
  22. package/skillhub-registry/rules/frontend/component-standards.md +10 -0
  23. package/skillhub-registry/rules/frontend-app.md +24 -0
  24. package/skillhub-registry/rules/general.md +51 -0
  25. package/skillhub-registry/skills/api/SKILL.md +167 -0
  26. package/skillhub-registry/skills/build/SKILL.md +114 -0
  27. package/skillhub-registry/skills/fast/SKILL.md +56 -0
  28. package/skillhub-registry/skills/feature-dev/SKILL.md +166 -0
  29. package/skillhub-registry/skills/frontend/app/SKILL.md +28 -0
  30. package/skillhub-registry/skills/frontend/app/skill.json +10 -0
  31. package/skillhub-registry/skills/frontend/app/templates/feature/{{kebabName}}.tsx.hbs +11 -0
  32. package/skillhub-registry/skills/frontend-app/SKILL.md +48 -0
  33. package/skillhub-registry/skills/frontend-app/skill.json +11 -0
  34. package/skillhub-registry/skills/frontend-app/templates/feature/{{kebabName}}.tsx.hbs +11 -0
  35. package/skillhub-registry/skills/performance/SKILL.md +168 -0
  36. package/skillhub-registry/skills/react/SKILL.md +224 -0
  37. package/skillhub-registry/skills/refactor/SKILL.md +149 -0
  38. package/skillhub-registry/skills/review/SKILL.md +199 -0
  39. package/skillhub-registry/skills/strict/SKILL.md +74 -0
  40. package/skillhub-registry/skills/testing/SKILL.md +132 -0
  41. package/skillhub-registry/accessibility-review/1.0.0/SKILL.md +0 -22
  42. package/skillhub-registry/accessibility-review/1.0.0/checklist/ui-review.md +0 -8
  43. package/skillhub-registry/accessibility-review/1.0.0/skill.json +0 -9
  44. package/skillhub-registry/nextjs-clean-architecture/1.0.0/SKILL.md +0 -37
  45. package/skillhub-registry/nextjs-clean-architecture/1.0.0/checklist/definition-of-done.md +0 -9
  46. package/skillhub-registry/nextjs-clean-architecture/1.0.0/rules/folder-structure.md +0 -7
  47. package/skillhub-registry/nextjs-clean-architecture/1.0.0/skill.json +0 -9
  48. package/skillhub-registry/shadcn-crud-generator/1.0.0/SKILL.md +0 -25
  49. package/skillhub-registry/shadcn-crud-generator/1.0.0/skill.json +0 -9
  50. package/skillhub-registry/shadcn-crud-generator/1.0.0/templates/feature/actions.ts.hbs +0 -16
  51. package/skillhub-registry/shadcn-crud-generator/1.0.0/templates/feature/page.tsx.hbs +0 -13
package/bin/skillhub.mjs CHANGED
@@ -1,34 +1,73 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import fs from "node:fs/promises";
4
+ import fsSync from "node:fs";
4
5
  import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
5
7
  import crypto from "node:crypto";
6
8
  import process from "node:process";
7
9
  import readline from "node:readline/promises";
8
10
 
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+ const PACKAGE_ROOT = path.resolve(__dirname, "..");
14
+ const BUNDLED_REGISTRY_DIR = path.join(PACKAGE_ROOT, "skillhub-registry");
15
+
9
16
  const CONFIG_FILE = "skillhub.json";
10
17
  const LOCK_FILE = "skillhub.lock.json";
11
18
  const DEFAULT_TARGET = "ai";
19
+ const GENERATED_START = "<!-- skillhub:start -->";
20
+ const GENERATED_END = "<!-- skillhub:end -->";
21
+
12
22
  const TARGETS = {
13
23
  ai: {
14
- label: ".ai/skills",
15
- skillsDir: ".ai/skills",
24
+ label: "Generic AI",
25
+ sections: {
26
+ skills: ".ai/skills",
27
+ rules: ".ai/rules",
28
+ domain: ".ai/domain",
29
+ },
16
30
  adapters: { agentsMd: true, cursorRules: false, claude: false, githubCopilot: false },
17
31
  },
18
32
  cursor: {
19
- label: ".cursor/skills",
20
- skillsDir: ".cursor/skills",
33
+ label: "Cursor",
34
+ sections: {
35
+ skills: ".cursor/skills",
36
+ rules: ".cursor/rules",
37
+ domain: ".cursor/domain",
38
+ },
21
39
  adapters: { agentsMd: false, cursorRules: true, claude: false, githubCopilot: false },
22
40
  },
23
41
  claude: {
24
- label: ".claude/skills",
25
- skillsDir: ".claude/skills",
42
+ label: "Claude",
43
+ sections: {
44
+ skills: ".claude/skills",
45
+ rules: ".claude/rules",
46
+ domain: ".claude/domain",
47
+ },
26
48
  adapters: { agentsMd: false, cursorRules: false, claude: true, githubCopilot: false },
27
49
  },
28
50
  };
29
- const DEFAULT_SKILLS_DIR = TARGETS[DEFAULT_TARGET].skillsDir;
30
- const GENERATED_START = "<!-- skillhub:start -->";
31
- const GENERATED_END = "<!-- skillhub:end -->";
51
+
52
+ const SECTION_ALIASES = {
53
+ skill: "skills",
54
+ skills: "skills",
55
+ sk: "skills",
56
+ rule: "rules",
57
+ rules: "rules",
58
+ rl: "rules",
59
+ domain: "domain",
60
+ domains: "domain",
61
+ knowledge: "domain",
62
+ "domain-knowledge": "domain",
63
+ dk: "domain",
64
+ };
65
+
66
+ const SECTION_SINGULAR = {
67
+ skills: "skill",
68
+ rules: "rule",
69
+ domain: "domain",
70
+ };
32
71
 
33
72
  const colors = {
34
73
  reset: "\x1b[0m",
@@ -95,7 +134,7 @@ function normalizeSlashes(value) {
95
134
  function safeJoin(root, relativePath) {
96
135
  const target = path.resolve(root, relativePath);
97
136
  const normalizedRoot = path.resolve(root);
98
- if (!target.startsWith(normalizedRoot)) {
137
+ if (target !== normalizedRoot && !target.startsWith(`${normalizedRoot}${path.sep}`)) {
99
138
  throw new Error(`Unsafe path detected: ${relativePath}`);
100
139
  }
101
140
  return target;
@@ -141,11 +180,8 @@ function normalizeTarget(value) {
141
180
  ai: "ai",
142
181
  cursor: "cursor",
143
182
  cursorrules: "cursor",
144
- ".cursor": "cursor",
145
183
  claude: "claude",
146
184
  cloude: "claude",
147
- ".claude": "claude",
148
- ".cloude": "claude",
149
185
  };
150
186
 
151
187
  const target = aliases[normalized] || normalized;
@@ -156,17 +192,24 @@ function normalizeTarget(value) {
156
192
  return target;
157
193
  }
158
194
 
159
- async function askTarget(defaultTarget = DEFAULT_TARGET) {
160
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
161
- return defaultTarget;
195
+ function normalizeSection(value, fallback = "skills") {
196
+ const raw = String(value || fallback).trim().toLowerCase();
197
+ const normalized = SECTION_ALIASES[raw] || raw;
198
+ if (!TARGETS.ai.sections[normalized]) {
199
+ throw new Error(`Invalid section "${value}". Use: skill, rule, or domain.`);
162
200
  }
201
+ return normalized;
202
+ }
203
+
204
+ async function askTarget(defaultTarget = DEFAULT_TARGET) {
205
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return defaultTarget;
163
206
 
164
207
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
165
208
  try {
166
- console.log(paint("bold", "Where should SkillHub install skill files?"));
167
- console.log(` 1. ${TARGETS.ai.skillsDir} ${paint("dim", "(generic AI folder + AGENTS.md)")}`);
168
- console.log(` 2. ${TARGETS.cursor.skillsDir} ${paint("dim", "(Cursor rules)")}`);
169
- console.log(` 3. ${TARGETS.claude.skillsDir} ${paint("dim", "(Claude project instructions)")}`);
209
+ console.log(paint("bold", "Where should SkillHub attach project knowledge?"));
210
+ console.log(` 1. .ai ${paint("dim", "(generic AI folder + AGENTS.md)")}`);
211
+ console.log(` 2. .cursor ${paint("dim", "(Cursor skills/rules/domain)")}`);
212
+ console.log(` 3. .claude ${paint("dim", "(Claude skills/rules/domain)")}`);
170
213
 
171
214
  const answer = await rl.question(`Choose target [1/2/3 or ai/cursor/claude] (${defaultTarget}): `);
172
215
  const raw = answer.trim();
@@ -180,10 +223,14 @@ async function askTarget(defaultTarget = DEFAULT_TARGET) {
180
223
  }
181
224
  }
182
225
 
226
+ function targetSections(target) {
227
+ return { ...TARGETS[normalizeTarget(target) || DEFAULT_TARGET].sections };
228
+ }
229
+
183
230
  function getConfigTarget(config) {
184
231
  if (config?.target) return normalizeTarget(config.target);
185
232
 
186
- const skillsDir = config?.skillsDir || DEFAULT_SKILLS_DIR;
233
+ const skillsDir = config?.skillsDir || config?.sections?.skills || TARGETS.ai.sections.skills;
187
234
  if (skillsDir.startsWith(".cursor/")) return "cursor";
188
235
  if (skillsDir.startsWith(".claude/") || skillsDir.startsWith(".cloude/")) return "claude";
189
236
  return "ai";
@@ -194,42 +241,141 @@ function applyTargetToConfig(config, targetValue, { preserveExistingAdapters = f
194
241
  const targetConfig = TARGETS[target];
195
242
 
196
243
  config.target = target;
197
- config.skillsDir = targetConfig.skillsDir;
244
+ config.sections = targetSections(target);
245
+ config.skillsDir = config.sections.skills; // backward compatibility
246
+ config.rulesDir = config.sections.rules;
247
+ config.domainDir = config.sections.domain;
198
248
  config.adapters = preserveExistingAdapters
199
249
  ? { ...targetConfig.adapters, ...(config.adapters || {}) }
200
- : { ...targetConfig.adapters, ...(target === "ai" ? { agentsMd: true } : {}) };
250
+ : { ...targetConfig.adapters };
201
251
 
202
252
  return config;
203
253
  }
204
254
 
205
- function parseSkillSpec(spec) {
206
- if (!spec || spec.trim().length === 0) {
207
- throw new Error("Skill name is required.");
255
+ function defaultInstalled() {
256
+ return { skills: {}, rules: {}, domain: {} };
257
+ }
258
+
259
+ function normalizeInstalled(value = {}) {
260
+ return {
261
+ skills: { ...(value.skills || {}) },
262
+ rules: { ...(value.rules || {}) },
263
+ domain: { ...(value.domain || {}) },
264
+ };
265
+ }
266
+
267
+ function defaultConfig(projectRoot, target = DEFAULT_TARGET) {
268
+ const config = {
269
+ $schema: "https://skillhub.local/schema/skillhub.schema.json",
270
+ project: path.basename(projectRoot),
271
+ registry: "./skillhub-registry",
272
+ target: DEFAULT_TARGET,
273
+ sections: targetSections(DEFAULT_TARGET),
274
+ skillsDir: TARGETS.ai.sections.skills,
275
+ rulesDir: TARGETS.ai.sections.rules,
276
+ domainDir: TARGETS.ai.sections.domain,
277
+ skills: {}, // backward compatibility
278
+ installed: defaultInstalled(),
279
+ adapters: {},
280
+ };
281
+
282
+ return applyTargetToConfig(config, target);
283
+ }
284
+
285
+ function defaultLock() {
286
+ return {
287
+ lockfileVersion: 2,
288
+ updatedAt: now(),
289
+ installed: defaultInstalled(),
290
+ skills: {}, // backward compatibility
291
+ };
292
+ }
293
+
294
+ async function readProjectConfig(projectRoot) {
295
+ const configPath = path.join(projectRoot, CONFIG_FILE);
296
+ const config = await readJson(configPath, null);
297
+ if (!config) throw new Error(`No ${CONFIG_FILE} found. Run: skillhub init`);
298
+
299
+ const target = getConfigTarget(config);
300
+ config.target = target;
301
+ config.sections = { ...targetSections(target), ...(config.sections || {}) };
302
+
303
+ // Migrate the older Cursor default. Rules should live directly under .cursor/rules,
304
+ // not under an extra .cursor/rules/skillhub namespace.
305
+ if (target === "cursor" && config.sections.rules === ".cursor/rules/skillhub") {
306
+ config.sections.rules = TARGETS.cursor.sections.rules;
208
307
  }
209
308
 
309
+ config.skillsDir = config.sections.skills || config.skillsDir || TARGETS[target].sections.skills;
310
+ config.rulesDir = config.sections.rules || config.rulesDir || TARGETS[target].sections.rules;
311
+ config.domainDir = config.sections.domain || config.domainDir || TARGETS[target].sections.domain;
312
+ config.adapters = config.adapters || TARGETS[target].adapters;
313
+ config.installed = normalizeInstalled(config.installed || { skills: config.skills || {} });
314
+ config.skills = config.installed.skills;
315
+
316
+ return config;
317
+ }
318
+
319
+ async function readProjectLock(projectRoot) {
320
+ const lock = (await readJson(path.join(projectRoot, LOCK_FILE), null)) || defaultLock();
321
+ lock.installed = normalizeInstalled(lock.installed || { skills: lock.skills || {} });
322
+ lock.skills = lock.installed.skills;
323
+ return lock;
324
+ }
325
+
326
+ function parseArtifactSpec(spec) {
327
+ if (!spec || spec.trim().length === 0) throw new Error("Name is required.");
328
+
210
329
  const trimmed = spec.trim();
211
330
  const atIndex = trimmed.lastIndexOf("@");
331
+ if (atIndex > 0) return { name: trimmed.slice(0, atIndex).replace(/\.md$/i, ""), version: trimmed.slice(atIndex + 1) };
332
+ return { name: trimmed.replace(/\.md$/i, ""), version: null };
333
+ }
212
334
 
213
- if (atIndex > 0) {
214
- return {
215
- name: trimmed.slice(0, atIndex),
216
- version: trimmed.slice(atIndex + 1),
217
- };
218
- }
335
+ function lastPathSegment(value) {
336
+ const parts = String(value || "")
337
+ .replace(/\\/g, "/")
338
+ .split("/")
339
+ .map((part) => part.trim())
340
+ .filter(Boolean);
341
+ return parts.at(-1) || String(value || "").trim();
342
+ }
343
+
344
+ function localArtifactName(section, requestedName, manifest, flags = {}) {
345
+ if (flags.as) return String(flags.as).trim().replace(/\.md$/i, "");
346
+
347
+ // Registry paths can be namespaced, for example frontend/antipattern.
348
+ // The namespace is only used to resolve the item from SkillHub. Locally we install
349
+ // the artifact by its leaf name: antipattern.md, app/, web-app.md.
350
+ const candidate = requestedName || manifest?.name || "";
351
+ const leaf = lastPathSegment(candidate);
352
+ return leaf || lastPathSegment(manifest?.name) || SECTION_SINGULAR[section];
353
+ }
354
+
355
+ function installedEntryVersion(entry) {
356
+ if (!entry) return null;
357
+ if (typeof entry === "string") return entry;
358
+ return entry.version || null;
359
+ }
360
+
361
+ function installedEntryLocalName(key, entry) {
362
+ if (!entry || typeof entry === "string") return lastPathSegment(key);
363
+ return entry.localName || lastPathSegment(entry.name || key);
364
+ }
219
365
 
220
- return { name: trimmed, version: null };
366
+ function installedEntrySpec(key, entry) {
367
+ if (!entry || typeof entry === "string") return key;
368
+ return entry.name || entry.sourceName || key;
221
369
  }
222
370
 
223
371
  function sortVersions(versions) {
224
372
  return versions.sort((left, right) => {
225
373
  const a = left.split(".").map((part) => Number.parseInt(part, 10) || 0);
226
374
  const b = right.split(".").map((part) => Number.parseInt(part, 10) || 0);
227
-
228
375
  for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
229
376
  const diff = (b[index] ?? 0) - (a[index] ?? 0);
230
377
  if (diff !== 0) return diff;
231
378
  }
232
-
233
379
  return right.localeCompare(left);
234
380
  });
235
381
  }
@@ -239,7 +385,8 @@ async function listFiles(root, current = root) {
239
385
  const files = [];
240
386
 
241
387
  for (const entry of entries) {
242
- if (entry.name === "node_modules" || entry.name === ".git") continue;
388
+ if (entry.name === "node_modules" || entry.name === ".git" || entry.name === ".DS_Store") continue;
389
+ if (entry.name.startsWith("._")) continue;
243
390
 
244
391
  const fullPath = path.join(current, entry.name);
245
392
  if (entry.isDirectory()) {
@@ -252,22 +399,18 @@ async function listFiles(root, current = root) {
252
399
  return files.sort();
253
400
  }
254
401
 
255
- async function readSkillPackageFiles(packageDir) {
402
+ async function readPackageFiles(packageDir) {
256
403
  const filePaths = await listFiles(packageDir);
257
404
  const files = [];
258
-
259
405
  for (const relativePath of filePaths) {
260
- const fullPath = path.join(packageDir, relativePath);
261
- const content = await fs.readFile(fullPath, "utf8");
262
- files.push({ path: relativePath, content });
406
+ files.push({ path: relativePath, content: await fs.readFile(path.join(packageDir, relativePath), "utf8") });
263
407
  }
264
-
265
408
  return files;
266
409
  }
267
410
 
268
411
  function checksumFiles(files) {
269
412
  const hash = crypto.createHash("sha256");
270
- for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
413
+ for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
271
414
  hash.update(file.path);
272
415
  hash.update("\0");
273
416
  hash.update(file.content);
@@ -276,231 +419,316 @@ function checksumFiles(files) {
276
419
  return `sha256-${hash.digest("hex")}`;
277
420
  }
278
421
 
279
- function defaultConfig(projectRoot, target = DEFAULT_TARGET) {
280
- const config = {
281
- $schema: "https://skillhub.local/schema/skillhub.schema.json",
282
- project: path.basename(projectRoot),
283
- registry: "./skillhub-registry",
284
- target: DEFAULT_TARGET,
285
- skillsDir: DEFAULT_SKILLS_DIR,
286
- skills: {},
287
- adapters: {},
288
- };
289
-
290
- return applyTargetToConfig(config, target);
291
- }
422
+ function resolveRegistry(projectRoot, config, flags = {}, options = {}) {
423
+ const { fallbackToBundled = true } = options;
424
+ const hasFlagRegistry = Boolean(flags.registry);
425
+ const hasEnvRegistry = Boolean(process.env.SKILLHUB_REGISTRY);
426
+ const value = flags.registry || process.env.SKILLHUB_REGISTRY || config.registry || "./skillhub-registry";
292
427
 
293
- function defaultLock() {
294
- return {
295
- lockfileVersion: 1,
296
- updatedAt: now(),
297
- skills: {},
298
- };
299
- }
428
+ if (value.startsWith("http://") || value.startsWith("https://")) return value.replace(/\/$/, "");
300
429
 
301
- async function readProjectConfig(projectRoot) {
302
- const configPath = path.join(projectRoot, CONFIG_FILE);
303
- const config = await readJson(configPath, null);
304
- if (!config) {
305
- throw new Error(`No ${CONFIG_FILE} found. Run: skillhub init`);
430
+ const resolved = path.resolve(projectRoot, value);
431
+ const isDefaultLocalRegistry = value === "./skillhub-registry" || value === "skillhub-registry";
432
+ if (fallbackToBundled && !hasFlagRegistry && !hasEnvRegistry && isDefaultLocalRegistry && !fsSync.existsSync(resolved) && fsSync.existsSync(BUNDLED_REGISTRY_DIR)) {
433
+ return BUNDLED_REGISTRY_DIR;
306
434
  }
307
435
 
308
- config.target = getConfigTarget(config);
309
- config.skillsDir = config.skillsDir || TARGETS[config.target].skillsDir;
310
- config.adapters = config.adapters || TARGETS[config.target].adapters;
311
- return config;
436
+ return resolved;
312
437
  }
313
438
 
314
- function resolveRegistry(projectRoot, config, flags = {}) {
315
- const value = flags.registry || process.env.SKILLHUB_REGISTRY || config.registry || "./skillhub-registry";
316
-
317
- if (value.startsWith("http://") || value.startsWith("https://")) {
318
- return value.replace(/\/$/, "");
319
- }
439
+ function firstHeading(content) {
440
+ const line = content.split(/\r?\n/).find((item) => item.trim().startsWith("# "));
441
+ return line ? line.replace(/^#\s+/, "").trim() : null;
442
+ }
320
443
 
321
- return path.resolve(projectRoot, value);
444
+ async function readOptionalJson(filePath) {
445
+ return (await exists(filePath)) ? readJson(filePath) : null;
322
446
  }
323
447
 
324
- async function loadLocalSkill(registryPath, name, requestedVersion) {
325
- const skillRoot = safeJoin(registryPath, name);
448
+ function defaultManifest(section, name, version, files) {
449
+ const entryFile = section === "skills" ? "SKILL.md" : section === "rules" ? "RULE.md" : "DOMAIN.md";
450
+ const entry = files.find((file) => file.path === entryFile) || files[0];
451
+ const title = entry ? firstHeading(entry.content) : name;
452
+ return {
453
+ name,
454
+ version: version || "1.0.0",
455
+ type: SECTION_SINGULAR[section],
456
+ section,
457
+ description: title ? `${title} ${SECTION_SINGULAR[section]}` : `Reusable ${SECTION_SINGULAR[section]} knowledge package`,
458
+ entry: entry?.path || entryFile,
459
+ };
460
+ }
326
461
 
327
- if (!(await exists(skillRoot))) {
328
- throw new Error(`Skill "${name}" was not found in registry: ${registryPath}`);
329
- }
462
+ async function loadVersionedPackage(baseDir, manifestName, requestedVersion) {
463
+ if (!(await exists(baseDir))) return null;
330
464
 
331
465
  let packageDir;
332
466
  let version = requestedVersion;
333
-
334
467
  if (requestedVersion) {
335
- packageDir = path.join(skillRoot, requestedVersion);
336
- } else if (await exists(path.join(skillRoot, "skill.json"))) {
337
- packageDir = skillRoot;
468
+ const versionedDir = path.join(baseDir, requestedVersion);
469
+ if (await exists(versionedDir)) {
470
+ packageDir = versionedDir;
471
+ } else if (await exists(path.join(baseDir, manifestName)) || await exists(path.join(baseDir, "skill.json"))) {
472
+ // Unversioned registry package. Use the package folder but keep the requested version in metadata.
473
+ packageDir = baseDir;
474
+ } else {
475
+ packageDir = versionedDir;
476
+ }
477
+ } else if (await exists(path.join(baseDir, manifestName))) {
478
+ packageDir = baseDir;
479
+ } else if (await exists(path.join(baseDir, "skill.json"))) {
480
+ packageDir = baseDir;
481
+ manifestName = "skill.json";
338
482
  } else {
339
- const entries = await fs.readdir(skillRoot, { withFileTypes: true });
483
+ const entries = await fs.readdir(baseDir, { withFileTypes: true });
340
484
  const versions = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
341
- if (versions.length === 0) {
342
- throw new Error(`Skill "${name}" has no versions in registry.`);
343
- }
485
+ if (versions.length === 0) return null;
344
486
  version = sortVersions(versions)[0];
345
- packageDir = path.join(skillRoot, version);
487
+ packageDir = path.join(baseDir, version);
346
488
  }
347
489
 
348
- if (!(await exists(packageDir))) {
349
- throw new Error(`Skill "${name}@${requestedVersion}" was not found.`);
490
+ if (!(await exists(packageDir))) return null;
491
+ return { packageDir, version };
492
+ }
493
+
494
+ async function loadLocalArtifact(registryPath, section, name, requestedVersion) {
495
+ const singular = SECTION_SINGULAR[section];
496
+ const manifestName = `${singular}.json`;
497
+ const entryName = section === "skills" ? "SKILL.md" : section === "rules" ? "RULE.md" : "DOMAIN.md";
498
+ const sectionDir = safeJoin(registryPath, section);
499
+
500
+ if (!(await exists(registryPath))) throw new Error(`Registry not found: ${registryPath}`);
501
+
502
+ // Flat file style: registry/rules/code-standards.md, registry/rules/frontend/antipattern.md, or registry/domain/api.md
503
+ if (section !== "skills") {
504
+ const flatFile = safeJoin(sectionDir, `${name}.md`);
505
+ if (await exists(flatFile)) {
506
+ const content = await fs.readFile(flatFile, "utf8");
507
+ const files = [{ path: entryName, content }];
508
+ return { manifest: defaultManifest(section, name, requestedVersion || "1.0.0", files), files, source: normalizeSlashes(path.relative(process.cwd(), flatFile)) || flatFile };
509
+ }
350
510
  }
351
511
 
352
- const manifestPath = path.join(packageDir, "skill.json");
353
- if (!(await exists(manifestPath))) {
354
- throw new Error(`Missing skill.json in ${packageDir}`);
512
+ // Section package style: registry/skills/react/SKILL.md or registry/rules/frontend/RULE.md
513
+ const sectionPackageBase = safeJoin(sectionDir, name);
514
+ const sectionPackage = await loadVersionedPackage(sectionPackageBase, manifestName, requestedVersion);
515
+ if (sectionPackage) {
516
+ const files = await readPackageFiles(sectionPackage.packageDir);
517
+ const manifest = (await readOptionalJson(path.join(sectionPackage.packageDir, manifestName))) ||
518
+ (section === "skills" ? await readOptionalJson(path.join(sectionPackage.packageDir, "skill.json")) : null) ||
519
+ defaultManifest(section, name, sectionPackage.version || requestedVersion || "1.0.0", files);
520
+ validateArtifactManifest(section, manifest, files);
521
+ return {
522
+ manifest: { ...manifest, name: manifest.name || name, version: manifest.version || sectionPackage.version || "1.0.0", type: manifest.type || singular, section },
523
+ files,
524
+ source: normalizeSlashes(path.relative(process.cwd(), sectionPackage.packageDir)) || sectionPackage.packageDir,
525
+ };
355
526
  }
356
527
 
357
- const manifest = await readJson(manifestPath);
358
- const files = await readSkillPackageFiles(packageDir);
528
+ // Backward compatible skill registry style: registry/nextjs-clean-architecture/1.0.0/skill.json
529
+ if (section === "skills") {
530
+ const legacyBase = safeJoin(registryPath, name);
531
+ const legacyPackage = await loadVersionedPackage(legacyBase, "skill.json", requestedVersion);
532
+ if (legacyPackage) {
533
+ const files = await readPackageFiles(legacyPackage.packageDir);
534
+ const manifest = (await readOptionalJson(path.join(legacyPackage.packageDir, "skill.json"))) || defaultManifest(section, name, legacyPackage.version || "1.0.0", files);
535
+ validateArtifactManifest(section, manifest, files);
536
+ return { manifest: { ...manifest, type: "skill", section }, files, source: normalizeSlashes(path.relative(process.cwd(), legacyPackage.packageDir)) || legacyPackage.packageDir };
537
+ }
538
+ }
359
539
 
360
- validateSkillManifest(manifest, files);
540
+ throw new Error(`${SECTION_SINGULAR[section]} "${name}" was not found in registry: ${registryPath}`);
541
+ }
361
542
 
362
- return {
363
- manifest: {
364
- ...manifest,
365
- name: manifest.name || name,
366
- version: manifest.version || version || "0.0.0",
367
- },
368
- files,
369
- source: normalizeSlashes(path.relative(process.cwd(), packageDir)) || packageDir,
370
- };
543
+ function encodePathParts(value) {
544
+ return String(value)
545
+ .split("/")
546
+ .filter(Boolean)
547
+ .map((part) => encodeURIComponent(part))
548
+ .join("/");
371
549
  }
372
550
 
373
- async function loadRemoteSkill(registryUrl, name, requestedVersion) {
374
- const versionPath = requestedVersion ? requestedVersion : "latest";
375
- const url = `${registryUrl}/skills/${encodeURIComponent(name)}/${encodeURIComponent(versionPath)}`;
551
+ async function fetchJsonIfOk(url) {
376
552
  const response = await fetch(url);
553
+ if (!response.ok) return null;
554
+ return response.json();
555
+ }
377
556
 
378
- if (!response.ok) {
379
- throw new Error(`Registry returned ${response.status} for ${url}`);
557
+ async function loadRemoteArtifact(registryUrl, section, name, requestedVersion) {
558
+ const versionPath = requestedVersion || "latest";
559
+ const itemPath = encodePathParts(name);
560
+ const version = encodeURIComponent(versionPath);
561
+
562
+ const urls = [
563
+ // Recommended web app contract:
564
+ // GET https://your-skillhub-app.com/api/skillhub/rules/frontend/antipattern/latest
565
+ `${registryUrl}/api/skillhub/${section}/${itemPath}/${version}`,
566
+
567
+ // Registry-only contract:
568
+ // GET https://your-registry.com/rules/frontend/antipattern/latest
569
+ `${registryUrl}/${section}/${itemPath}/${version}`,
570
+
571
+ // Legacy encoded-name contract:
572
+ `${registryUrl}/${section}/${encodeURIComponent(name)}/${version}`,
573
+ ];
574
+
575
+ let payload = null;
576
+ let usedUrl = null;
577
+ for (const url of urls) {
578
+ payload = await fetchJsonIfOk(url);
579
+ if (payload) {
580
+ usedUrl = url;
581
+ break;
582
+ }
380
583
  }
381
584
 
382
- const payload = await response.json();
383
- const manifest = payload.manifest || payload.skill || payload;
384
- const files = payload.files || [];
385
-
386
- validateSkillManifest(manifest, files);
585
+ if (!payload) {
586
+ throw new Error(`Remote ${SECTION_SINGULAR[section]} "${name}" was not found. Tried: ${urls.join(", ")}`);
587
+ }
387
588
 
388
- return {
389
- manifest,
390
- files,
391
- source: url,
392
- };
589
+ const manifest = payload.manifest || payload[SECTION_SINGULAR[section]] || payload;
590
+ const files = payload.files || [];
591
+ validateArtifactManifest(section, manifest, files);
592
+ return { manifest: { ...manifest, name: manifest.name || name, section, type: manifest.type || SECTION_SINGULAR[section] }, files, source: usedUrl };
393
593
  }
394
594
 
395
- async function loadSkill(registry, name, requestedVersion) {
595
+ async function loadArtifact(registry, section, name, requestedVersion) {
396
596
  if (registry.startsWith("http://") || registry.startsWith("https://")) {
397
- return loadRemoteSkill(registry, name, requestedVersion);
597
+ return loadRemoteArtifact(registry, section, name, requestedVersion);
398
598
  }
599
+ return loadLocalArtifact(registry, section, name, requestedVersion);
600
+ }
601
+
602
+ function validateArtifactManifest(section, manifest, files) {
603
+ if (!manifest || typeof manifest !== "object") throw new Error("Invalid manifest.");
604
+ if (!manifest.name) throw new Error("Manifest must include name.");
605
+ if (!manifest.version) throw new Error("Manifest must include version.");
606
+
607
+ const required = section === "skills" ? "SKILL.md" : section === "rules" ? "RULE.md" : "DOMAIN.md";
608
+ const hasRequired = files.some((file) => file.path === required || file.path.endsWith(`/${required}`));
609
+ if (!hasRequired && files.length === 0) throw new Error(`${manifest.name}@${manifest.version} has no files.`);
610
+ }
399
611
 
400
- return loadLocalSkill(registry, name, requestedVersion);
612
+ function cursorRuleContent(content, title) {
613
+ if (content.trimStart().startsWith("---")) return content;
614
+ return `---\ndescription: ${title}\nalwaysApply: true\n---\n\n${content}`;
401
615
  }
402
616
 
403
- function validateSkillManifest(manifest, files) {
404
- if (!manifest || typeof manifest !== "object") {
405
- throw new Error("Invalid skill manifest.");
617
+ async function writeArtifactFiles(projectRoot, config, section, artifactName, files) {
618
+ const target = getConfigTarget(config);
619
+ const baseDir = config.sections?.[section] || TARGETS[target].sections[section];
620
+
621
+ if (section === "skills") {
622
+ const targetDir = path.join(projectRoot, baseDir, artifactName);
623
+ await fs.rm(targetDir, { recursive: true, force: true });
624
+ await ensureDir(targetDir);
625
+
626
+ // Skills are capability packages. Project rules must be attached explicitly with
627
+ // `skillhub rule ...`, so we do not copy a skill package's internal rules folder
628
+ // into the IDE skill folder. This keeps .cursor/skills/app focused on the skill
629
+ // itself while .cursor/rules remains the single place for rules.
630
+ const skillFiles = files.filter((file) => {
631
+ const relativePath = normalizeSlashes(file.path);
632
+ return relativePath !== "rules" && !relativePath.startsWith("rules/");
633
+ });
634
+
635
+ for (const file of skillFiles) {
636
+ const targetPath = safeJoin(targetDir, file.path);
637
+ await ensureDir(path.dirname(targetPath));
638
+ await fs.writeFile(targetPath, file.content, "utf8");
639
+ }
640
+ return `${baseDir}/${artifactName}`;
406
641
  }
407
642
 
408
- if (!manifest.name) throw new Error("skill.json must include name.");
409
- if (!manifest.version) throw new Error("skill.json must include version.");
643
+ const entryName = section === "rules" ? "RULE.md" : "DOMAIN.md";
644
+ const singleEntry = files.length === 1 && files[0].path === entryName;
410
645
 
411
- const hasSkillMd = files.some((file) => file.path === "SKILL.md");
412
- if (!hasSkillMd) {
413
- throw new Error(`${manifest.name}@${manifest.version} must include SKILL.md.`);
646
+ if (singleEntry) {
647
+ const targetPath = safeJoin(path.join(projectRoot, baseDir), `${artifactName}.md`);
648
+ await ensureDir(path.dirname(targetPath));
649
+ await fs.writeFile(targetPath, files[0].content, "utf8");
650
+ return `${baseDir}/${artifactName}.md`;
414
651
  }
415
- }
416
652
 
417
- async function writeSkillFiles(projectRoot, skillsDir, skillName, files) {
418
- const targetDir = path.join(projectRoot, skillsDir, skillName);
653
+ const targetDir = path.join(projectRoot, baseDir, artifactName);
419
654
  await fs.rm(targetDir, { recursive: true, force: true });
420
655
  await ensureDir(targetDir);
421
-
422
656
  for (const file of files) {
423
657
  const targetPath = safeJoin(targetDir, file.path);
424
658
  await ensureDir(path.dirname(targetPath));
425
659
  await fs.writeFile(targetPath, file.content, "utf8");
426
660
  }
427
-
428
- return targetDir;
429
- }
430
-
431
- async function updateAdapters(projectRoot, config, lock) {
432
- const adapters = config.adapters || {};
433
- const skillsDir = config.skillsDir || DEFAULT_SKILLS_DIR;
434
- const installed = Object.entries(lock.skills || {}).sort(([a], [b]) => a.localeCompare(b));
435
-
436
- if (adapters.agentsMd) {
437
- await updateAgentsMd(projectRoot, skillsDir, installed);
438
- }
439
-
440
- if (adapters.cursorRules) {
441
- await updateCursorRules(projectRoot, skillsDir, installed);
442
- }
443
-
444
- if (adapters.claude) {
445
- await updateClaudeMd(projectRoot, skillsDir, installed);
446
- }
447
-
448
- if (adapters.githubCopilot) {
449
- await updateCopilotInstructions(projectRoot, skillsDir, installed);
450
- }
661
+ return `${baseDir}/${artifactName}`;
451
662
  }
452
663
 
453
- function generatedSkillList(skillsDir, installed) {
454
- if (installed.length === 0) {
455
- return "No SkillHub skills installed yet.";
664
+ function generatedArtifactList(lock) {
665
+ const installed = normalizeInstalled(lock.installed || { skills: lock.skills || {} });
666
+ const sections = [
667
+ ["Skills", "skills"],
668
+ ["Rules", "rules"],
669
+ ["Domain Knowledge", "domain"],
670
+ ];
671
+
672
+ const lines = [];
673
+ for (const [title, section] of sections) {
674
+ const entries = Object.entries(installed[section] || {}).sort(([a], [b]) => a.localeCompare(b));
675
+ lines.push(`## ${title}`);
676
+ if (entries.length === 0) {
677
+ lines.push("No entries installed.");
678
+ } else {
679
+ for (const [name, meta] of entries) {
680
+ const version = installedEntryVersion(meta);
681
+ const installTo = typeof meta === "string" ? "" : `: ${meta.installTo}`;
682
+ const localName = installedEntryLocalName(name, meta);
683
+ const label = localName && localName !== name ? `${name} → ${localName}` : name;
684
+ lines.push(`- ${label}@${version}${installTo}`);
685
+ }
686
+ }
687
+ lines.push("");
456
688
  }
457
-
458
- return installed
459
- .map(([name, meta]) => `- ${name}@${meta.version}: ${skillsDir}/${name}/SKILL.md`)
460
- .join("\n");
689
+ return lines.join("\n").trim();
461
690
  }
462
691
 
463
692
  async function replaceGeneratedBlock(filePath, generatedBlock, defaultPrefix = "") {
464
693
  let content = defaultPrefix;
465
-
466
- if (await exists(filePath)) {
467
- content = await fs.readFile(filePath, "utf8");
468
- }
694
+ if (await exists(filePath)) content = await fs.readFile(filePath, "utf8");
469
695
 
470
696
  const block = `${GENERATED_START}\n${generatedBlock.trim()}\n${GENERATED_END}`;
471
697
  const pattern = new RegExp(`${GENERATED_START}[\\s\\S]*?${GENERATED_END}`);
472
-
473
- if (pattern.test(content)) {
474
- content = content.replace(pattern, block);
475
- } else {
476
- const separator = content.trim().length > 0 ? "\n\n" : "";
477
- content = `${content.trimEnd()}${separator}${block}\n`;
478
- }
698
+ if (pattern.test(content)) content = content.replace(pattern, block);
699
+ else content = `${content.trimEnd()}${content.trim().length > 0 ? "\n\n" : ""}${block}\n`;
479
700
 
480
701
  await ensureDir(path.dirname(filePath));
481
702
  await fs.writeFile(filePath, content, "utf8");
482
703
  }
483
704
 
484
- async function updateAgentsMd(projectRoot, skillsDir, installed) {
485
- const body = `# SkillHub Instructions\n\nWhen working in this project, read and follow the installed skills below before generating or changing code.\n\n${generatedSkillList(skillsDir, installed)}`;
486
- await replaceGeneratedBlock(path.join(projectRoot, "AGENTS.md"), body, "# Project Agents\n");
487
- }
705
+ async function updateAdapters(projectRoot, config, lock) {
706
+ const adapters = config.adapters || {};
707
+ const target = getConfigTarget(config);
708
+ const body = `# SkillHub Project Knowledge\n\nBefore editing this project, read and follow the attached SkillHub knowledge packages.\n\n${generatedArtifactList(lock)}`;
488
709
 
489
- async function updateCursorRules(projectRoot, skillsDir, installed) {
490
- const body = `---\ndescription: SkillHub installed project skills\nalwaysApply: true\n---\n\n# SkillHub Rules\n\nFollow these installed skill files before editing code:\n\n${generatedSkillList(skillsDir, installed)}`;
491
- await ensureDir(path.join(projectRoot, ".cursor/rules"));
492
- await fs.writeFile(path.join(projectRoot, ".cursor/rules/skillhub.mdc"), `${body}\n`, "utf8");
493
- }
710
+ if (adapters.agentsMd) {
711
+ await replaceGeneratedBlock(path.join(projectRoot, "AGENTS.md"), body, "# Project Agents\n");
712
+ }
494
713
 
495
- async function updateClaudeMd(projectRoot, skillsDir, installed) {
496
- const body = `# SkillHub Instructions\n\nFollow the installed skills below before generating or changing code:\n\n${generatedSkillList(skillsDir, installed)}`;
497
- await replaceGeneratedBlock(path.join(projectRoot, "CLAUDE.md"), body, "# Claude Project Instructions\n");
498
- await replaceGeneratedBlock(path.join(projectRoot, ".claude/skillhub.md"), body, "# Claude SkillHub Instructions\n");
499
- }
714
+ if (adapters.cursorRules) {
715
+ const cursorBody = `---\ndescription: SkillHub installed project knowledge\nalwaysApply: true\n---\n\n${body}\n\nUse the linked skill, rule, and domain files as the source of truth.`;
716
+ await ensureDir(path.join(projectRoot, ".cursor/rules"));
717
+ await fs.writeFile(path.join(projectRoot, ".cursor/rules/skillhub.md"), `${cursorBody}\n`, "utf8");
718
+ }
500
719
 
501
- async function updateCopilotInstructions(projectRoot, skillsDir, installed) {
502
- const body = `# SkillHub Instructions\n\nUse these installed skill files as project coding guidance:\n\n${generatedSkillList(skillsDir, installed)}`;
503
- await replaceGeneratedBlock(path.join(projectRoot, ".github/copilot-instructions.md"), body, "# GitHub Copilot Instructions\n");
720
+ if (adapters.claude) {
721
+ await replaceGeneratedBlock(path.join(projectRoot, "CLAUDE.md"), body, "# Claude Project Instructions\n");
722
+ await replaceGeneratedBlock(path.join(projectRoot, ".claude/skillhub.md"), body, "# Claude SkillHub Instructions\n");
723
+ }
724
+
725
+ if (adapters.githubCopilot) {
726
+ await replaceGeneratedBlock(path.join(projectRoot, ".github/copilot-instructions.md"), body, "# GitHub Copilot Instructions\n");
727
+ }
728
+
729
+ await ensureDir(path.join(projectRoot, TARGETS[target].sections.skills));
730
+ await ensureDir(path.join(projectRoot, TARGETS[target].sections.rules));
731
+ await ensureDir(path.join(projectRoot, TARGETS[target].sections.domain));
504
732
  }
505
733
 
506
734
  async function commandInit(projectRoot, flags) {
@@ -512,17 +740,12 @@ async function commandInit(projectRoot, flags) {
512
740
  if (await exists(configPath)) {
513
741
  config = await readProjectConfig(projectRoot);
514
742
  warn(`${CONFIG_FILE} already exists.`);
515
-
516
743
  if (requestedTarget) {
517
744
  const previousTarget = getConfigTarget(config);
518
745
  applyTargetToConfig(config, requestedTarget);
519
746
  if (flags.registry) config.registry = flags.registry;
520
747
  await writeJson(configPath, config);
521
- if (previousTarget === requestedTarget) {
522
- ok(`${CONFIG_FILE} already uses target ${requestedTarget}`);
523
- } else {
524
- ok(`Updated ${CONFIG_FILE} target: ${previousTarget} → ${requestedTarget}`);
525
- }
748
+ ok(previousTarget === requestedTarget ? `${CONFIG_FILE} already uses target ${requestedTarget}` : `Updated ${CONFIG_FILE} target: ${previousTarget} → ${requestedTarget}`);
526
749
  } else if (flags.registry) {
527
750
  config.registry = flags.registry;
528
751
  await writeJson(configPath, config);
@@ -539,202 +762,339 @@ async function commandInit(projectRoot, flags) {
539
762
  ok(`Created ${CONFIG_FILE}`);
540
763
  }
541
764
 
542
- if (await exists(lockPath)) {
543
- warn(`${LOCK_FILE} already exists.`);
544
- } else {
545
- await writeJson(lockPath, defaultLock());
765
+ const lock = (await exists(lockPath)) ? await readProjectLock(projectRoot) : defaultLock();
766
+ if (await exists(lockPath)) warn(`${LOCK_FILE} already exists.`);
767
+ else {
768
+ await writeJson(lockPath, lock);
546
769
  ok(`Created ${LOCK_FILE}`);
547
770
  }
548
771
 
549
- await ensureDir(path.join(projectRoot, config.skillsDir));
550
- ok(`Created ${config.skillsDir}`);
551
-
772
+ await updateAdapters(projectRoot, config, lock);
773
+ ok(`Created ${config.sections.skills}`);
774
+ ok(`Created ${config.sections.rules}`);
775
+ ok(`Created ${config.sections.domain}`);
552
776
  info(`Target: ${config.target}`);
553
- info("Next: skillhub install nextjs-clean-architecture");
777
+ info("Next: skillhub rule frontend/antipattern");
554
778
  }
555
779
 
556
- async function commandInstall(projectRoot, spec, flags = {}) {
780
+ async function persistInstall(projectRoot, config, lock, section, sourceName, localName, artifact, installTo) {
557
781
  const configPath = path.join(projectRoot, CONFIG_FILE);
558
782
  const lockPath = path.join(projectRoot, LOCK_FILE);
783
+ const checksum = checksumFiles(artifact.files);
784
+
785
+ config.installed = normalizeInstalled(config.installed);
786
+ config.installed[section][sourceName] = {
787
+ name: sourceName,
788
+ localName,
789
+ version: artifact.manifest.version,
790
+ installTo,
791
+ };
792
+ config.skills = config.installed.skills;
793
+
794
+ lock.installed = normalizeInstalled(lock.installed);
795
+ lock.installed[section][sourceName] = {
796
+ name: sourceName,
797
+ localName,
798
+ version: artifact.manifest.version,
799
+ source: artifact.source,
800
+ installTo,
801
+ checksum,
802
+ installedAt: now(),
803
+ };
804
+ lock.skills = lock.installed.skills;
805
+ lock.updatedAt = now();
806
+
807
+ await writeJson(configPath, config);
808
+ await writeJson(lockPath, lock);
809
+ await updateAdapters(projectRoot, config, lock);
810
+ }
811
+
812
+ async function commandAttach(projectRoot, sectionValue, spec, flags = {}) {
813
+ const section = normalizeSection(sectionValue || flags.type || flags.section || "skills");
814
+ if (!spec) throw new Error(`${SECTION_SINGULAR[section]} name is required.`);
815
+
559
816
  const config = await readProjectConfig(projectRoot);
560
817
  if (flags.target || flags.to) {
561
818
  applyTargetToConfig(config, flags.target || flags.to);
562
819
  }
563
- const lock = (await readJson(lockPath, null)) || defaultLock();
564
- const registry = resolveRegistry(projectRoot, config, flags);
565
- const { name, version } = parseSkillSpec(spec);
566
-
567
- info(`Resolving ${name}${version ? `@${version}` : ""}`);
568
- const skill = await loadSkill(registry, name, version);
569
- const skillName = skill.manifest.name;
570
- const skillsDir = config.skillsDir || DEFAULT_SKILLS_DIR;
571
- const checksum = checksumFiles(skill.files);
572
820
 
573
- await writeSkillFiles(projectRoot, skillsDir, skillName, skill.files);
821
+ const lock = await readProjectLock(projectRoot);
822
+ const registry = resolveRegistry(projectRoot, config, flags);
823
+ const { name, version } = parseArtifactSpec(spec);
824
+
825
+ info(`Resolving ${SECTION_SINGULAR[section]} ${name}${version ? `@${version}` : ""}`);
826
+ const artifact = await loadArtifact(registry, section, name, version);
827
+ const sourceName = name;
828
+ const artifactName = localArtifactName(section, sourceName, artifact.manifest, flags);
829
+ const installTo = await writeArtifactFiles(projectRoot, config, section, artifactName, artifact.files);
830
+ await persistInstall(projectRoot, config, lock, section, sourceName, artifactName, artifact, installTo);
831
+
832
+ ok(`Attached ${SECTION_SINGULAR[section]} ${sourceName}@${artifact.manifest.version}`);
833
+ if (sourceName !== artifactName) info(`Local name: ${artifactName}`);
834
+ info(`Files written to ${installTo}`);
835
+ }
574
836
 
575
- config.skills = config.skills || {};
576
- config.skills[skillName] = skill.manifest.version;
577
- await writeJson(configPath, config);
837
+ async function commandInstall(projectRoot, positional, flags = {}) {
838
+ if (positional.length === 0) {
839
+ await commandSync(projectRoot, flags);
840
+ return;
841
+ }
578
842
 
579
- lock.updatedAt = now();
580
- lock.skills = lock.skills || {};
581
- lock.skills[skillName] = {
582
- version: skill.manifest.version,
583
- source: skill.source,
584
- installTo: `${skillsDir}/${skillName}`,
585
- checksum,
586
- installedAt: now(),
587
- };
588
- await writeJson(lockPath, lock);
843
+ let section = flags.type || flags.section || "skills";
844
+ let spec = positional[0];
589
845
 
590
- await updateAdapters(projectRoot, config, lock);
846
+ if (positional.length >= 2 && SECTION_ALIASES[positional[0]]) {
847
+ section = positional[0];
848
+ spec = positional[1];
849
+ }
591
850
 
592
- ok(`Installed ${skillName}@${skill.manifest.version}`);
593
- info(`Files written to ${skillsDir}/${skillName}`);
851
+ await commandAttach(projectRoot, section, spec, flags);
594
852
  }
595
853
 
596
854
  async function commandSync(projectRoot, flags = {}) {
597
- const configPath = path.join(projectRoot, CONFIG_FILE);
598
855
  const config = await readProjectConfig(projectRoot);
599
856
  if (flags.target || flags.to) {
600
857
  applyTargetToConfig(config, flags.target || flags.to);
601
- await writeJson(configPath, config);
858
+ await writeJson(path.join(projectRoot, CONFIG_FILE), config);
602
859
  }
603
- const skills = Object.entries(config.skills || {});
604
860
 
605
- if (skills.length === 0) {
606
- warn("No skills configured in skillhub.json.");
861
+ const installed = normalizeInstalled(config.installed || { skills: config.skills || {} });
862
+ const entries = [
863
+ ...Object.entries(installed.skills).map(([key, entry]) => ["skills", `${installedEntrySpec(key, entry)}@${installedEntryVersion(entry)}`, installedEntryLocalName(key, entry)]),
864
+ ...Object.entries(installed.rules).map(([key, entry]) => ["rules", `${installedEntrySpec(key, entry)}@${installedEntryVersion(entry)}`, installedEntryLocalName(key, entry)]),
865
+ ...Object.entries(installed.domain).map(([key, entry]) => ["domain", `${installedEntrySpec(key, entry)}@${installedEntryVersion(entry)}`, installedEntryLocalName(key, entry)]),
866
+ ];
867
+
868
+ if (entries.length === 0) {
869
+ warn("No SkillHub knowledge configured in skillhub.json.");
607
870
  return;
608
871
  }
609
872
 
610
- for (const [name, version] of skills) {
611
- await commandInstall(projectRoot, `${name}@${version}`, flags);
873
+ for (const [section, spec, localName] of entries) {
874
+ await commandAttach(projectRoot, section, spec, { ...flags, as: flags.as || localName });
612
875
  }
613
876
 
614
- ok(`Synced ${skills.length} skill${skills.length === 1 ? "" : "s"}.`);
877
+ ok(`Synced ${entries.length} item${entries.length === 1 ? "" : "s"}.`);
615
878
  }
616
879
 
617
880
  async function commandList(projectRoot) {
618
- const lock = await readJson(path.join(projectRoot, LOCK_FILE), null);
881
+ const lock = await readProjectLock(projectRoot);
882
+ const installed = normalizeInstalled(lock.installed || { skills: lock.skills || {} });
883
+ const hasAny = Object.values(installed).some((items) => Object.keys(items).length > 0);
619
884
 
620
- if (!lock || !lock.skills || Object.keys(lock.skills).length === 0) {
621
- warn("No skills installed yet.");
885
+ if (!hasAny) {
886
+ warn("No SkillHub knowledge attached yet.");
622
887
  return;
623
888
  }
624
889
 
625
- console.log(paint("bold", "Installed SkillHub skills"));
626
- for (const [name, meta] of Object.entries(lock.skills).sort(([a], [b]) => a.localeCompare(b))) {
627
- console.log(`- ${name}@${meta.version} ${paint("dim", `→ ${meta.installTo}`)}`);
890
+ console.log(paint("bold", "Attached SkillHub knowledge"));
891
+ for (const [title, section] of [["Skills", "skills"], ["Rules", "rules"], ["Domain", "domain"]]) {
892
+ const entries = Object.entries(installed[section] || {}).sort(([a], [b]) => a.localeCompare(b));
893
+ if (entries.length === 0) continue;
894
+ console.log(`\n${paint("bold", title)}`);
895
+ for (const [name, meta] of entries) {
896
+ const version = installedEntryVersion(meta);
897
+ const installTo = typeof meta === "string" ? "" : ` → ${meta.installTo}`;
898
+ const localName = installedEntryLocalName(name, meta);
899
+ const label = localName && localName !== name ? `${name} → ${localName}` : name;
900
+ console.log(`- ${label}@${version}${paint("dim", installTo)}`);
901
+ }
628
902
  }
629
903
  }
630
904
 
631
- async function commandRemove(projectRoot, skillName) {
632
- if (!skillName) throw new Error("Skill name is required.");
905
+ async function commandRemove(projectRoot, sectionValue, name) {
906
+ let section = normalizeSection(sectionValue || "skills");
907
+ let artifactName = name;
908
+ if (!artifactName) {
909
+ artifactName = sectionValue;
910
+ section = "skills";
911
+ }
912
+ if (!artifactName) throw new Error("Name is required.");
633
913
 
634
- const configPath = path.join(projectRoot, CONFIG_FILE);
635
- const lockPath = path.join(projectRoot, LOCK_FILE);
636
914
  const config = await readProjectConfig(projectRoot);
637
- const lock = (await readJson(lockPath, null)) || defaultLock();
638
- const skillsDir = config.skillsDir || DEFAULT_SKILLS_DIR;
639
- const installedPath = lock.skills?.[skillName]?.installTo || `${skillsDir}/${skillName}`;
640
-
641
- delete config.skills?.[skillName];
642
- delete lock.skills?.[skillName];
915
+ const lock = await readProjectLock(projectRoot);
916
+ config.installed = normalizeInstalled(config.installed);
917
+ lock.installed = normalizeInstalled(lock.installed);
918
+
919
+ const sectionLock = lock.installed[section] || {};
920
+ const sectionConfig = config.installed[section] || {};
921
+ const key = sectionLock[artifactName] || sectionConfig[artifactName]
922
+ ? artifactName
923
+ : Object.keys({ ...sectionConfig, ...sectionLock }).find((candidate) => installedEntryLocalName(candidate, sectionLock[candidate] || sectionConfig[candidate]) === artifactName);
924
+
925
+ if (!key) throw new Error(`${SECTION_SINGULAR[section]} "${artifactName}" is not attached.`);
926
+
927
+ const installedPath = sectionLock[key]?.installTo || sectionConfig[key]?.installTo;
928
+ delete config.installed[section]?.[key];
929
+ delete lock.installed[section]?.[key];
930
+ config.skills = config.installed.skills;
931
+ lock.skills = lock.installed.skills;
643
932
  lock.updatedAt = now();
644
933
 
645
- await fs.rm(path.join(projectRoot, installedPath), { recursive: true, force: true });
646
- await writeJson(configPath, config);
647
- await writeJson(lockPath, lock);
934
+ if (installedPath) await fs.rm(path.join(projectRoot, installedPath), { recursive: true, force: true });
935
+ await writeJson(path.join(projectRoot, CONFIG_FILE), config);
936
+ await writeJson(path.join(projectRoot, LOCK_FILE), lock);
648
937
  await updateAdapters(projectRoot, config, lock);
649
938
 
650
- ok(`Removed ${skillName}`);
939
+ ok(`Removed ${SECTION_SINGULAR[section]} ${artifactName}`);
651
940
  }
652
941
 
653
942
  async function commandTarget(projectRoot, targetValue, flags = {}) {
654
- const configPath = path.join(projectRoot, CONFIG_FILE);
655
- const lockPath = path.join(projectRoot, LOCK_FILE);
656
943
  const config = await readProjectConfig(projectRoot);
657
944
  const target = normalizeTarget(targetValue || flags.target || flags.to) || await askTarget(getConfigTarget(config));
658
-
659
945
  applyTargetToConfig(config, target);
660
- await writeJson(configPath, config);
661
- await ensureDir(path.join(projectRoot, config.skillsDir));
946
+ await writeJson(path.join(projectRoot, CONFIG_FILE), config);
662
947
 
663
- const lock = (await readJson(lockPath, null)) || defaultLock();
948
+ const lock = await readProjectLock(projectRoot);
664
949
  await updateAdapters(projectRoot, config, lock);
665
950
 
666
951
  ok(`SkillHub target set to ${target}`);
667
- info(`Skill files will be installed to ${config.skillsDir}`);
668
- if (Object.keys(lock.skills || {}).length > 0) {
669
- info("Run: skillhub sync");
670
- }
952
+ info(`Skills: ${config.sections.skills}`);
953
+ info(`Rules: ${config.sections.rules}`);
954
+ info(`Domain: ${config.sections.domain}`);
955
+ if (Object.values(lock.installed || {}).some((items) => Object.keys(items).length > 0)) info("Run: skillhub sync");
671
956
  }
672
957
 
673
- async function commandCreate(projectRoot, name, flags = {}) {
674
- if (!name) throw new Error("Skill name is required.");
675
-
676
- const config = (await readJson(path.join(projectRoot, CONFIG_FILE), null)) || defaultConfig(projectRoot);
677
- const registry = resolveRegistry(projectRoot, config, flags);
958
+ function titleFromName(name) {
959
+ return String(name)
960
+ .replace(/[-_]+/g, " ")
961
+ .replace(/\b\w/g, (char) => char.toUpperCase());
962
+ }
678
963
 
679
- if (registry.startsWith("http://") || registry.startsWith("https://")) {
680
- throw new Error("Cannot create a skill inside a remote registry. Use --registry ./path");
964
+ async function commandCreate(projectRoot, positional, flags = {}) {
965
+ let section = "skills";
966
+ let name = positional[0];
967
+ if (positional.length >= 2 && SECTION_ALIASES[positional[0]]) {
968
+ section = normalizeSection(positional[0]);
969
+ name = positional[1];
681
970
  }
682
-
683
- const version = flags.version || "1.0.0";
684
- const category = flags.category || "general";
685
- const packageDir = path.join(registry, name, version);
686
-
687
- if (await exists(packageDir)) {
688
- throw new Error(`Skill already exists: ${packageDir}`);
971
+ if (!name && process.stdin.isTTY && process.stdout.isTTY) {
972
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
973
+ try {
974
+ const sectionAnswer = await rl.question("Create which section? [skill/rule/domain] (skill): ");
975
+ section = normalizeSection(sectionAnswer || "skill");
976
+ name = (await rl.question(`${SECTION_SINGULAR[section]} name: `)).trim();
977
+ if (!flags.description) flags.description = (await rl.question("Description: ")).trim();
978
+ } finally {
979
+ rl.close();
980
+ }
689
981
  }
982
+ if (!name) throw new Error("Name is required. Example: skillhub create skill frontend-app");
690
983
 
691
- await ensureDir(path.join(packageDir, "rules"));
692
- await ensureDir(path.join(packageDir, "checklist"));
984
+ const config = (await readJson(path.join(projectRoot, CONFIG_FILE), null)) || defaultConfig(projectRoot);
985
+ const registry = resolveRegistry(projectRoot, config, flags, { fallbackToBundled: false });
986
+ if (registry.startsWith("http://") || registry.startsWith("https://")) throw new Error("Cannot create inside a remote registry. Use --registry ./skillhub-registry");
693
987
 
694
- await writeJson(path.join(packageDir, "skill.json"), {
695
- name,
696
- version,
697
- description: flags.description || `Reusable ${name} project skill`,
698
- category,
699
- tags: [category],
700
- entry: "SKILL.md",
701
- compatibleWith: ["cursor", "claude", "chatgpt", "github-copilot"],
702
- });
988
+ const version = flags.version || "1.0.0";
989
+ const description = flags.description || `Reusable ${SECTION_SINGULAR[section]} for ${titleFromName(name)}`;
990
+ const sectionDir = path.join(registry, section);
991
+
992
+ if (section === "skills") {
993
+ const packageDir = path.join(sectionDir, name);
994
+ if (await exists(packageDir)) throw new Error(`Skill already exists: ${packageDir}`);
995
+ await ensureDir(path.join(packageDir, "templates"));
996
+ await writeJson(path.join(packageDir, "skill.json"), {
997
+ name,
998
+ version,
999
+ type: "skill",
1000
+ section: "skills",
1001
+ description,
1002
+ category: flags.category || "development",
1003
+ tags: (flags.tags ? String(flags.tags).split(",") : ["ai", "development"]).map((item) => item.trim()).filter(Boolean),
1004
+ entry: "SKILL.md",
1005
+ compatibleWith: ["cursor", "claude", "codex", "gemini", "opencode"],
1006
+ });
1007
+ await fs.writeFile(path.join(packageDir, "SKILL.md"), `# ${titleFromName(name)}\n\n## Description\n\n${description}\n\n## When to Use\n\nUse this skill when the user asks for ${titleFromName(name).toLowerCase()} work.\n\n## Workflow\n\n1. Understand the requirement and constraints.\n2. Inspect the existing project structure before changing code.\n3. Propose the smallest safe implementation plan.\n4. Implement using project conventions.\n5. Validate with build, lint, tests, or manual checks.\n\n## Rules\n\n- Follow installed project rules first.\n- Use installed domain knowledge when relevant.\n- Do not invent APIs, paths, or product behavior.\n- Keep changes scoped to the user request.\n\n## Output\n\nExplain changed files, validation performed, and any remaining risks.\n`, "utf8");
1008
+ ok(`Created skill ${name}@${version}`);
1009
+ info(`Location: ${packageDir}`);
1010
+ return;
1011
+ }
703
1012
 
704
- await fs.writeFile(
705
- path.join(packageDir, "SKILL.md"),
706
- `# ${name}\n\n## Purpose\n\nDescribe when this skill should be used.\n\n## Rules\n\n1. Add your first rule.\n2. Add examples and edge cases.\n3. Keep outputs consistent across projects.\n\n## Definition of Done\n\n- Requirements are clear\n- Implementation follows project standards\n- Tests or validation steps are documented\n`,
707
- "utf8",
708
- );
1013
+ await ensureDir(sectionDir);
1014
+ const fileName = `${name}.md`;
1015
+ const targetPath = path.join(sectionDir, fileName);
1016
+ if (await exists(targetPath)) throw new Error(`${SECTION_SINGULAR[section]} already exists: ${targetPath}`);
1017
+ const heading = section === "rules" ? `${titleFromName(name)} Rules` : `${titleFromName(name)} Domain Knowledge`;
1018
+ const body = flags.content || `# ${heading}\n\n## Purpose\n\n${description}\n\n## Guidance\n\n- Add concrete project knowledge here.\n- Include examples, naming conventions, edge cases, and decision rules.\n- Keep this file factual and maintainable.\n`;
1019
+ await fs.writeFile(targetPath, body, "utf8");
1020
+ ok(`Created ${SECTION_SINGULAR[section]} ${name}@${version}`);
1021
+ info(`Location: ${targetPath}`);
1022
+ }
709
1023
 
710
- await fs.writeFile(path.join(packageDir, "rules/main.md"), `# ${name} Rules\n\n- Add project-specific rules here.\n`, "utf8");
711
- await fs.writeFile(path.join(packageDir, "checklist/definition-of-done.md"), `# Definition of Done\n\n- [ ] Rules followed\n- [ ] Code reviewed\n- [ ] Edge cases checked\n`, "utf8");
1024
+ async function commandValidate(projectRoot, positional, flags = {}) {
1025
+ let section = flags.type || flags.section || "skills";
1026
+ let spec = positional[0];
1027
+ if (positional.length >= 2 && SECTION_ALIASES[positional[0]]) {
1028
+ section = positional[0];
1029
+ spec = positional[1];
1030
+ }
1031
+ section = normalizeSection(section);
1032
+ if (!spec) throw new Error(`${SECTION_SINGULAR[section]} name or path is required.`);
1033
+
1034
+ let artifact;
1035
+ if (spec.includes("/") || spec.includes("\\") || spec.startsWith(".")) {
1036
+ const packagePath = path.resolve(projectRoot, spec);
1037
+ if ((await fs.stat(packagePath)).isFile()) {
1038
+ const entryName = section === "skills" ? "SKILL.md" : section === "rules" ? "RULE.md" : "DOMAIN.md";
1039
+ const files = [{ path: entryName, content: await fs.readFile(packagePath, "utf8") }];
1040
+ artifact = { manifest: defaultManifest(section, path.basename(packagePath, path.extname(packagePath)), "1.0.0", files), files };
1041
+ } else {
1042
+ const files = await readPackageFiles(packagePath);
1043
+ artifact = { manifest: defaultManifest(section, path.basename(packagePath), "1.0.0", files), files };
1044
+ }
1045
+ } else {
1046
+ const config = await readProjectConfig(projectRoot);
1047
+ const registry = resolveRegistry(projectRoot, config, flags);
1048
+ const { name, version } = parseArtifactSpec(spec);
1049
+ artifact = await loadArtifact(registry, section, name, version);
1050
+ }
712
1051
 
713
- ok(`Created ${name}@${version}`);
714
- info(`Location: ${packageDir}`);
1052
+ validateArtifactManifest(section, artifact.manifest, artifact.files);
1053
+ ok(`Valid ${SECTION_SINGULAR[section]}: ${artifact.manifest.name}@${artifact.manifest.version}`);
1054
+ info(`Files: ${artifact.files.length}`);
1055
+ info(`Checksum: ${checksumFiles(artifact.files)}`);
715
1056
  }
716
1057
 
717
- async function commandValidate(projectRoot, specOrPath, flags = {}) {
718
- if (!specOrPath) throw new Error("Skill name or path is required.");
1058
+ async function collectRegistryNames(sectionDir, section) {
1059
+ if (!(await exists(sectionDir))) return [];
1060
+ const files = await listFiles(sectionDir);
1061
+ const names = new Set();
719
1062
 
720
- let skill;
721
- if (specOrPath.includes("/") || specOrPath.includes("\\") || specOrPath.startsWith(".")) {
722
- const packageDir = path.resolve(projectRoot, specOrPath);
723
- const manifest = await readJson(path.join(packageDir, "skill.json"));
724
- const files = await readSkillPackageFiles(packageDir);
725
- validateSkillManifest(manifest, files);
726
- skill = { manifest, files };
1063
+ if (section === "skills") {
1064
+ for (const file of files) {
1065
+ if (file.endsWith("/SKILL.md") || file === "SKILL.md") {
1066
+ names.add(normalizeSlashes(path.dirname(file)));
1067
+ }
1068
+ if (file.endsWith("/skill.json") || file === "skill.json") {
1069
+ names.add(normalizeSlashes(path.dirname(file)));
1070
+ }
1071
+ }
727
1072
  } else {
728
- const config = await readProjectConfig(projectRoot);
729
- const registry = resolveRegistry(projectRoot, config, flags);
730
- const { name, version } = parseSkillSpec(specOrPath);
731
- skill = await loadSkill(registry, name, version);
1073
+ for (const file of files) {
1074
+ if (file.toLowerCase().endsWith(".md")) {
1075
+ names.add(file.replace(/\.md$/i, ""));
1076
+ }
1077
+ }
732
1078
  }
733
1079
 
734
- const checksum = checksumFiles(skill.files);
735
- ok(`Valid skill: ${skill.manifest.name}@${skill.manifest.version}`);
736
- info(`Files: ${skill.files.length}`);
737
- info(`Checksum: ${checksum}`);
1080
+ return [...names].filter((name) => name && name !== ".").sort();
1081
+ }
1082
+
1083
+ async function commandSearch(projectRoot, query, flags = {}) {
1084
+ const config = (await readJson(path.join(projectRoot, CONFIG_FILE), null)) || defaultConfig(projectRoot);
1085
+ const registry = resolveRegistry(projectRoot, config, flags);
1086
+ if (registry.startsWith("http://") || registry.startsWith("https://")) throw new Error("Remote search is not supported in this CLI build yet. Use your web app search UI, then fetch by path with skillhub rule/skill/domain.");
1087
+ const needle = String(query || "").toLowerCase();
1088
+
1089
+ console.log(paint("bold", "SkillHub registry"));
1090
+ for (const section of ["skills", "rules", "domain"]) {
1091
+ const sectionDir = path.join(registry, section);
1092
+ const names = (await collectRegistryNames(sectionDir, section))
1093
+ .filter((name) => !needle || name.toLowerCase().includes(needle));
1094
+ if (names.length === 0) continue;
1095
+ console.log(`\n${paint("bold", section)}`);
1096
+ for (const name of names) console.log(`- ${name}`);
1097
+ }
738
1098
  }
739
1099
 
740
1100
  function toWords(value) {
@@ -747,34 +1107,25 @@ function toWords(value) {
747
1107
  }
748
1108
 
749
1109
  function toKebabCase(value) {
750
- return toWords(value)
751
- .map((word) => word.toLowerCase())
752
- .join("-");
1110
+ return toWords(value).map((word) => word.toLowerCase()).join("-");
753
1111
  }
754
1112
 
755
1113
  function toCamelCase(value) {
756
1114
  const words = toWords(value).map((word) => word.toLowerCase());
757
- return words
758
- .map((word, index) => (index === 0 ? word : `${word.charAt(0).toUpperCase()}${word.slice(1)}`))
759
- .join("");
1115
+ return words.map((word, index) => (index === 0 ? word : `${word.charAt(0).toUpperCase()}${word.slice(1)}`)).join("");
760
1116
  }
761
1117
 
762
1118
  function toPascalCase(value) {
763
- return toWords(value)
764
- .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`)
765
- .join("");
1119
+ return toWords(value).map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`).join("");
766
1120
  }
767
1121
 
768
1122
  function toTitleCase(value) {
769
- return toWords(value)
770
- .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`)
771
- .join(" ");
1123
+ return toWords(value).map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`).join(" ");
772
1124
  }
773
1125
 
774
1126
  function templateVariables(name, flags = {}) {
775
1127
  const baseName = name || flags.name;
776
- if (!baseName) throw new Error("Generator name is required. Example: skillhub generate shadcn-crud-generator feature users");
777
-
1128
+ if (!baseName) throw new Error("Generator name is required. Example: skillhub generate frontend-app feature users");
778
1129
  return {
779
1130
  name: baseName,
780
1131
  kebabName: flags.kebabName || toKebabCase(baseName),
@@ -793,12 +1144,8 @@ async function commandGenerate(projectRoot, skillName, templateName, resourceNam
793
1144
  if (!templateName) throw new Error("Template name is required.");
794
1145
 
795
1146
  const config = await readProjectConfig(projectRoot);
796
- const skillsDir = config.skillsDir || DEFAULT_SKILLS_DIR;
797
- const templateDir = path.join(projectRoot, skillsDir, skillName, "templates", templateName);
798
-
799
- if (!(await exists(templateDir))) {
800
- throw new Error(`Template not found: ${skillsDir}/${skillName}/templates/${templateName}. Install the skill first.`);
801
- }
1147
+ const templateDir = path.join(projectRoot, config.sections.skills, skillName, "templates", templateName);
1148
+ if (!(await exists(templateDir))) throw new Error(`Template not found: ${config.sections.skills}/${skillName}/templates/${templateName}. Attach the skill first.`);
802
1149
 
803
1150
  const variables = templateVariables(resourceName || flags.name, flags);
804
1151
  const outDir = path.resolve(projectRoot, flags.out || `src/features/${variables.kebabName}`);
@@ -814,21 +1161,16 @@ async function commandGenerate(projectRoot, skillName, templateName, resourceNam
814
1161
  const targetPath = safeJoin(outDir, renderedRelativePath);
815
1162
  const sourcePath = path.join(templateDir, relativePath);
816
1163
  const content = await fs.readFile(sourcePath, "utf8");
817
-
818
- if ((await exists(targetPath)) && !flags.force) {
819
- throw new Error(`File already exists: ${targetPath}. Use --force to overwrite.`);
820
- }
821
-
1164
+ if ((await exists(targetPath)) && !flags.force) throw new Error(`File already exists: ${targetPath}. Use --force to overwrite.`);
822
1165
  await ensureDir(path.dirname(targetPath));
823
1166
  await fs.writeFile(targetPath, renderTemplate(content, variables), "utf8");
824
1167
  ok(`Generated ${normalizeSlashes(path.relative(projectRoot, targetPath))}`);
825
1168
  }
826
-
827
1169
  info(`Template variables: ${JSON.stringify(variables)}`);
828
1170
  }
829
1171
 
830
1172
  function printHelp() {
831
- console.log(`\n${paint("bold", "SkillHub CLI")}\n\nInstall reusable AI/project skills into any codebase.\n\n${paint("bold", "Usage")}\n skillhub <command> [options]\n\n${paint("bold", "Commands")}\n init Create skillhub.json, lockfile, and chosen skills folder\n target [ai|cursor|claude] Change where skills are installed\n install <skill[@version]> Install a skill from the registry\n sync Reinstall all skills from skillhub.json\n list Show installed skills\n remove <skill> Remove an installed skill\n create <skill> Scaffold a new local skill package\n validate <skill|path> Validate skill.json and SKILL.md\n generate <skill> <template> <name> Generate files from a skill template\n\n${paint("bold", "Targets")}\n ai Install to .ai/skills and update AGENTS.md\n cursor Install to .cursor/skills and update .cursor/rules/skillhub.mdc\n claude Install to .claude/skills and update CLAUDE.md + .claude/skillhub.md\n\n${paint("bold", "Options")}\n --target <ai|cursor|claude> Install target. Alias: --to\n --registry <path|url> Registry location. Default: ./skillhub-registry\n --version <version> Version used by create. Default: 1.0.0\n --category <name> Category used by create. Default: general\n --yes Use default init target without prompting\n\n${paint("bold", "Examples")}\n skillhub init --target cursor\n skillhub init --target claude\n skillhub install nextjs-clean-architecture --target cursor\n skillhub target claude\n skillhub sync\n skillhub create api-security-rules --category security\n`);
1173
+ console.log(`\n${paint("bold", "SkillHub CLI")}\n\nFetch SkillHub web-app knowledge into any codebase: skills, rules, and domain knowledge.\n\n${paint("bold", "Usage")}\n skillhub <command> [options]\n\n${paint("bold", "Commands")}\n init Create skillhub.json and target folders\n target [ai|cursor|claude] Change where knowledge is attached\n attach <skill|rule|domain> <name> Attach a registry item to this project\n install <name> Attach a skill. Alias for attach skill <name>\n install <rule|domain> <name> Attach rule/domain using install syntax\n sync Reinstall all configured knowledge\n list Show attached knowledge\n remove [section] <name> Remove attached knowledge\n create [skill|rule|domain] <name> Create a local registry item\n validate [section] <name|path> Validate registry item\n search [query] Search local/bundled registry\n generate <skill> <template> <name> Generate files from an attached skill template\n\n${paint("bold", "Targets")}\n ai .ai/skills, .ai/rules, .ai/domain + AGENTS.md\n cursor .cursor/skills, .cursor/rules, .cursor/domain + .cursor/rules/skillhub.md\n claude .claude/skills, .claude/rules, .claude/domain + CLAUDE.md\n\n${paint("bold", "Options")}\n --target <ai|cursor|claude> Install target. Alias: --to\n --registry <path|url> Registry location. Default: ./skillhub-registry; falls back to bundled registry\n --type <skill|rule|domain> Section for install/validate\n --version <version> Version used by create. Default: 1.0.0\n --description <text> Description used by create\n --category <name> Category used by create skill\n --tags <a,b,c> Tags used by create skill\n --yes Use default init target without prompting\n\n${paint("bold", "Examples")}\n skillhub init --target cursor\n skillhub attach skill frontend-app\n skillhub attach rule code-standards\n skillhub attach domain frontend-architecture\n skillhub install frontend-app --target claude\n skillhub create skill frontend-app --description "Develop production frontend apps"\n skillhub create rule react-query-rules\n skillhub create domain ott-video-cms\n skillhub search react\n`);
832
1174
  }
833
1175
 
834
1176
  async function main() {
@@ -845,9 +1187,22 @@ async function main() {
845
1187
  case "init":
846
1188
  await commandInit(projectRoot, flags);
847
1189
  break;
1190
+ case "attach":
1191
+ case "use":
1192
+ await commandAttach(projectRoot, positional[0], positional[1], flags);
1193
+ break;
1194
+ case "skill":
1195
+ case "skills":
1196
+ case "rule":
1197
+ case "rules":
1198
+ case "domain":
1199
+ case "domains":
1200
+ case "knowledge":
1201
+ await commandAttach(projectRoot, command, positional[0], flags);
1202
+ break;
848
1203
  case "install":
849
1204
  case "add":
850
- await commandInstall(projectRoot, positional[0], flags);
1205
+ await commandInstall(projectRoot, positional, flags);
851
1206
  break;
852
1207
  case "target":
853
1208
  case "configure":
@@ -862,13 +1217,16 @@ async function main() {
862
1217
  break;
863
1218
  case "remove":
864
1219
  case "rm":
865
- await commandRemove(projectRoot, positional[0]);
1220
+ await commandRemove(projectRoot, positional[0], positional[1]);
866
1221
  break;
867
1222
  case "create":
868
- await commandCreate(projectRoot, positional[0], flags);
1223
+ await commandCreate(projectRoot, positional, flags);
869
1224
  break;
870
1225
  case "validate":
871
- await commandValidate(projectRoot, positional[0], flags);
1226
+ await commandValidate(projectRoot, positional, flags);
1227
+ break;
1228
+ case "search":
1229
+ await commandSearch(projectRoot, positional[0], flags);
872
1230
  break;
873
1231
  case "generate":
874
1232
  case "gen":
@@ -885,13 +1243,12 @@ main().catch((error) => {
885
1243
  });
886
1244
 
887
1245
  export {
888
- parseSkillSpec,
1246
+ normalizeTarget,
1247
+ normalizeSection,
1248
+ parseArtifactSpec,
889
1249
  checksumFiles,
890
1250
  sortVersions,
891
- validateSkillManifest,
1251
+ validateArtifactManifest,
892
1252
  defaultConfig,
893
- normalizeTarget,
894
1253
  applyTargetToConfig,
895
1254
  };
896
-
897
- // Let people run this file through `node packages/skillhub-cli/bin/skillhub.mjs`.