@roilab/crm-cli 0.1.0 → 0.4.0

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 (67) hide show
  1. package/CHANGELOG.md +125 -6
  2. package/SKILL.md +256 -7
  3. package/SURFACE.txt +148 -3
  4. package/dist/bin/crm.js +26 -2
  5. package/dist/bin/crm.js.map +1 -1
  6. package/dist/src/commands/access.js +104 -0
  7. package/dist/src/commands/access.js.map +1 -0
  8. package/dist/src/commands/brief.js +52 -0
  9. package/dist/src/commands/brief.js.map +1 -0
  10. package/dist/src/commands/chat.js +203 -0
  11. package/dist/src/commands/chat.js.map +1 -0
  12. package/dist/src/commands/commands.js +89 -0
  13. package/dist/src/commands/commands.js.map +1 -0
  14. package/dist/src/commands/comment.js +1 -0
  15. package/dist/src/commands/comment.js.map +1 -1
  16. package/dist/src/commands/generic.js +335 -5
  17. package/dist/src/commands/generic.js.map +1 -1
  18. package/dist/src/commands/integrations.js +236 -0
  19. package/dist/src/commands/integrations.js.map +1 -0
  20. package/dist/src/commands/mention.js +139 -0
  21. package/dist/src/commands/mention.js.map +1 -0
  22. package/dist/src/commands/options.js +21 -1
  23. package/dist/src/commands/options.js.map +1 -1
  24. package/dist/src/commands/report.js +209 -0
  25. package/dist/src/commands/report.js.map +1 -0
  26. package/dist/src/commands/review.js +136 -0
  27. package/dist/src/commands/review.js.map +1 -1
  28. package/dist/src/commands/skill.js +836 -0
  29. package/dist/src/commands/skill.js.map +1 -0
  30. package/dist/src/commands/task.js +298 -4
  31. package/dist/src/commands/task.js.map +1 -1
  32. package/dist/src/commands/time.js +242 -0
  33. package/dist/src/commands/time.js.map +1 -0
  34. package/dist/src/lib/skillBundles.js +84 -0
  35. package/dist/src/lib/skillBundles.js.map +1 -0
  36. package/dist/src/lib/skillManifest.js +77 -0
  37. package/dist/src/lib/skillManifest.js.map +1 -0
  38. package/dist/src/lib/skillSidecar.js +69 -0
  39. package/dist/src/lib/skillSidecar.js.map +1 -0
  40. package/dist/src/lib/skillWriter.js +162 -0
  41. package/dist/src/lib/skillWriter.js.map +1 -0
  42. package/dist/src/transport/envelope.js +12 -2
  43. package/dist/src/transport/envelope.js.map +1 -1
  44. package/dist/src/transport/http.js +27 -0
  45. package/dist/src/transport/http.js.map +1 -1
  46. package/dist/src/transport/run.js +6 -0
  47. package/dist/src/transport/run.js.map +1 -1
  48. package/dist/src/types.js.map +1 -1
  49. package/dist/src/utils/server-nudge.js +57 -0
  50. package/dist/src/utils/server-nudge.js.map +1 -0
  51. package/dist/src/utils/version-check.js +68 -0
  52. package/dist/src/utils/version-check.js.map +1 -1
  53. package/package.json +2 -1
  54. package/skill-bundles/tools/ahrefs-tool/SKILL.md +134 -0
  55. package/skill-bundles/tools/brightlocal-tool/SKILL.md +154 -0
  56. package/skill-bundles/tools/dataforseo-tool/SKILL.md +118 -0
  57. package/skill-bundles/tools/google-analytics-tool/SKILL.md +143 -0
  58. package/skill-bundles/tools/google-search-console-tool/SKILL.md +133 -0
  59. package/skill-bundles/tools/local-falcon-tool/SKILL.md +142 -0
  60. package/skill-bundles/tools/localseodata-tool/SKILL.md +388 -0
  61. package/skill-bundles/tools/lsa-spy-tool/SKILL.md +113 -0
  62. package/skill-bundles/tools/screaming-frog-tool/SKILL.md +166 -0
  63. package/skill-bundles/tools/semrush-tool/SKILL.md +121 -0
  64. package/skill-bundles/tools/serpapi-tool/SKILL.md +148 -0
  65. package/skill-bundles/tools/task-preflight/SKILL.md +149 -0
  66. package/skill-bundles/tools/tool-routing/SKILL.md +59 -0
  67. package/skill-bundles/tools/whitespark-tool/SKILL.md +129 -0
