@roilab/crm-cli 0.1.0 → 0.6.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.
- package/CHANGELOG.md +195 -25
- package/SKILL.md +256 -7
- package/SURFACE.txt +237 -69
- package/dist/bin/crm.js +28 -2
- package/dist/bin/crm.js.map +1 -1
- package/dist/src/commands/access.js +104 -0
- package/dist/src/commands/access.js.map +1 -0
- package/dist/src/commands/brief.js +52 -0
- package/dist/src/commands/brief.js.map +1 -0
- package/dist/src/commands/chat.js +220 -0
- package/dist/src/commands/chat.js.map +1 -0
- package/dist/src/commands/commands.js +89 -0
- package/dist/src/commands/commands.js.map +1 -0
- package/dist/src/commands/comment.js +1 -0
- package/dist/src/commands/comment.js.map +1 -1
- package/dist/src/commands/generic.js +335 -5
- package/dist/src/commands/generic.js.map +1 -1
- package/dist/src/commands/integrations.js +236 -0
- package/dist/src/commands/integrations.js.map +1 -0
- package/dist/src/commands/mention.js +139 -0
- package/dist/src/commands/mention.js.map +1 -0
- package/dist/src/commands/options.js +21 -1
- package/dist/src/commands/options.js.map +1 -1
- package/dist/src/commands/rank.js +300 -0
- package/dist/src/commands/rank.js.map +1 -0
- package/dist/src/commands/report.js +209 -0
- package/dist/src/commands/report.js.map +1 -0
- package/dist/src/commands/review.js +136 -0
- package/dist/src/commands/review.js.map +1 -1
- package/dist/src/commands/skill.js +1005 -0
- package/dist/src/commands/skill.js.map +1 -0
- package/dist/src/commands/task.js +298 -4
- package/dist/src/commands/task.js.map +1 -1
- package/dist/src/commands/time.js +242 -0
- package/dist/src/commands/time.js.map +1 -0
- package/dist/src/lib/skillBundles.js +84 -0
- package/dist/src/lib/skillBundles.js.map +1 -0
- package/dist/src/lib/skillManifest.js +77 -0
- package/dist/src/lib/skillManifest.js.map +1 -0
- package/dist/src/lib/skillSidecar.js +69 -0
- package/dist/src/lib/skillSidecar.js.map +1 -0
- package/dist/src/lib/skillWriter.js +162 -0
- package/dist/src/lib/skillWriter.js.map +1 -0
- package/dist/src/transport/envelope.js +12 -2
- package/dist/src/transport/envelope.js.map +1 -1
- package/dist/src/transport/http.js +27 -0
- package/dist/src/transport/http.js.map +1 -1
- package/dist/src/transport/run.js +6 -0
- package/dist/src/transport/run.js.map +1 -1
- package/dist/src/types.js.map +1 -1
- package/dist/src/utils/server-nudge.js +57 -0
- package/dist/src/utils/server-nudge.js.map +1 -0
- package/dist/src/utils/version-check.js +68 -0
- package/dist/src/utils/version-check.js.map +1 -1
- package/package.json +58 -57
- package/skill-bundles/tools/ahrefs-tool/SKILL.md +134 -0
- package/skill-bundles/tools/brightlocal-tool/SKILL.md +154 -0
- package/skill-bundles/tools/dataforseo-tool/SKILL.md +118 -0
- package/skill-bundles/tools/google-analytics-tool/SKILL.md +143 -0
- package/skill-bundles/tools/google-search-console-tool/SKILL.md +133 -0
- package/skill-bundles/tools/local-falcon-tool/SKILL.md +142 -0
- package/skill-bundles/tools/localseodata-tool/SKILL.md +388 -0
- package/skill-bundles/tools/lsa-spy-tool/SKILL.md +113 -0
- package/skill-bundles/tools/screaming-frog-tool/SKILL.md +166 -0
- package/skill-bundles/tools/semrush-tool/SKILL.md +121 -0
- package/skill-bundles/tools/serpapi-tool/SKILL.md +148 -0
- package/skill-bundles/tools/task-preflight/SKILL.md +149 -0
- package/skill-bundles/tools/tool-routing/SKILL.md +59 -0
- package/skill-bundles/tools/whitespark-tool/SKILL.md +129 -0
|
@@ -0,0 +1,1005 @@
|
|
|
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
|
+
// ── revisions (history)
|
|
311
|
+
skill
|
|
312
|
+
.command("revisions")
|
|
313
|
+
.description("Historial de revisiones publicadas del skill (autor + changeSummary + timestamp).")
|
|
314
|
+
.argument("<slug>")
|
|
315
|
+
.action(async (slug, _opts, cmd) => {
|
|
316
|
+
const flags = readFlags(cmd);
|
|
317
|
+
await run({
|
|
318
|
+
method: "GET",
|
|
319
|
+
path: `/skills/${encodeURIComponent(slug)}/revisions`,
|
|
320
|
+
request: { query: { limit: flags.limit } },
|
|
321
|
+
output: outputFromFlags(flags),
|
|
322
|
+
profile: flags.profile,
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
// ── revision (single immutable revision body + frontmatter + resources)
|
|
326
|
+
skill
|
|
327
|
+
.command("revision")
|
|
328
|
+
.description("Obtiene una revisión inmutable por id (body + frontmatter + recursos).")
|
|
329
|
+
.argument("<id>", "id de la revisión")
|
|
330
|
+
.action(async (id, _opts, cmd) => {
|
|
331
|
+
const flags = readFlags(cmd);
|
|
332
|
+
await run({
|
|
333
|
+
method: "GET",
|
|
334
|
+
path: `/skills/revisions/${encodeURIComponent(id)}`,
|
|
335
|
+
output: outputFromFlags(flags),
|
|
336
|
+
profile: flags.profile,
|
|
337
|
+
});
|
|
338
|
+
});
|
|
339
|
+
const SKILL_CATEGORIES = [
|
|
340
|
+
"local-seo",
|
|
341
|
+
"google-ads",
|
|
342
|
+
"technical-seo",
|
|
343
|
+
"content",
|
|
344
|
+
"link-building",
|
|
345
|
+
"crm-ops",
|
|
346
|
+
"workflow",
|
|
347
|
+
"general",
|
|
348
|
+
];
|
|
349
|
+
const SKILL_KINDS = ["playbook", "workflow", "tool", "reference"];
|
|
350
|
+
const SKILL_VISIBILITIES = ["workspace", "staff_only"];
|
|
351
|
+
// ── create (draft only — publish with `crm skill push --publish`)
|
|
352
|
+
skill
|
|
353
|
+
.command("create")
|
|
354
|
+
.description("Crea un skill en estado draft. Usa `crm skill push <slug> --publish` para publicar la primera revisión.")
|
|
355
|
+
.requiredOption("--slug <slug>", "identificador lowercase-hyphen (3-64 chars)")
|
|
356
|
+
.requiredOption("--name <name>", "nombre visible")
|
|
357
|
+
.requiredOption("--description <text>", "descripción para agentes (≤1024 chars)")
|
|
358
|
+
.requiredOption("--category <name>", `categoría: ${SKILL_CATEGORIES.join(" | ")}`)
|
|
359
|
+
.option("--kind <kind>", `forma del skill: ${SKILL_KINDS.join(" | ")}`)
|
|
360
|
+
.option("--tag <id...>", "id(s) de tag a aplicar")
|
|
361
|
+
.option("--visibility <v>", `visibilidad: ${SKILL_VISIBILITIES.join(" | ")} (default: workspace)`)
|
|
362
|
+
.option("--body <text>", "cuerpo inicial del draft (markdown)")
|
|
363
|
+
.option("--frontmatter <yaml>", "frontmatter YAML inicial del draft")
|
|
364
|
+
.action(async (opts, cmd) => {
|
|
365
|
+
const flags = readFlags(cmd);
|
|
366
|
+
if (!SKILL_CATEGORIES.includes(opts.category)) {
|
|
367
|
+
process.stderr.write(`error: --category debe ser uno de ${SKILL_CATEGORIES.join(", ")}\n`);
|
|
368
|
+
process.exit(2);
|
|
369
|
+
}
|
|
370
|
+
if (opts.kind !== undefined && !SKILL_KINDS.includes(opts.kind)) {
|
|
371
|
+
process.stderr.write(`error: --kind debe ser uno de ${SKILL_KINDS.join(", ")}\n`);
|
|
372
|
+
process.exit(2);
|
|
373
|
+
}
|
|
374
|
+
if (opts.visibility !== undefined &&
|
|
375
|
+
!SKILL_VISIBILITIES.includes(opts.visibility)) {
|
|
376
|
+
process.stderr.write(`error: --visibility debe ser uno de ${SKILL_VISIBILITIES.join(", ")}\n`);
|
|
377
|
+
process.exit(2);
|
|
378
|
+
}
|
|
379
|
+
await run({
|
|
380
|
+
method: "POST",
|
|
381
|
+
path: "/skills",
|
|
382
|
+
request: {
|
|
383
|
+
body: {
|
|
384
|
+
slug: opts.slug,
|
|
385
|
+
name: opts.name,
|
|
386
|
+
description: opts.description,
|
|
387
|
+
category: opts.category,
|
|
388
|
+
kind: opts.kind,
|
|
389
|
+
tagIds: opts.tag,
|
|
390
|
+
visibility: opts.visibility,
|
|
391
|
+
initialBody: opts.body,
|
|
392
|
+
initialFrontmatterRaw: opts.frontmatter,
|
|
393
|
+
},
|
|
394
|
+
idempotencyKey: flags.idempotencyKey,
|
|
395
|
+
},
|
|
396
|
+
output: outputFromFlags(flags),
|
|
397
|
+
profile: flags.profile,
|
|
398
|
+
asAgent: flags.asAgent,
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
// ── set (metadata-only PATCH; body edits go through `crm skill push`)
|
|
402
|
+
skill
|
|
403
|
+
.command("set")
|
|
404
|
+
.description("Edita los metadatos del draft (nombre, descripción, categoría, tags, visibilidad). Para editar el cuerpo usa `crm skill push`.")
|
|
405
|
+
.argument("<slug>")
|
|
406
|
+
.option("--name <name>", "nuevo nombre visible")
|
|
407
|
+
.option("--description <text>", "nueva descripción (≤1024 chars)")
|
|
408
|
+
.option("--category <name>", `categoría: ${SKILL_CATEGORIES.join(" | ")}`)
|
|
409
|
+
.option("--kind <kind>", `forma del skill: ${SKILL_KINDS.join(" | ")}`)
|
|
410
|
+
.option("--tag <id...>", "id(s) de tag — reemplaza el set existente (pasa lista completa)")
|
|
411
|
+
.option("--visibility <v>", `visibilidad: ${SKILL_VISIBILITIES.join(" | ")}`)
|
|
412
|
+
.action(async (slug, opts, cmd) => {
|
|
413
|
+
const flags = readFlags(cmd);
|
|
414
|
+
if (opts.category !== undefined &&
|
|
415
|
+
!SKILL_CATEGORIES.includes(opts.category)) {
|
|
416
|
+
process.stderr.write(`error: --category debe ser uno de ${SKILL_CATEGORIES.join(", ")}\n`);
|
|
417
|
+
process.exit(2);
|
|
418
|
+
}
|
|
419
|
+
if (opts.kind !== undefined && !SKILL_KINDS.includes(opts.kind)) {
|
|
420
|
+
process.stderr.write(`error: --kind debe ser uno de ${SKILL_KINDS.join(", ")}\n`);
|
|
421
|
+
process.exit(2);
|
|
422
|
+
}
|
|
423
|
+
if (opts.visibility !== undefined &&
|
|
424
|
+
!SKILL_VISIBILITIES.includes(opts.visibility)) {
|
|
425
|
+
process.stderr.write(`error: --visibility debe ser uno de ${SKILL_VISIBILITIES.join(", ")}\n`);
|
|
426
|
+
process.exit(2);
|
|
427
|
+
}
|
|
428
|
+
await run({
|
|
429
|
+
method: "PATCH",
|
|
430
|
+
path: `/skills/${encodeURIComponent(slug)}`,
|
|
431
|
+
request: {
|
|
432
|
+
body: {
|
|
433
|
+
name: opts.name,
|
|
434
|
+
description: opts.description,
|
|
435
|
+
category: opts.category,
|
|
436
|
+
kind: opts.kind,
|
|
437
|
+
tagIds: opts.tag,
|
|
438
|
+
visibility: opts.visibility,
|
|
439
|
+
},
|
|
440
|
+
idempotencyKey: flags.idempotencyKey,
|
|
441
|
+
},
|
|
442
|
+
output: outputFromFlags(flags),
|
|
443
|
+
profile: flags.profile,
|
|
444
|
+
asAgent: flags.asAgent,
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
// ── archive
|
|
448
|
+
skill
|
|
449
|
+
.command("archive")
|
|
450
|
+
.description("Archiva un skill (oculto de la librería; revisiones siguen accesibles).")
|
|
451
|
+
.argument("<slug>")
|
|
452
|
+
.action(async (slug, _opts, cmd) => {
|
|
453
|
+
const flags = readFlags(cmd);
|
|
454
|
+
await run({
|
|
455
|
+
method: "POST",
|
|
456
|
+
path: `/skills/${encodeURIComponent(slug)}/archive`,
|
|
457
|
+
request: { body: {}, idempotencyKey: flags.idempotencyKey },
|
|
458
|
+
output: outputFromFlags(flags),
|
|
459
|
+
profile: flags.profile,
|
|
460
|
+
asAgent: flags.asAgent,
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
// ── restore
|
|
464
|
+
skill
|
|
465
|
+
.command("restore")
|
|
466
|
+
.description("Restaura un skill archivado (vuelve a published / draft).")
|
|
467
|
+
.argument("<slug>")
|
|
468
|
+
.action(async (slug, _opts, cmd) => {
|
|
469
|
+
const flags = readFlags(cmd);
|
|
470
|
+
await run({
|
|
471
|
+
method: "POST",
|
|
472
|
+
path: `/skills/${encodeURIComponent(slug)}/restore`,
|
|
473
|
+
request: { body: {}, idempotencyKey: flags.idempotencyKey },
|
|
474
|
+
output: outputFromFlags(flags),
|
|
475
|
+
profile: flags.profile,
|
|
476
|
+
asAgent: flags.asAgent,
|
|
477
|
+
});
|
|
478
|
+
});
|
|
479
|
+
// ── pull
|
|
480
|
+
//
|
|
481
|
+
// `--all` is the global pagination flag (registered on program root in
|
|
482
|
+
// registerGlobalFlags). We reuse it here for "all skills" because the
|
|
483
|
+
// overload is intuitive + avoids a parser collision with a subcommand-local
|
|
484
|
+
// option of the same name.
|
|
485
|
+
skill
|
|
486
|
+
.command("pull")
|
|
487
|
+
.description("Descarga uno o varios skills a `.claude/skills/<slug>/SKILL.md`. Usa --all para bajar todos los publicados.")
|
|
488
|
+
.argument("[slug]", "slug del skill (omitir cuando se usa --all)")
|
|
489
|
+
.option("--revision <id>", "revisión específica (default: última publicada)")
|
|
490
|
+
.option("--category <name>", "limita --all a una categoría")
|
|
491
|
+
.option("--tag <id>", "limita --all a un tag")
|
|
492
|
+
.option("--dry-run", "no escribe en disco, solo imprime lo que haría")
|
|
493
|
+
.option("--preserve", "no borra archivos antiguos del skill aunque la nueva revisión los haya quitado")
|
|
494
|
+
.option("--force", "ignora la comprobación de directorio raíz del proyecto y escribe en CWD aunque no parezca un repo")
|
|
495
|
+
.action(async (slug, opts, cmd) => {
|
|
496
|
+
const flags = readFlags(cmd);
|
|
497
|
+
assertOutputFlagsCompatible(outputFromFlags(flags));
|
|
498
|
+
const wantAll = flags.all === true;
|
|
499
|
+
if (wantAll && slug) {
|
|
500
|
+
process.stderr.write("No puedes combinar un slug con --all.\n");
|
|
501
|
+
process.exit(EXIT.USAGE);
|
|
502
|
+
}
|
|
503
|
+
if (!wantAll && !slug) {
|
|
504
|
+
process.stderr.write("Pasa un slug o --all.\n");
|
|
505
|
+
process.exit(EXIT.USAGE);
|
|
506
|
+
}
|
|
507
|
+
const baseDir = process.cwd();
|
|
508
|
+
if (!opts.force && detectProjectRoot(baseDir) === null) {
|
|
509
|
+
process.stderr.write(`El directorio actual no parece la raíz de un proyecto (no se encuentra .git, package.json, convex, .claude...).\n` +
|
|
510
|
+
`Si realmente quieres crear .claude/skills aquí, repite con --force.\n` +
|
|
511
|
+
`CWD: ${baseDir}\n`);
|
|
512
|
+
process.exit(EXIT.USAGE);
|
|
513
|
+
}
|
|
514
|
+
// Resolve the target slug list.
|
|
515
|
+
let targets;
|
|
516
|
+
// slug → skillId, populated lazily — for --all from the list call,
|
|
517
|
+
// for single-slug pulls from a per-slug GET in the loop below.
|
|
518
|
+
const skillIdBySlug = new Map();
|
|
519
|
+
if (wantAll) {
|
|
520
|
+
const list = await getJson(`/skills?${new URLSearchParams({
|
|
521
|
+
status: "published",
|
|
522
|
+
...(opts.category ? { category: opts.category } : {}),
|
|
523
|
+
...(opts.tag ? { tagId: opts.tag } : {}),
|
|
524
|
+
}).toString()}`, flags);
|
|
525
|
+
const published = list.filter((s) => s.status === "published");
|
|
526
|
+
for (const s of published)
|
|
527
|
+
skillIdBySlug.set(s.slug, s.id);
|
|
528
|
+
targets = published.map((s) => s.slug);
|
|
529
|
+
if (targets.length === 0) {
|
|
530
|
+
renderSuccess(envelopeOk({ written: [], skipped: [], message: "No hay skills publicados que coincidan." }, "Sin skills para descargar."), outputFromFlags(flags));
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
else {
|
|
535
|
+
targets = [slug];
|
|
536
|
+
}
|
|
537
|
+
const written = [];
|
|
538
|
+
const skipped = [];
|
|
539
|
+
for (const target of targets) {
|
|
540
|
+
const revQuery = opts.revision ? `?revisionId=${encodeURIComponent(opts.revision)}` : "";
|
|
541
|
+
const content = await getJson(`/skills/${encodeURIComponent(target)}/content${revQuery}`, flags);
|
|
542
|
+
if (!content) {
|
|
543
|
+
skipped.push({ slug: target, reason: "Sin revisión publicada." });
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
const files = [
|
|
547
|
+
{ path: "SKILL.md", content: content.assembled },
|
|
548
|
+
...content.resources.map((r) => ({ path: r.path, content: r.content })),
|
|
549
|
+
];
|
|
550
|
+
if (opts.dryRun) {
|
|
551
|
+
written.push({
|
|
552
|
+
slug: target,
|
|
553
|
+
folder: skillFolderPath(target, baseDir),
|
|
554
|
+
files: files.map((f) => f.path),
|
|
555
|
+
revisionId: content.revisionId,
|
|
556
|
+
});
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
const previousFiles = loadManifest(baseDir).skills[target]?.files;
|
|
560
|
+
const result = writeSkillFiles(skillFolderPath(target, baseDir), target, files, {
|
|
561
|
+
previousManagedPaths: previousFiles,
|
|
562
|
+
preserveAll: opts.preserve === true,
|
|
563
|
+
});
|
|
564
|
+
// The sidecar carries skillId so the folder remains identifiable
|
|
565
|
+
// across slug renames. Reuse the list-call result when available
|
|
566
|
+
// (--all path); fall back to a per-slug GET for single-slug pulls.
|
|
567
|
+
let skillId = skillIdBySlug.get(target) ?? "";
|
|
568
|
+
if (!skillId) {
|
|
569
|
+
const meta = await getJson(`/skills/${encodeURIComponent(target)}`, flags);
|
|
570
|
+
skillId = meta?.id ?? "";
|
|
571
|
+
if (skillId)
|
|
572
|
+
skillIdBySlug.set(target, skillId);
|
|
573
|
+
}
|
|
574
|
+
// Write sidecar so future `crm skill push` can detect drift +
|
|
575
|
+
// local edits. Hash covers SKILL.md + every resource file.
|
|
576
|
+
writeSidecar(target, {
|
|
577
|
+
skillId,
|
|
578
|
+
revisionId: content.revisionId,
|
|
579
|
+
contentHash: computeContentHash(files),
|
|
580
|
+
}, baseDir);
|
|
581
|
+
written.push({
|
|
582
|
+
slug: target,
|
|
583
|
+
folder: result.folder,
|
|
584
|
+
files: result.files,
|
|
585
|
+
revisionId: content.revisionId,
|
|
586
|
+
});
|
|
587
|
+
// Update manifest after each successful write so a crash mid-loop
|
|
588
|
+
// leaves a consistent record of what we did manage to pull. The
|
|
589
|
+
// manifest stays gitignored (per-dev state); the sidecar above is
|
|
590
|
+
// the committed drift basis. Sidecar is NOT listed in `files` so
|
|
591
|
+
// a later pull's orphan-pruning never deletes it.
|
|
592
|
+
let manifest = loadManifest(baseDir);
|
|
593
|
+
manifest = upsertEntry(manifest, target, {
|
|
594
|
+
revisionId: content.revisionId,
|
|
595
|
+
pulledAt: Date.now(),
|
|
596
|
+
files: result.files,
|
|
597
|
+
});
|
|
598
|
+
saveManifest(manifest, baseDir);
|
|
599
|
+
}
|
|
600
|
+
// Auto-prune folders whose sidecar references a skill that's no longer
|
|
601
|
+
// published (archived or deleted server-side). Only runs when the
|
|
602
|
+
// pull is unfiltered — with --category/--tag the returned list is a
|
|
603
|
+
// subset, so we cannot tell archived from "filtered out".
|
|
604
|
+
const removed = [];
|
|
605
|
+
if (wantAll && !opts.dryRun && !opts.category && !opts.tag) {
|
|
606
|
+
const publishedIds = new Set(skillIdBySlug.values());
|
|
607
|
+
for (const orphan of findOrphanedSkillFolders(baseDir, publishedIds)) {
|
|
608
|
+
removeSkillFolder(skillFolderPath(orphan.slug, baseDir), orphan.slug);
|
|
609
|
+
saveManifest(removeEntry(loadManifest(baseDir), orphan.slug), baseDir);
|
|
610
|
+
removed.push({ slug: orphan.slug, reason: "archived_or_deleted" });
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const removedNote = removed.length === 0 ? "" : ` ${removed.length} archivado(s) eliminado(s) del mirror.`;
|
|
614
|
+
renderSuccess(envelopeOk({ written, skipped, removed }, opts.dryRun
|
|
615
|
+
? `Dry-run: ${written.length} skill(s) listos para escribir.`
|
|
616
|
+
: `Descargados ${written.length} skill(s) a ${skillsDirPath(baseDir)}.${removedNote} Claude Code los cargará en el próximo prompt.`), outputFromFlags(flags));
|
|
617
|
+
});
|
|
618
|
+
// ── update
|
|
619
|
+
skill
|
|
620
|
+
.command("update")
|
|
621
|
+
.description("Refresca todos los skills instalados. Compara el manifest local con la revisión actual y descarga solo lo que cambió.")
|
|
622
|
+
.option("--dry-run", "no escribe en disco, solo informa lo desactualizado")
|
|
623
|
+
.option("--preserve", "no borra archivos antiguos del skill aunque la nueva revisión los haya quitado")
|
|
624
|
+
.option("--prune-archived", "elimina del manifest + disco los skills que el servidor marcó como archivados")
|
|
625
|
+
.action(async (opts, cmd) => {
|
|
626
|
+
const flags = readFlags(cmd);
|
|
627
|
+
assertOutputFlagsCompatible(outputFromFlags(flags));
|
|
628
|
+
const baseDir = process.cwd();
|
|
629
|
+
const manifest = loadManifest(baseDir);
|
|
630
|
+
const installed = Object.values(manifest.skills);
|
|
631
|
+
if (installed.length === 0) {
|
|
632
|
+
renderSuccess(envelopeOk({ updated: [], upToDate: [], missing: [], archived: [] }, "No hay skills instalados. Usa `crm skill pull --all` para empezar."), outputFromFlags(flags));
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const updated = [];
|
|
636
|
+
const upToDate = [];
|
|
637
|
+
const missing = [];
|
|
638
|
+
const archived = [];
|
|
639
|
+
const bundled = [];
|
|
640
|
+
for (const entry of installed) {
|
|
641
|
+
// Bundled skills are versioned by CLI release, not by Convex revisions.
|
|
642
|
+
// `crm skill init` refreshes them from whatever the installed CLI ships
|
|
643
|
+
// with — never re-fetch from the API for these.
|
|
644
|
+
if (entry.source === "bundle") {
|
|
645
|
+
bundled.push(entry.slug);
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
const skill = await getJson(`/skills/${encodeURIComponent(entry.slug)}`, flags);
|
|
649
|
+
if (!skill) {
|
|
650
|
+
missing.push(entry.slug);
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
if (skill.status === "archived") {
|
|
654
|
+
// Server still has it but won't ship it on `pull --all`. Either
|
|
655
|
+
// surface for the user, or auto-remove if they asked us to.
|
|
656
|
+
if (opts.pruneArchived === true && opts.dryRun !== true) {
|
|
657
|
+
removeSkillFolder(skillFolderPath(entry.slug, baseDir), entry.slug);
|
|
658
|
+
saveManifest(removeEntry(loadManifest(baseDir), entry.slug), baseDir);
|
|
659
|
+
archived.push({ slug: entry.slug, pruned: true });
|
|
660
|
+
}
|
|
661
|
+
else {
|
|
662
|
+
archived.push({ slug: entry.slug, pruned: false });
|
|
663
|
+
}
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
if (!skill.currentRevisionId) {
|
|
667
|
+
missing.push(entry.slug);
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
if (skill.currentRevisionId === entry.revisionId) {
|
|
671
|
+
upToDate.push(entry.slug);
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
if (opts.dryRun) {
|
|
675
|
+
updated.push({
|
|
676
|
+
slug: entry.slug,
|
|
677
|
+
fromRevisionId: entry.revisionId,
|
|
678
|
+
toRevisionId: skill.currentRevisionId,
|
|
679
|
+
});
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
const content = await getJson(`/skills/${encodeURIComponent(entry.slug)}/content`, flags);
|
|
683
|
+
const files = [
|
|
684
|
+
{ path: "SKILL.md", content: content.assembled },
|
|
685
|
+
...content.resources.map((r) => ({ path: r.path, content: r.content })),
|
|
686
|
+
];
|
|
687
|
+
const result = writeSkillFiles(skillFolderPath(entry.slug, baseDir), entry.slug, files, {
|
|
688
|
+
previousManagedPaths: entry.files,
|
|
689
|
+
preserveAll: opts.preserve === true,
|
|
690
|
+
});
|
|
691
|
+
const next = upsertEntry(loadManifest(baseDir), entry.slug, {
|
|
692
|
+
revisionId: content.revisionId,
|
|
693
|
+
pulledAt: Date.now(),
|
|
694
|
+
files: result.files,
|
|
695
|
+
});
|
|
696
|
+
saveManifest(next, baseDir);
|
|
697
|
+
updated.push({
|
|
698
|
+
slug: entry.slug,
|
|
699
|
+
fromRevisionId: entry.revisionId,
|
|
700
|
+
toRevisionId: content.revisionId,
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
const archivedNote = archived.length === 0
|
|
704
|
+
? ""
|
|
705
|
+
: opts.pruneArchived
|
|
706
|
+
? ` ${archived.length} archivado(s) eliminado(s).`
|
|
707
|
+
: ` ${archived.length} archivado(s) en el servidor — usa --prune-archived o \`crm skill remove\` para limpiarlos.`;
|
|
708
|
+
const bundledNote = bundled.length === 0
|
|
709
|
+
? ""
|
|
710
|
+
: ` ${bundled.length} bundled (refresca con \`crm skill init\`).`;
|
|
711
|
+
renderSuccess(envelopeOk({ updated, upToDate, missing, archived, bundled }, opts.dryRun
|
|
712
|
+
? `${updated.length} skill(s) desactualizados, ${upToDate.length} al día.${archivedNote}${bundledNote}`
|
|
713
|
+
: `${updated.length} skill(s) actualizados, ${upToDate.length} al día.${archivedNote}${bundledNote} Claude Code los cargará en el próximo prompt.`), outputFromFlags(flags));
|
|
714
|
+
});
|
|
715
|
+
// ── remove
|
|
716
|
+
skill
|
|
717
|
+
.command("remove")
|
|
718
|
+
.description("Elimina un skill instalado: borra `.claude/skills/<slug>/` y la entrada del manifest.")
|
|
719
|
+
.argument("<slug>")
|
|
720
|
+
.option("--purge", "borra el directorio aunque no exista una entrada en el manifest (útil tras desinstalaciones manuales o slugs huérfanos)")
|
|
721
|
+
.action(async (slug, opts, cmd) => {
|
|
722
|
+
const flags = readFlags(cmd);
|
|
723
|
+
assertOutputFlagsCompatible(outputFromFlags(flags));
|
|
724
|
+
const baseDir = process.cwd();
|
|
725
|
+
const manifest = loadManifest(baseDir);
|
|
726
|
+
const wasInManifest = Boolean(manifest.skills[slug]);
|
|
727
|
+
if (!wasInManifest && opts.purge !== true) {
|
|
728
|
+
renderError({
|
|
729
|
+
ok: false,
|
|
730
|
+
error: {
|
|
731
|
+
code: "NOT_FOUND",
|
|
732
|
+
message: `\`${slug}\` no figura en el manifest. Usa --purge para forzar el borrado del directorio.`,
|
|
733
|
+
retryable: false,
|
|
734
|
+
},
|
|
735
|
+
meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
|
|
736
|
+
});
|
|
737
|
+
process.exit(exitCodeForErrorCode("NOT_FOUND"));
|
|
738
|
+
}
|
|
739
|
+
const folder = skillFolderPath(slug, baseDir);
|
|
740
|
+
const removed = removeSkillFolder(folder, slug);
|
|
741
|
+
if (wasInManifest) {
|
|
742
|
+
saveManifest(removeEntry(manifest, slug), baseDir);
|
|
743
|
+
}
|
|
744
|
+
renderSuccess(envelopeOk({
|
|
745
|
+
slug,
|
|
746
|
+
folderRemoved: removed,
|
|
747
|
+
manifestEntryRemoved: wasInManifest,
|
|
748
|
+
folder,
|
|
749
|
+
}, removed
|
|
750
|
+
? `Eliminado \`${slug}\` (${folder}).`
|
|
751
|
+
: `No había nada que borrar en ${folder}.`), outputFromFlags(flags));
|
|
752
|
+
});
|
|
753
|
+
// ── diff
|
|
754
|
+
skill
|
|
755
|
+
.command("diff")
|
|
756
|
+
.description("Compara la copia local con la revisión actual en el servidor")
|
|
757
|
+
.argument("<slug>")
|
|
758
|
+
.action(async (slug, _opts, cmd) => {
|
|
759
|
+
const flags = readFlags(cmd);
|
|
760
|
+
const baseDir = process.cwd();
|
|
761
|
+
const manifest = loadManifest(baseDir);
|
|
762
|
+
const local = manifest.skills[slug];
|
|
763
|
+
const skill = await getJson(`/skills/${encodeURIComponent(slug)}`, flags);
|
|
764
|
+
if (!skill) {
|
|
765
|
+
renderError({
|
|
766
|
+
ok: false,
|
|
767
|
+
error: {
|
|
768
|
+
code: "NOT_FOUND",
|
|
769
|
+
message: `Skill \`${slug}\` no existe en el workspace.`,
|
|
770
|
+
retryable: false,
|
|
771
|
+
},
|
|
772
|
+
meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
|
|
773
|
+
});
|
|
774
|
+
process.exit(exitCodeForErrorCode("NOT_FOUND"));
|
|
775
|
+
}
|
|
776
|
+
const remoteRevisionId = skill.currentRevisionId;
|
|
777
|
+
const localRevisionId = local?.revisionId ?? null;
|
|
778
|
+
const status = !local
|
|
779
|
+
? "not_installed"
|
|
780
|
+
: skill.status === "archived"
|
|
781
|
+
? "archived_remote"
|
|
782
|
+
: remoteRevisionId === localRevisionId
|
|
783
|
+
? "up_to_date"
|
|
784
|
+
: "outdated";
|
|
785
|
+
renderSuccess(envelopeOk({
|
|
786
|
+
slug,
|
|
787
|
+
status,
|
|
788
|
+
localRevisionId,
|
|
789
|
+
remoteRevisionId,
|
|
790
|
+
remoteStatus: skill.status,
|
|
791
|
+
pulledAt: local?.pulledAt ?? null,
|
|
792
|
+
}, `\`${slug}\`: ${status}`), outputFromFlags(flags));
|
|
793
|
+
});
|
|
794
|
+
// ── push
|
|
795
|
+
//
|
|
796
|
+
// Sends local edits to `.claude/skills/<slug>/` back to Convex. By default
|
|
797
|
+
// creates a draft revision (review in /dashboard/skills/<slug>); pass
|
|
798
|
+
// --publish to chain the publish step in one call.
|
|
799
|
+
//
|
|
800
|
+
// Two safety checks gate the write:
|
|
801
|
+
// - drift: sidecar.revisionId vs server's currentRevisionId. Rejected
|
|
802
|
+
// unless --force.
|
|
803
|
+
// - draft-pending: server's draftBody/draftFrontmatterRaw differs from the
|
|
804
|
+
// last published revision. Rejected unless --force-overwrite-draft.
|
|
805
|
+
skill
|
|
806
|
+
.command("push")
|
|
807
|
+
.description("Envía las ediciones locales de `.claude/skills/<slug>/` al servidor como un draft. Usa --publish para publicar en la misma llamada.")
|
|
808
|
+
.argument("<slug>")
|
|
809
|
+
.requiredOption("--note <text>", "resumen del cambio (≤200 chars; obligatorio para --publish)")
|
|
810
|
+
.option("--publish", "publica el draft inmediatamente (requiere rol owner/admin en la API key)")
|
|
811
|
+
.option("--force", "ignora la comprobación de drift (sidecar.revisionId ≠ servidor)")
|
|
812
|
+
.option("--force-overwrite-draft", "sobrescribe un draft pendiente en el servidor que difiere del publicado")
|
|
813
|
+
.option("--dry-run", "no envía nada, solo informa qué haría")
|
|
814
|
+
.action(async (slug, opts, cmd) => {
|
|
815
|
+
const flags = readFlags(cmd);
|
|
816
|
+
assertOutputFlagsCompatible(outputFromFlags(flags));
|
|
817
|
+
const baseDir = process.cwd();
|
|
818
|
+
const sidecar = readSidecar(slug, baseDir);
|
|
819
|
+
if (!sidecar) {
|
|
820
|
+
renderError({
|
|
821
|
+
ok: false,
|
|
822
|
+
error: {
|
|
823
|
+
code: "NOT_FOUND",
|
|
824
|
+
message: `\`${slug}\` no está en el mirror local. Ejecuta \`crm skill pull ${slug}\` primero.`,
|
|
825
|
+
retryable: false,
|
|
826
|
+
},
|
|
827
|
+
meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
|
|
828
|
+
});
|
|
829
|
+
process.exit(exitCodeForErrorCode("NOT_FOUND"));
|
|
830
|
+
}
|
|
831
|
+
if (opts.note.length > 200) {
|
|
832
|
+
process.stderr.write("--note debe tener 200 caracteres o menos.\n");
|
|
833
|
+
process.exit(EXIT.USAGE);
|
|
834
|
+
}
|
|
835
|
+
// Read local files + compute hash for the no-op short-circuit.
|
|
836
|
+
const skillFolder = skillFolderPath(slug, baseDir);
|
|
837
|
+
const { skillMd, resources } = readLocalSkillFiles(skillFolder);
|
|
838
|
+
const allFiles = [
|
|
839
|
+
{ path: "SKILL.md", content: skillMd },
|
|
840
|
+
...resources,
|
|
841
|
+
];
|
|
842
|
+
const localHash = computeContentHash(allFiles);
|
|
843
|
+
// Idempotency: nothing changed locally and we're not asking for an
|
|
844
|
+
// explicit publish → bail. (--publish on an unchanged skill still
|
|
845
|
+
// does something useful: re-publish the existing draft if any.)
|
|
846
|
+
if (localHash === sidecar.contentHash && !opts.publish) {
|
|
847
|
+
renderSuccess(envelopeOk({ slug, action: "noop", revisionId: sidecar.revisionId }, "Sin cambios locales — nada que enviar."), outputFromFlags(flags));
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
// Fetch current server state for drift + pending-draft checks.
|
|
851
|
+
const remote = await getJson(`/skills/${encodeURIComponent(slug)}`, flags);
|
|
852
|
+
if (!remote) {
|
|
853
|
+
renderError({
|
|
854
|
+
ok: false,
|
|
855
|
+
error: {
|
|
856
|
+
code: "NOT_FOUND",
|
|
857
|
+
message: `Skill \`${slug}\` ya no existe en el servidor. Borra el folder local o restaura el skill en /dashboard/skills.`,
|
|
858
|
+
retryable: false,
|
|
859
|
+
},
|
|
860
|
+
meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
|
|
861
|
+
});
|
|
862
|
+
process.exit(exitCodeForErrorCode("NOT_FOUND"));
|
|
863
|
+
}
|
|
864
|
+
// Drift: server moved past the revision the sidecar was based on.
|
|
865
|
+
const serverRevisionId = remote.currentRevisionId ?? null;
|
|
866
|
+
if (serverRevisionId &&
|
|
867
|
+
serverRevisionId !== sidecar.revisionId &&
|
|
868
|
+
!opts.force) {
|
|
869
|
+
renderError({
|
|
870
|
+
ok: false,
|
|
871
|
+
error: {
|
|
872
|
+
code: "CONFLICT",
|
|
873
|
+
message: `Drift detectado: el servidor está en la revisión ${serverRevisionId} ` +
|
|
874
|
+
`pero tu mirror está en ${sidecar.revisionId}. ` +
|
|
875
|
+
`Ejecuta \`crm skill pull ${slug}\` y reaplica tus cambios, o repite con --force.`,
|
|
876
|
+
retryable: false,
|
|
877
|
+
},
|
|
878
|
+
meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
|
|
879
|
+
});
|
|
880
|
+
process.exit(exitCodeForErrorCode("CONFLICT"));
|
|
881
|
+
}
|
|
882
|
+
// Pending draft: server's draft body differs from what we'd produce
|
|
883
|
+
// locally if we hadn't edited anything. Approximation: compare the
|
|
884
|
+
// server's draft against the on-disk SKILL.md split. If they differ
|
|
885
|
+
// AND the on-disk hash matches the sidecar (i.e. we have no local
|
|
886
|
+
// edits), the only explanation is a draft submitted by someone else.
|
|
887
|
+
// If we DO have local edits, the comparison is ambiguous — be safe
|
|
888
|
+
// and require --force-overwrite-draft only when it would clobber a
|
|
889
|
+
// draft that was clearly authored elsewhere.
|
|
890
|
+
const { frontmatterRaw, body } = splitSkillMd(skillMd);
|
|
891
|
+
const remoteHasPendingDraft = remote.draftBody !== body || remote.draftFrontmatterRaw !== frontmatterRaw;
|
|
892
|
+
const localUnchanged = localHash === sidecar.contentHash;
|
|
893
|
+
if (remoteHasPendingDraft &&
|
|
894
|
+
!localUnchanged &&
|
|
895
|
+
!opts.forceOverwriteDraft) {
|
|
896
|
+
renderError({
|
|
897
|
+
ok: false,
|
|
898
|
+
error: {
|
|
899
|
+
code: "CONFLICT",
|
|
900
|
+
message: "Hay un draft pendiente en el servidor que difiere del publicado. " +
|
|
901
|
+
"Revísalo en /dashboard/skills/" +
|
|
902
|
+
slug +
|
|
903
|
+
" o repite con --force-overwrite-draft para sobrescribirlo.",
|
|
904
|
+
retryable: false,
|
|
905
|
+
},
|
|
906
|
+
meta: { requestId: randomUUID(), timestamp: new Date().toISOString() },
|
|
907
|
+
});
|
|
908
|
+
process.exit(exitCodeForErrorCode("CONFLICT"));
|
|
909
|
+
}
|
|
910
|
+
if (opts.dryRun) {
|
|
911
|
+
renderSuccess(envelopeOk({
|
|
912
|
+
slug,
|
|
913
|
+
action: opts.publish ? "would_publish" : "would_draft",
|
|
914
|
+
bodyLength: body.length,
|
|
915
|
+
resourceCount: resources.length,
|
|
916
|
+
serverRevisionId,
|
|
917
|
+
}, opts.publish
|
|
918
|
+
? `Dry-run: publicaría \`${slug}\` con ${resources.length} recurso(s).`
|
|
919
|
+
: `Dry-run: actualizaría el draft de \`${slug}\`.`), outputFromFlags(flags));
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
// Update the draft (body + frontmatter only — resources flow through
|
|
923
|
+
// publish per the schema).
|
|
924
|
+
const creds = resolveCredentials(flags.profile);
|
|
925
|
+
const client = new HttpClient({ apiKey: creds.apiKey, apiBaseUrl: creds.apiBaseUrl });
|
|
926
|
+
try {
|
|
927
|
+
const patchRes = await client.request("PATCH", `/skills/${encodeURIComponent(slug)}`, { body: { draftBody: body, draftFrontmatterRaw: frontmatterRaw } });
|
|
928
|
+
if (patchRes.envelope.ok !== true) {
|
|
929
|
+
renderError(patchRes.envelope);
|
|
930
|
+
process.exit(exitCodeForErrorCode(patchRes.envelope.error.code));
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
catch (err) {
|
|
934
|
+
if (err instanceof HttpError) {
|
|
935
|
+
renderError(err.envelope);
|
|
936
|
+
if (err.envelope.ok === false) {
|
|
937
|
+
process.exit(exitCodeForErrorCode(err.envelope.error.code));
|
|
938
|
+
}
|
|
939
|
+
process.exit(EXIT.INTERNAL);
|
|
940
|
+
}
|
|
941
|
+
if (err instanceof NetworkError) {
|
|
942
|
+
process.stderr.write(`[RED] ${err.message}\n`);
|
|
943
|
+
process.exit(EXIT.NETWORK);
|
|
944
|
+
}
|
|
945
|
+
throw err;
|
|
946
|
+
}
|
|
947
|
+
if (!opts.publish) {
|
|
948
|
+
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));
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
let publishedRevisionId;
|
|
952
|
+
try {
|
|
953
|
+
const publishRes = await client.request("POST", `/skills/${encodeURIComponent(slug)}/publish`, {
|
|
954
|
+
body: {
|
|
955
|
+
changeSummary: opts.note,
|
|
956
|
+
resources: resources.map((r) => ({
|
|
957
|
+
path: r.path,
|
|
958
|
+
content: r.content,
|
|
959
|
+
contentType: "text/plain",
|
|
960
|
+
})),
|
|
961
|
+
},
|
|
962
|
+
});
|
|
963
|
+
if (publishRes.envelope.ok !== true) {
|
|
964
|
+
renderError(publishRes.envelope);
|
|
965
|
+
process.exit(exitCodeForErrorCode(publishRes.envelope.error.code));
|
|
966
|
+
}
|
|
967
|
+
// Success envelope guarantees `data`; TS doesn't follow process.exit
|
|
968
|
+
// through the early-return branch above.
|
|
969
|
+
publishedRevisionId = publishRes.envelope.data.revisionId;
|
|
970
|
+
}
|
|
971
|
+
catch (err) {
|
|
972
|
+
if (err instanceof HttpError) {
|
|
973
|
+
renderError(err.envelope);
|
|
974
|
+
if (err.envelope.ok === false) {
|
|
975
|
+
process.exit(exitCodeForErrorCode(err.envelope.error.code));
|
|
976
|
+
}
|
|
977
|
+
process.exit(EXIT.INTERNAL);
|
|
978
|
+
}
|
|
979
|
+
if (err instanceof NetworkError) {
|
|
980
|
+
process.stderr.write(`[RED] ${err.message}\n`);
|
|
981
|
+
process.exit(EXIT.NETWORK);
|
|
982
|
+
}
|
|
983
|
+
throw err;
|
|
984
|
+
}
|
|
985
|
+
// Refresh sidecar so next push starts from the new published revision.
|
|
986
|
+
writeSidecar(slug, {
|
|
987
|
+
skillId: sidecar.skillId,
|
|
988
|
+
revisionId: publishedRevisionId,
|
|
989
|
+
contentHash: localHash,
|
|
990
|
+
}, baseDir);
|
|
991
|
+
// Refresh manifest's revisionId for `crm skill update`/`diff`.
|
|
992
|
+
const manifestNow = loadManifest(baseDir);
|
|
993
|
+
const existingEntry = manifestNow.skills[slug];
|
|
994
|
+
if (existingEntry) {
|
|
995
|
+
saveManifest(upsertEntry(manifestNow, slug, {
|
|
996
|
+
revisionId: publishedRevisionId,
|
|
997
|
+
pulledAt: existingEntry.pulledAt,
|
|
998
|
+
files: existingEntry.files,
|
|
999
|
+
source: existingEntry.source,
|
|
1000
|
+
}), baseDir);
|
|
1001
|
+
}
|
|
1002
|
+
renderSuccess(envelopeOk({ slug, action: "published", revisionId: publishedRevisionId }, `Publicado \`${slug}\` como revisión ${publishedRevisionId}.`), outputFromFlags(flags));
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
//# sourceMappingURL=skill.js.map
|