@@ -0,0 +1,836 @@
1
+ /**
2
+ * Agency Skills — CLI commands (Phase 39).
3
+ *
4
+ * Humans + agents pull skills from the CRM to `.claude/skills/<slug>/SKILL.md`
5
+ * so Claude Code auto-loads them. Commands:
6
+ *
7
+ * crm skill list [--category=...] [--tag=...] [--status=...]
8
+ * crm skill show <slug> [--revision=<id>]
9
+ * crm skill pull <slug> [--revision=<id>] [--dry-run]
10
+ * crm skill pull --all [--category=...] [--tag=...]
11
+ * crm skill update # diff contentHash, refresh anything outdated
12
+ * crm skill diff <slug> # shows local-vs-remote state
13
+ *
14
+ * `list` / `show` go through the shared `run()` helper so the JSON envelope
15
+ * contract is identical to every other CLI command. `pull` / `update` / `diff`
16
+ * use the HttpClient directly because they touch disk after the fetch — they
17
+ * still emit the envelope contract at the end so agents can parse them the
18
+ * same way.
19
+ */
20
+ import { run } from "../transport/run.js";
21
+ import { HttpClient, HttpError, NetworkError } from "../transport/http.js";
22
+ import { resolveCredentials, } from "../auth/credentials.js";
23
+ import { renderError, renderSuccess, assertOutputFlagsCompatible, } from "../transport/envelope.js";
24
+ import { EXIT, exitCodeForErrorCode } from "../types.js";
25
+ import { outputFromFlags, readFlags, } from "./options.js";
26
+ import { loadManifest, saveManifest, upsertEntry, removeEntry, skillFolderPath, skillsDirPath, detectProjectRoot, } from "../lib/skillManifest.js";
27
+ import { writeSkillFiles, removeSkillFolder } from "../lib/skillWriter.js";
28
+ import { listBundleSkills } from "../lib/skillBundles.js";
29
+ import { computeContentHash, readSidecar, writeSidecar, SIDECAR_FILE_NAME, } from "../lib/skillSidecar.js";
30
+ import { randomUUID } from "node:crypto";
31
+ import { readdirSync, readFileSync, existsSync, statSync } from "node:fs";
32
+ import { join, relative, sep } from "node:path";
33
+ // ────────────────────────────────────────────────────────
34
+ // Fetch helper — direct HttpClient for commands that post-process
35
+ // ────────────────────────────────────────────────────────
36
+ async function getJson(path, flags) {
37
+ const creds = resolveCredentials(flags.profile);
38
+ const client = new HttpClient({ apiKey: creds.apiKey, apiBaseUrl: creds.apiBaseUrl });
39
+ try {
40
+ const { envelope } = await client.request("GET", path);
41
+ if (envelope.ok !== true) {
42
+ renderError(envelope);
43
+ process.exit(exitCodeForErrorCode(envelope.error.code));
44
+ }
45
+ return envelope.data;
46
+ }
47
+ catch (err) {
48
+ if (err instanceof HttpError) {
49
+ renderError(err.envelope);
50
+ if (err.envelope.ok === false) {
51
+ process.exit(exitCodeForErrorCode(err.envelope.error.code));
52
+ }
53
+ process.exit(EXIT.INTERNAL);
54
+ }
55
+ if (err instanceof NetworkError) {
56
+ process.stderr.write(`[RED] ${err.message}\n`);
57
+ process.exit(EXIT.NETWORK);
58
+ }
59
+ throw err;
60
+ }
61
+ }
62
+ function envelopeOk(data, summary) {
63
+ return {
64
+ ok: true,
65
+ data,
66
+ summary,
67
+ meta: {
68
+ requestId: randomUUID(),
69
+ timestamp: new Date().toISOString(),
70
+ },
71
+ };
72
+ }
73
+ /**
74
+ * Split a SKILL.md file into raw frontmatter + body. Mirrors the inverse of
75
+ * `assembleSkillMd` in convex/lib/skillYaml.ts. The CLI never inspects the
76
+ * frontmatter contents — the server validates on PATCH — so a literal
77
+ * splitter is enough.
78
+ */
79
+ function splitSkillMd(raw) {
80
+ // Normalise CRLF for parsing; emit LF on the wire.
81
+ const text = raw.replace(/\r\n/g, "\n");
82
+ if (!text.startsWith("---\n")) {
83
+ return { frontmatterRaw: "", body: text };
84
+ }
85
+ // Find the closing fence — the first `\n---` that's followed by a newline
86
+ // or end-of-file. Keeps `---` lines inside YAML strings safe in practice
87
+ // because real frontmatter never quotes them.
88
+ const closeIdx = text.indexOf("\n---", 4);
89
+ if (closeIdx === -1) {
90
+ return { frontmatterRaw: "", body: text };
91
+ }
92
+ const frontmatterRaw = text.slice(4, closeIdx);
93
+ // Skip the closing fence + trailing newline(s).
94
+ let bodyStart = closeIdx + "\n---".length;
95
+ if (text[bodyStart] === "\n")
96
+ bodyStart += 1;
97
+ if (text[bodyStart] === "\n")
98
+ bodyStart += 1;
99
+ return { frontmatterRaw, body: text.slice(bodyStart) };
100
+ }
101
+ /**
102
+ * Walk a skill folder and collect every text file under it as a resource,
103
+ * EXCEPT the top-level SKILL.md (returned separately by the caller) and the
104
+ * sidecar. Returns paths relative to the folder, forward-slash-normalised so
105
+ * the server stores them portably.
106
+ */
107
+ function readLocalSkillFiles(skillFolder) {
108
+ const skillMdAbs = join(skillFolder, "SKILL.md");
109
+ if (!existsSync(skillMdAbs)) {
110
+ throw new Error(`No existe ${skillMdAbs}. Ejecuta \`crm skill pull <slug>\` primero.`);
111
+ }
112
+ const skillMd = readFileSync(skillMdAbs, "utf8");
113
+ const resources = [];
114
+ const walk = (dir) => {
115
+ for (const name of readdirSync(dir)) {
116
+ // Always skip the sidecar — it's metadata, not skill content.
117
+ if (dir === skillFolder && name === SIDECAR_FILE_NAME)
118
+ continue;
119
+ const abs = join(dir, name);
120
+ const st = statSync(abs);
121
+ if (st.isDirectory()) {
122
+ walk(abs);
123
+ continue;
124
+ }
125
+ if (!st.isFile())
126
+ continue;
127
+ // Top-level SKILL.md is the assembled file, not a resource.
128
+ if (dir === skillFolder && name === "SKILL.md")
129
+ continue;
130
+ const rel = relative(skillFolder, abs).split(sep).join("/");
131
+ const content = readFileSync(abs, "utf8");
132
+ resources.push({ path: rel, content });
133
+ }
134
+ };
135
+ walk(skillFolder);
136
+ resources.sort((a, b) => a.path.localeCompare(b.path));
137
+ return { skillMd, resources };
138
+ }
139
+ /**
140
+ * Walk `.claude/skills/<*>/` and return any subfolder whose `.skill.json`
141
+ * sidecar references a skill that's no longer in `keepSkillIds`. Folders
142
+ * without a sidecar are project skills (tinybird/, next-best-practices/,
143
+ * bundle skills) and are never returned — the sidecar is the marker that
144
+ * a folder is part of the agency-skills committed mirror.
145
+ */
146
+ function findOrphanedSkillFolders(baseDir, keepSkillIds) {
147
+ const root = skillsDirPath(baseDir);
148
+ const orphans = [];
149
+ let entries;
150
+ try {
151
+ entries = readdirSync(root);
152
+ }
153
+ catch {
154
+ return orphans;
155
+ }
156
+ for (const name of entries) {
157
+ if (name.startsWith("."))
158
+ continue;
159
+ const folder = join(root, name);
160
+ let st;
161
+ try {
162
+ st = statSync(folder);
163
+ }
164
+ catch {
165
+ continue;
166
+ }
167
+ if (!st.isDirectory())
168
+ continue;
169
+ let sidecar;
170
+ try {
171
+ sidecar = readSidecar(name, baseDir);
172
+ }
173
+ catch {
174
+ // Corrupt sidecar — leave the folder alone rather than guess.
175
+ continue;
176
+ }
177
+ if (!sidecar)
178
+ continue;
179
+ if (!keepSkillIds.has(sidecar.skillId)) {
180
+ orphans.push({ slug: sidecar.slug, skillId: sidecar.skillId });
181
+ }
182
+ }
183
+ return orphans;
184
+ }
185
+ // ────────────────────────────────────────────────────────
186
+ // Command registration
187
+ // ────────────────────────────────────────────────────────
188
+ export function registerSkill(program) {
189
+ const skill = program
190
+ .command("skill")
191
+ .description("Librería de skills de la agencia para Claude Code / agentes");
192
+ // ── init
193
+ //
194
+ // Drops the bundled `*-tool` SKILL.md files into `.claude/skills/` without
195
+ // any Convex round-trip. Meant for external-tool docs (Screaming Frog,
196
+ // Ahrefs, etc.) that are stable across agencies and don't benefit from
197
+ // workspace-level revisions. Skills written this way carry `source: "bundle"`
198
+ // in the manifest so `update`/`remove` keep treating them consistently.
199
+ skill
200
+ .command("init")
201
+ .description("Copia la librería empaquetada de skills de herramientas externas a `.claude/skills/` (no requiere login).")
202
+ .option("--dry-run", "no escribe en disco, solo imprime lo que haría")
203
+ .option("--force", "ignora la comprobación de directorio raíz del proyecto y escribe en CWD aunque no parezca un repo")
204
+ .option("--preserve", "no borra archivos antiguos del skill aunque la versión empaquetada los haya quitado")
205
+ .action(async (opts, cmd) => {
206
+ const flags = readFlags(cmd);
207
+ assertOutputFlagsCompatible(outputFromFlags(flags));
208
+ const baseDir = process.cwd();
209
+ if (!opts.force && detectProjectRoot(baseDir) === null) {
210
+ process.stderr.write(`El directorio actual no parece la raíz de un proyecto. Repite con --force si realmente quieres crear .claude/skills aquí.\nCWD: ${baseDir}\n`);
211
+ process.exit(EXIT.USAGE);
212
+ }
213
+ let bundle;
214
+ try {
215
+ bundle = listBundleSkills("tools");
216
+ }
217
+ catch (err) {
218
+ process.stderr.write(`${err instanceof Error ? err.message : "bundle no disponible"}\n`);
219
+ process.exit(EXIT.INTERNAL);
220
+ }
221
+ if (bundle.length === 0) {
222
+ renderSuccess(envelopeOk({ written: [], skipped: [] }, "El bundle de skills está vacío."), outputFromFlags(flags));
223
+ return;
224
+ }
225
+ const written = [];
226
+ for (const b of bundle) {
227
+ const files = [
228
+ { path: "SKILL.md", content: b.content },
229
+ ...b.resources.map((r) => ({ path: r.path, content: r.content })),
230
+ ];
231
+ if (opts.dryRun === true) {
232
+ written.push({
233
+ slug: b.slug,
234
+ folder: skillFolderPath(b.slug, baseDir),
235
+ files: files.map((f) => f.path),
236
+ });
237
+ continue;
238
+ }
239
+ const previousFiles = loadManifest(baseDir).skills[b.slug]?.files;
240
+ const result = writeSkillFiles(skillFolderPath(b.slug, baseDir), b.slug, files, {
241
+ previousManagedPaths: previousFiles,
242
+ preserveAll: opts.preserve === true,
243
+ });
244
+ written.push({
245
+ slug: b.slug,
246
+ folder: result.folder,
247
+ files: result.files,
248
+ });
249
+ // Manifest records the bundle origin. No revisionId exists for
250
+ // bundled skills (they ship with the CLI version), so we stamp the
251
+ // CLI's pulledAt timestamp and a synthetic `bundle-<slug>` marker
252
+ // so `diff`/`update` don't mistake them for stale Convex pulls.
253
+ let manifest = loadManifest(baseDir);
254
+ manifest = upsertEntry(manifest, b.slug, {
255
+ revisionId: `bundle-${b.slug}`,
256
+ pulledAt: Date.now(),
257
+ files: result.files,
258
+ source: "bundle",
259
+ });
260
+ saveManifest(manifest, baseDir);
261
+ }
262
+ renderSuccess(envelopeOk({ written, skipped: [] }, opts.dryRun === true
263
+ ? `Dry-run: ${written.length} skill(s) listos para escribir desde el bundle.`
264
+ : `Copiados ${written.length} skill(s) del bundle a ${skillsDirPath(baseDir)}. Claude Code los cargará en el próximo prompt.`), outputFromFlags(flags));
265
+ });
266
+ // ── list
267
+ skill
268
+ .command("list")
269
+ .description("Lista los skills disponibles en el workspace")
270
+ .option("--category <name>", "filtra por categoría")
271
+ .option("--status <name>", "draft | published | archived")
272
+ .option("--tag <id>", "id del tag")
273
+ .option("--q <text>", "búsqueda libre sobre la descripción")
274
+ .action(async (opts, cmd) => {
275
+ const flags = readFlags(cmd);
276
+ await run({
277
+ method: "GET",
278
+ path: "/skills",
279
+ request: {
280
+ query: {
281
+ category: opts.category,
282
+ status: opts.status,
283
+ tagId: opts.tag,
284
+ q: opts.q,
285
+ limit: flags.limit,
286
+ },
287
+ },
288
+ output: outputFromFlags(flags),
289
+ profile: flags.profile,
290
+ });
291
+ });
292
+ // ── show
293
+ skill
294
+ .command("show")
295
+ .description("Muestra los metadatos de un skill")
296
+ .argument("<slug>")
297
+ .option("--revision <id>", "revisión específica (default: última publicada)")
298
+ .action(async (slug, opts, cmd) => {
299
+ const flags = readFlags(cmd);
300
+ const path = opts.revision
301
+ ? `/skills/${encodeURIComponent(slug)}/content?revisionId=${encodeURIComponent(opts.revision)}`
302
+ : `/skills/${encodeURIComponent(slug)}`;
303
+ await run({
304
+ method: "GET",
305
+ path,
306
+ output: outputFromFlags(flags),
307
+ profile: flags.profile,
308
+ });
309
+ });
310
+ // ── pull
311
+ //
312
+ // `--all` is the global pagination flag (registered on program root in
313
+ // registerGlobalFlags). We reuse it here for "all skills" because the
314
+ // overload is intuitive + avoids a parser collision with a subcommand-local
315
+ // option of the same name.
316
+ skill
317
+ .command("pull")
318
+ .description("Descarga uno o varios skills a `.claude/skills/<slug>/SKILL.md`. Usa --all para bajar todos los publicados.")
319
+ .argument("[slug]", "slug del skill (omitir cuando se usa --all)")
320
+ .option("--revision <id>", "revisión específica (default: última publicada)")
321
+ .option("--category <name>", "limita --all a una categoría")
322
+ .option("--tag <id>", "limita --all a un tag")
323
+ .option("--dry-run", "no escribe en disco, solo imprime lo que haría")
324
+ .option("--preserve", "no borra archivos antiguos del skill aunque la nueva revisión los haya quitado")
325
+ .option("--force", "ignora la comprobación de directorio raíz del proyecto y escribe en CWD aunque no parezca un repo")
326
+ .action(async (slug, opts, cmd) => {
327
+ const flags = readFlags(cmd);
328
+ assertOutputFlagsCompatible(outputFromFlags(flags));
329
+ const wantAll = flags.all === true;
330
+ if (wantAll && slug) {
331
+ process.stderr.write("No puedes combinar un slug con --all.\n");
332
+ process.exit(EXIT.USAGE);
333
+ }
334
+ if (!wantAll && !slug) {
335
+ process.stderr.write("Pasa un slug o --all.\n");
336
+ process.exit(EXIT.USAGE);
337
+ }
338
+ const baseDir = process.cwd();
339
+ if (!opts.force && detectProjectRoot(baseDir) === null) {
340
+ process.stderr.write(`El directorio actual no parece la raíz de un proyecto (no se encuentra .git, package.json, convex, .claude...).\n` +
341
+ `Si realmente quieres crear .claude/skills aquí, repite con --force.\n` +
342
+ `CWD: ${baseDir}\n`);
343
+ process.exit(EXIT.USAGE);
344
+ }
345
+ // Resolve the target slug list.
346
+ let targets;
347
+ // slug → skillId, populated lazily — for --all from the list call,
348
+ // for single-slug pulls from a per-slug GET in the loop below.
349
+ const skillIdBySlug = new Map();
350
+ if (wantAll) {
351
+ const list = await getJson(`/skills?${new URLSearchParams({
352
+ status: "published",
353
+ ...(opts.category ? { category: opts.category } : {}),
354
+ ...(opts.tag ? { tagId: opts.tag } : {}),
355
+ }).toString()}`, flags);
356
+ const published = list.filter((s) => s.status === "published");
357
+ for (const s of published)
358
+ skillIdBySlug.set(s.slug, s.id);
359
+ targets = published.map((s) => s.slug);
360
+ if (targets.length === 0) {
361
+ renderSuccess(envelopeOk({ written: [], skipped: [], message: "No hay skills publicados que coincidan." }, "Sin skills para descargar."), outputFromFlags(flags));
362
+ return;
363
+ }
364
+ }
365
+ else {
366
+ targets = [slug];
367
+ }
368
+ const written = [];
369
+ const skipped = [];
370
+ for (const target of targets) {
371
+ const revQuery = opts.revision ? `?revisionId=${encodeURIComponent(opts.revision)}` : "";
372
+ const content = await getJson(`/skills/${encodeURIComponent(target)}/content${revQuery}`, flags);
373
+ if (!content) {
374
+ skipped.push({ slug: target, reason: "Sin revisión publicada." });
375
+ continue;
376
+ }
377
+ const files = [
378
+ { path: "SKILL.md", content: content.assembled },
379
+ ...content.resources.map((r) => ({ path: r.path, content: r.content })),
380
+ ];
381
+ if (opts.dryRun) {
382
+ written.push({
383
+ slug: target,
384
+ folder: skillFolderPath(target, baseDir),
385
+ files: files.map((f) => f.path),
386
+ revisionId: content.revisionId,
387
+ });
388
+ continue;
389
+ }
390
+ const previousFiles = loadManifest(baseDir).skills[target]?.files;
391
+ const result = writeSkillFiles(skillFolderPath(target, baseDir), target, files, {
392
+ previousManagedPaths: previousFiles,
393
+ preserveAll: opts.preserve === true,
394
+ });
395
+ // The sidecar carries skillId so the folder remains identifiable
396
+ // across slug renames. Reuse the list-call result when available
397
+ // (--all path); fall back to a per-slug GET for single-slug pulls.
398
+ let skillId = skillIdBySlug.get(target) ?? "";
399
+ if (!skillId) {
400
+ const meta = await getJson(`/skills/${encodeURIComponent(target)}`, flags);
401
+ skillId = meta?.id ?? "";
402
+ if (skillId)
403
+ skillIdBySlug.set(target, skillId);
404
+ }
405
+ // Write sidecar so future `crm skill push` can detect drift +
406
+ // local edits. Hash covers SKILL.md + every resource file.
407
+ writeSidecar(target, {
408
+ skillId,
409
+ revisionId: content.revisionId,
410
+ contentHash: computeContentHash(files),
411
+ }, baseDir);
412
+ written.push({
413
+ slug: target,
414
+ folder: result.folder,
415
+ files: result.files,
416
+ revisionId: content.revisionId,
417
+ });
418
+ // Update manifest after each successful write so a crash mid-loop
419
+ // leaves a consistent record of what we did manage to pull. The
420
+ // manifest stays gitignored (per-dev state); the sidecar above is
421
+ // the committed drift basis. Sidecar is NOT listed in `files` so
422
+ // a later pull's orphan-pruning never deletes it.
423
+ let manifest = loadManifest(baseDir);
424
+ manifest = upsertEntry(manifest, target, {
425
+ revisionId: content.revisionId,
426
+ pulledAt: Date.now(),
427
+ files: result.files,
428
+ });
429
+ saveManifest(manifest, baseDir);
430
+ }
431
+ // Auto-prune folders whose sidecar references a skill that's no longer
432
+ // published (archived or deleted server-side). Only runs when the
433
+ // pull is unfiltered — with --category/--tag the returned list is a
434
+ // subset, so we cannot tell archived from "filtered out".
435
+ const removed = [];
436
+ if (wantAll && !opts.dryRun && !opts.category && !opts.tag) {
437
+ const publishedIds = new Set(skillIdBySlug.values());
438
+ for (const orphan of findOrphanedSkillFolders(baseDir, publishedIds)) {
439
+ removeSkillFolder(skillFolderPath(orphan.slug, baseDir), orphan.slug);
440
+ saveManifest(removeEntry(loadManifest(baseDir), orphan.slug), baseDir);
441
+ removed.push({ slug: orphan.slug, reason: "archived_or_deleted" });
442
+ }
443
+ }
444
+ const removedNote = removed.length === 0 ? "" : ` ${removed.length} archivado(s) eliminado(s) del mirror.`;
445
+ renderSuccess(envelopeOk({ written, skipped, removed }, opts.dryRun
446
+ ? `Dry-run: ${written.length} skill(s) listos para escribir.`
447
+ : `Descargados ${written.length} skill(s) a ${skillsDirPath(baseDir)}.${removedNote} Claude Code los cargará en el próximo prompt.`), outputFromFlags(flags));
448
+ });
449
+ // ── update
450
+ skill
451
+ .command("update")
452
+ .description("Refresca todos los skills instalados. Compara el manifest local con la revisión actual y descarga solo lo que cambió.")
453
+ .option("--dry-run", "no escribe en disco, solo informa lo desactualizado")
454
+ .option("--preserve", "no borra archivos antiguos del skill aunque la nueva revisión los haya quitado")
455
+ .option("--prune-archived", "elimina del manifest + disco los skills que el servidor marcó como archivados")
456
+ .action(async (opts, cmd) => {
457
+ const flags = readFlags(cmd);
458
+ assertOutputFlagsCompatible(outputFromFlags(flags));
459
+ const baseDir = process.cwd();
460
+ const manifest = loadManifest(baseDir);
461
+ const installed = Object.values(manifest.skills);
462
+ if (installed.length === 0) {
463
+ renderSuccess(envelopeOk({ updated: [], upToDate: [], missing: [], archived: [] }, "No hay skills instalados. Usa `crm skill pull --all` para empezar."), outputFromFlags(flags));
464
+ return;
465
+ }
466
+ const updated = [];
467
+ const upToDate = [];
468
+ const missing = [];
469
+ const archived = [];
470
+ const bundled = [];
471
+ for (const entry of installed) {
472
+ // Bundled skills are versioned by CLI release, not by Convex revisions.
473
+ // `crm skill init` refreshes them from whatever the installed CLI ships
474
+ // with — never re-fetch from the API for these.
475
+ if (entry.source === "bundle") {
476
+ bundled.push(entry.slug);
477
+ continue;
478
+ }
479
+ const skill = await getJson(`/skills/${encodeURIComponent(entry.slug)}`, flags);
480
+ if (!skill) {
481
+ missing.push(entry.slug);
482
+ continue;
483
+ }
484
+ if (skill.status === "archived") {
485
+ // Server still has it but won't ship it on `pull --all`. Either
486
+ // surface for the user, or auto-remove if they asked us to.
487
+ if (opts.pruneArchived === true && opts.dryRun !== true) {
488
+ removeSkillFolder(skillFolderPath(entry.slug, baseDir), entry.slug);
489
+ saveManifest(removeEntry(loadManifest(baseDir), entry.slug), baseDir);
490
+ archived.push({ slug: entry.slug, pruned: true });
491
+ }
492
+ else {
493
+ archived.push({ slug: entry.slug, pruned: false });
494
+ }
495
+ continue;
496
+ }
497
+ if (!skill.currentRevisionId) {
498
+ missing.push(entry.slug);
499
+ continue;
500
+ }
501
+ if (skill.currentRevisionId === entry.revisionId) {
502
+ upToDate.push(entry.slug);
503
+ continue;
504
+ }
505
+ if (opts.dryRun) {
506
+ updated.push({
507
+ slug: entry.slug,
508
+ fromRevisionId: entry.revisionId,
509
+ toRevisionId: skill.currentRevisionId,
510
+ });
511
+ continue;
512
+ }
513
+ const content = await getJson(`/skills/${encodeURIComponent(entry.slug)}/content`, flags);
514
+ const files = [
515
+ { path: "SKILL.md", content: content.assembled },
516
+ ...content.resources.map((r) => ({ path: r.path, content: r.content })),
517
+ ];
518
+ const result = writeSkillFiles(skillFolderPath(entry.slug, baseDir), entry.slug, files, {
519
+ previousManagedPaths: entry.files,
520
+ preserveAll: opts.preserve === true,
521
+ });
522
+ const next = upsertEntry(loadManifest(baseDir), entry.slug, {
523
+ revisionId: content.revisionId,
524
+ pulledAt: Date.now(),
525
+ files: result.files,
526
+ });
527
+ saveManifest(next, baseDir);
528
+ updated.push({
529
+ slug: entry.slug,
530
+ fromRevisionId: entry.revisionId,
531
+ toRevisionId: content.revisionId,
532
+ });
533
+ }
534
+ const archivedNote = archived.length === 0
535
+ ? ""
536
+ : opts.pruneArchived
537
+ ? ` ${archived.length} archivado(s) eliminado(s).`
538
+ : ` ${archived.length} archivado(s) en el servidor — usa --prune-archived o \`crm skill remove\` para limpiarlos.`;
539
+ const bundledNote = bundled.length === 0
540
+ ? ""
541
+ : ` ${bundled.length} bundled (refresca con \`crm skill init\`).`;
542
+ renderSuccess(envelopeOk({ updated, upToDate, missing, archived, bundled }, opts.dryRun
543
+ ? `${updated.length} skill(s) desactualizados, ${upToDate.length} al día.${archivedNote}${bundledNote}`
544
+ : `${updated.length} skill(s) actualizados, ${upToDate.length} al día.${archivedNote}${bundledNote} Claude Code los cargará en el próximo prompt.`), outputFromFlags(flags));
545
+ });
546
+ // ── remove
547
+ skill
548
+ .command("remove")
549
+ .description("Elimina un skill instalado: borra `.claude/skills/<slug>/` y la entrada del manifest.")
550
+ .argument("<slug>")
551
+ .option("--purge", "borra el directorio aunque no exista una entrada en el manifest (útil tras desinstalaciones manuales o slugs huérfanos)")
552
+ .action(async (slug, opts, cmd) => {
553
+ const flags = readFlags(cmd);
554
+ assertOutputFlagsCompatible(outputFromFlags(flags));
555
+ const baseDir = process.cwd();
556
+ const manifest = loadManifest(baseDir);
557
+ const wasInManifest = Boolean(manifest.skills[slug]);
558
+ if (!wasInManifest && opts.purge !== true) {
559
+ renderError({
560
+ ok: false,
561
+ error: {
562
+ code: "NOT_FOUND",
563
+ message: `\`${slug}\` no figura en el manifest. Usa --purge para forzar el borrado del directorio.`,
564
+ retryable: false,
565
+ },
566
+ meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
567
+ });
568
+ process.exit(exitCodeForErrorCode("NOT_FOUND"));
569
+ }
570
+ const folder = skillFolderPath(slug, baseDir);
571
+ const removed = removeSkillFolder(folder, slug);
572
+ if (wasInManifest) {
573
+ saveManifest(removeEntry(manifest, slug), baseDir);
574
+ }
575
+ renderSuccess(envelopeOk({
576
+ slug,
577
+ folderRemoved: removed,
578
+ manifestEntryRemoved: wasInManifest,
579
+ folder,
580
+ }, removed
581
+ ? `Eliminado \`${slug}\` (${folder}).`
582
+ : `No había nada que borrar en ${folder}.`), outputFromFlags(flags));
583
+ });
584
+ // ── diff
585
+ skill
586
+ .command("diff")
587
+ .description("Compara la copia local con la revisión actual en el servidor")
588
+ .argument("<slug>")
589
+ .action(async (slug, _opts, cmd) => {
590
+ const flags = readFlags(cmd);
591
+ const baseDir = process.cwd();
592
+ const manifest = loadManifest(baseDir);
593
+ const local = manifest.skills[slug];
594
+ const skill = await getJson(`/skills/${encodeURIComponent(slug)}`, flags);
595
+ if (!skill) {
596
+ renderError({
597
+ ok: false,
598
+ error: {
599
+ code: "NOT_FOUND",
600
+ message: `Skill \`${slug}\` no existe en el workspace.`,
601
+ retryable: false,
602
+ },
603
+ meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
604
+ });
605
+ process.exit(exitCodeForErrorCode("NOT_FOUND"));
606
+ }
607
+ const remoteRevisionId = skill.currentRevisionId;
608
+ const localRevisionId = local?.revisionId ?? null;
609
+ const status = !local
610
+ ? "not_installed"
611
+ : skill.status === "archived"
612
+ ? "archived_remote"
613
+ : remoteRevisionId === localRevisionId
614
+ ? "up_to_date"
615
+ : "outdated";
616
+ renderSuccess(envelopeOk({
617
+ slug,
618
+ status,
619
+ localRevisionId,
620
+ remoteRevisionId,
621
+ remoteStatus: skill.status,
622
+ pulledAt: local?.pulledAt ?? null,
623
+ }, `\`${slug}\`: ${status}`), outputFromFlags(flags));
624
+ });
625
+ // ── push
626
+ //
627
+ // Sends local edits to `.claude/skills/<slug>/` back to Convex. By default
628
+ // creates a draft revision (review in /dashboard/skills/<slug>); pass
629
+ // --publish to chain the publish step in one call.
630
+ //
631
+ // Two safety checks gate the write:
632
+ // - drift: sidecar.revisionId vs server's currentRevisionId. Rejected
633
+ // unless --force.
634
+ // - draft-pending: server's draftBody/draftFrontmatterRaw differs from the
635
+ // last published revision. Rejected unless --force-overwrite-draft.
636
+ skill
637
+ .command("push")
638
+ .description("Envía las ediciones locales de `.claude/skills/<slug>/` al servidor como un draft. Usa --publish para publicar en la misma llamada.")
639
+ .argument("<slug>")
640
+ .requiredOption("--note <text>", "resumen del cambio (≤200 chars; obligatorio para --publish)")
641
+ .option("--publish", "publica el draft inmediatamente (requiere rol owner/admin en la API key)")
642
+ .option("--force", "ignora la comprobación de drift (sidecar.revisionId ≠ servidor)")
643
+ .option("--force-overwrite-draft", "sobrescribe un draft pendiente en el servidor que difiere del publicado")
644
+ .option("--dry-run", "no envía nada, solo informa qué haría")
645
+ .action(async (slug, opts, cmd) => {
646
+ const flags = readFlags(cmd);
647
+ assertOutputFlagsCompatible(outputFromFlags(flags));
648
+ const baseDir = process.cwd();
649
+ const sidecar = readSidecar(slug, baseDir);
650
+ if (!sidecar) {
651
+ renderError({
652
+ ok: false,
653
+ error: {
654
+ code: "NOT_FOUND",
655
+ message: `\`${slug}\` no está en el mirror local. Ejecuta \`crm skill pull ${slug}\` primero.`,
656
+ retryable: false,
657
+ },
658
+ meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
659
+ });
660
+ process.exit(exitCodeForErrorCode("NOT_FOUND"));
661
+ }
662
+ if (opts.note.length > 200) {
663
+ process.stderr.write("--note debe tener 200 caracteres o menos.\n");
664
+ process.exit(EXIT.USAGE);
665
+ }
666
+ // Read local files + compute hash for the no-op short-circuit.
667
+ const skillFolder = skillFolderPath(slug, baseDir);
668
+ const { skillMd, resources } = readLocalSkillFiles(skillFolder);
669
+ const allFiles = [
670
+ { path: "SKILL.md", content: skillMd },
671
+ ...resources,
672
+ ];
673
+ const localHash = computeContentHash(allFiles);
674
+ // Idempotency: nothing changed locally and we're not asking for an
675
+ // explicit publish → bail. (--publish on an unchanged skill still
676
+ // does something useful: re-publish the existing draft if any.)
677
+ if (localHash === sidecar.contentHash && !opts.publish) {
678
+ renderSuccess(envelopeOk({ slug, action: "noop", revisionId: sidecar.revisionId }, "Sin cambios locales — nada que enviar."), outputFromFlags(flags));
679
+ return;
680
+ }
681
+ // Fetch current server state for drift + pending-draft checks.
682
+ const remote = await getJson(`/skills/${encodeURIComponent(slug)}`, flags);
683
+ if (!remote) {
684
+ renderError({
685
+ ok: false,
686
+ error: {
687
+ code: "NOT_FOUND",
688
+ message: `Skill \`${slug}\` ya no existe en el servidor. Borra el folder local o restaura el skill en /dashboard/skills.`,
689
+ retryable: false,
690
+ },
691
+ meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
692
+ });
693
+ process.exit(exitCodeForErrorCode("NOT_FOUND"));
694
+ }
695
+ // Drift: server moved past the revision the sidecar was based on.
696
+ const serverRevisionId = remote.currentRevisionId ?? null;
697
+ if (serverRevisionId &&
698
+ serverRevisionId !== sidecar.revisionId &&
699
+ !opts.force) {
700
+ renderError({
701
+ ok: false,
702
+ error: {
703
+ code: "CONFLICT",
704
+ message: `Drift detectado: el servidor está en la revisión ${serverRevisionId} ` +
705
+ `pero tu mirror está en ${sidecar.revisionId}. ` +
706
+ `Ejecuta \`crm skill pull ${slug}\` y reaplica tus cambios, o repite con --force.`,
707
+ retryable: false,
708
+ },
709
+ meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
710
+ });
711
+ process.exit(exitCodeForErrorCode("CONFLICT"));
712
+ }
713
+ // Pending draft: server's draft body differs from what we'd produce
714
+ // locally if we hadn't edited anything. Approximation: compare the
715
+ // server's draft against the on-disk SKILL.md split. If they differ
716
+ // AND the on-disk hash matches the sidecar (i.e. we have no local
717
+ // edits), the only explanation is a draft submitted by someone else.
718
+ // If we DO have local edits, the comparison is ambiguous — be safe
719
+ // and require --force-overwrite-draft only when it would clobber a
720
+ // draft that was clearly authored elsewhere.
721
+ const { frontmatterRaw, body } = splitSkillMd(skillMd);
722
+ const remoteHasPendingDraft = remote.draftBody !== body || remote.draftFrontmatterRaw !== frontmatterRaw;
723
+ const localUnchanged = localHash === sidecar.contentHash;
724
+ if (remoteHasPendingDraft &&
725
+ !localUnchanged &&
726
+ !opts.forceOverwriteDraft) {
727
+ renderError({
728
+ ok: false,
729
+ error: {
730
+ code: "CONFLICT",
731
+ message: "Hay un draft pendiente en el servidor que difiere del publicado. " +
732
+ "Revísalo en /dashboard/skills/" +
733
+ slug +
734
+ " o repite con --force-overwrite-draft para sobrescribirlo.",
735
+ retryable: false,
736
+ },
737
+ meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
738
+ });
739
+ process.exit(exitCodeForErrorCode("CONFLICT"));
740
+ }
741
+ if (opts.dryRun) {
742
+ renderSuccess(envelopeOk({
743
+ slug,
744
+ action: opts.publish ? "would_publish" : "would_draft",
745
+ bodyLength: body.length,
746
+ resourceCount: resources.length,
747
+ serverRevisionId,
748
+ }, opts.publish
749
+ ? `Dry-run: publicaría \`${slug}\` con ${resources.length} recurso(s).`
750
+ : `Dry-run: actualizaría el draft de \`${slug}\`.`), outputFromFlags(flags));
751
+ return;
752
+ }
753
+ // Update the draft (body + frontmatter only — resources flow through
754
+ // publish per the schema).
755
+ const creds = resolveCredentials(flags.profile);
756
+ const client = new HttpClient({ apiKey: creds.apiKey, apiBaseUrl: creds.apiBaseUrl });
757
+ try {
758
+ const patchRes = await client.request("PATCH", `/skills/${encodeURIComponent(slug)}`, { body: { draftBody: body, draftFrontmatterRaw: frontmatterRaw } });
759
+ if (patchRes.envelope.ok !== true) {
760
+ renderError(patchRes.envelope);
761
+ process.exit(exitCodeForErrorCode(patchRes.envelope.error.code));
762
+ }
763
+ }
764
+ catch (err) {
765
+ if (err instanceof HttpError) {
766
+ renderError(err.envelope);
767
+ if (err.envelope.ok === false) {
768
+ process.exit(exitCodeForErrorCode(err.envelope.error.code));
769
+ }
770
+ process.exit(EXIT.INTERNAL);
771
+ }
772
+ if (err instanceof NetworkError) {
773
+ process.stderr.write(`[RED] ${err.message}\n`);
774
+ process.exit(EXIT.NETWORK);
775
+ }
776
+ throw err;
777
+ }
778
+ if (!opts.publish) {
779
+ renderSuccess(envelopeOk({ slug, action: "drafted", revisionId: sidecar.revisionId }, `Draft de \`${slug}\` actualizado. Revisa en /dashboard/skills/${slug} y publica desde la UI (o repite con --publish).`), outputFromFlags(flags));
780
+ return;
781
+ }
782
+ let publishedRevisionId;
783
+ try {
784
+ const publishRes = await client.request("POST", `/skills/${encodeURIComponent(slug)}/publish`, {
785
+ body: {
786
+ changeSummary: opts.note,
787
+ resources: resources.map((r) => ({
788
+ path: r.path,
789
+ content: r.content,
790
+ contentType: "text/plain",
791
+ })),
792
+ },
793
+ });
794
+ if (publishRes.envelope.ok !== true) {
795
+ renderError(publishRes.envelope);
796
+ process.exit(exitCodeForErrorCode(publishRes.envelope.error.code));
797
+ }
798
+ // Success envelope guarantees `data`; TS doesn't follow process.exit
799
+ // through the early-return branch above.
800
+ publishedRevisionId = publishRes.envelope.data.revisionId;
801
+ }
802
+ catch (err) {
803
+ if (err instanceof HttpError) {
804
+ renderError(err.envelope);
805
+ if (err.envelope.ok === false) {
806
+ process.exit(exitCodeForErrorCode(err.envelope.error.code));
807
+ }
808
+ process.exit(EXIT.INTERNAL);
809
+ }
810
+ if (err instanceof NetworkError) {
811
+ process.stderr.write(`[RED] ${err.message}\n`);
812
+ process.exit(EXIT.NETWORK);
813
+ }
814
+ throw err;
815
+ }
816
+ // Refresh sidecar so next push starts from the new published revision.
817
+ writeSidecar(slug, {
818
+ skillId: sidecar.skillId,
819
+ revisionId: publishedRevisionId,
820
+ contentHash: localHash,
821
+ }, baseDir);
822
+ // Refresh manifest's revisionId for `crm skill update`/`diff`.
823
+ const manifestNow = loadManifest(baseDir);
824
+ const existingEntry = manifestNow.skills[slug];
825
+ if (existingEntry) {
826
+ saveManifest(upsertEntry(manifestNow, slug, {
827
+ revisionId: publishedRevisionId,
828
+ pulledAt: existingEntry.pulledAt,
829
+ files: existingEntry.files,
830
+ source: existingEntry.source,
831
+ }), baseDir);
832
+ }
833
+ renderSuccess(envelopeOk({ slug, action: "published", revisionId: publishedRevisionId }, `Publicado \`${slug}\` como revisión ${publishedRevisionId}.`), outputFromFlags(flags));
834
+ });
835
+ }
836
+ //# sourceMappingURL=skill.js.map