@rafter-security/cli 0.11.6 → 0.12.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 (52) hide show
  1. package/dist/commands/agent/auto-update.js +171 -0
  2. package/dist/commands/agent/components.js +50 -176
  3. package/dist/commands/agent/enable.js +11 -1
  4. package/dist/commands/agent/index.js +2 -0
  5. package/dist/commands/agent/init.js +654 -764
  6. package/dist/commands/agent/install-files.js +689 -0
  7. package/dist/commands/agent/instruction-block.js +82 -40
  8. package/dist/commands/agent/scan.js +70 -21
  9. package/dist/commands/agent/status.js +11 -0
  10. package/dist/commands/agent/update.js +179 -0
  11. package/dist/commands/agent/verify.js +11 -0
  12. package/dist/commands/backend/get.js +5 -10
  13. package/dist/commands/backend/run.js +10 -20
  14. package/dist/commands/backend/scan-status.js +16 -3
  15. package/dist/commands/backend/usage.js +3 -6
  16. package/dist/commands/brief.js +6 -12
  17. package/dist/commands/counters.js +146 -0
  18. package/dist/commands/gates.js +36 -0
  19. package/dist/commands/hook/pretool.js +22 -9
  20. package/dist/commands/mcp/server.js +1 -1
  21. package/dist/commands/skill/registry.js +48 -0
  22. package/dist/core/risk-rules.js +240 -34
  23. package/dist/core/usage-counters.js +439 -0
  24. package/dist/index.js +36 -0
  25. package/dist/scanners/gate-scanner.js +721 -0
  26. package/dist/scanners/regex-scanner.js +26 -25
  27. package/dist/utils/skill-manager.js +8 -338
  28. package/package.json +1 -1
  29. package/resources/continue-rules/rafter-code-review.md +6 -6
  30. package/resources/continue-rules/rafter-secure-design.md +3 -4
  31. package/resources/continue-rules/rafter-skill-review.md +4 -4
  32. package/resources/continue-rules/rafter.md +2 -2
  33. package/resources/cursor-rules/rafter-code-review.mdc +6 -6
  34. package/resources/cursor-rules/rafter-secure-design.mdc +3 -4
  35. package/resources/cursor-rules/rafter-skill-review.mdc +4 -4
  36. package/resources/cursor-rules/rafter.mdc +2 -2
  37. package/resources/rafter-security-skill.md +1 -1
  38. package/resources/shipped-hashes.json +332 -0
  39. package/resources/skills/rafter/SKILL.md +7 -7
  40. package/resources/skills/rafter/docs/cli-reference.md +37 -10
  41. package/resources/skills/rafter/docs/finding-triage.md +1 -1
  42. package/resources/skills/rafter/docs/guardrails.md +2 -2
  43. package/resources/skills/rafter/docs/shift-left.md +4 -4
  44. package/resources/skills/rafter-code-review/SKILL.md +43 -14
  45. package/resources/skills/rafter-code-review/docs/llm.md +2 -2
  46. package/resources/skills/rafter-code-review/docs/security-gates.md +53 -0
  47. package/resources/skills/rafter-secure-design/SKILL.md +1 -0
  48. package/resources/skills/rafter-skill-review/SKILL.md +1 -0
  49. package/resources/windsurf-rules/rafter-code-review.md +6 -6
  50. package/resources/windsurf-rules/rafter-secure-design.md +3 -4
  51. package/resources/windsurf-rules/rafter-skill-review.md +4 -4
  52. package/resources/windsurf-rules/rafter.md +2 -2
@@ -0,0 +1,689 @@
1
+ /**
2
+ * Whole-file artifacts that `rafter agent init` installs (skill files and their
3
+ * docs/, per-skill rule files, sub-agent files, the OpenClaw skill), and the
4
+ * policy for writing them over whatever is already on disk.
5
+ *
6
+ * A re-run used to overwrite these silently, so a user's hand edit vanished
7
+ * behind the same "Installed" line as a fresh install. Now init overwrites a
8
+ * file only when it can prove the file still holds rafter's own content:
9
+ *
10
+ * - the install manifest, <root>/.rafter/installed.json, records the sha256
11
+ * of every file init wrote; or
12
+ * - resources/shipped-hashes.json lists the sha256 of every bundled resource
13
+ * in every published release (regenerate with scripts/gen-shipped-hashes.py),
14
+ * which covers installs made before the manifest existed.
15
+ *
16
+ * Anything else is treated as the user's and kept; the new version lands
17
+ * beside it as <file>.rafter-new. Marker-block files (CLAUDE.md, AGENTS.md, ...)
18
+ * and merged JSON/YAML configs are not whole-file artifacts and do not pass
19
+ * through here. Mirrors python/rafter_cli/commands/install_files.py.
20
+ */
21
+ import crypto from "crypto";
22
+ import fs from "fs";
23
+ import os from "os";
24
+ import path from "path";
25
+ import { createRequire } from "module";
26
+ import { fileURLToPath } from "url";
27
+ import { fmt } from "../../utils/formatter.js";
28
+ import { KNOWN_SKILL_NAMES, RETIRED_SKILL_NAMES, isRafterAuthoredSkillDir, removeRetiredSkills } from "../skill/registry.js";
29
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
30
+ /**
31
+ * What init does with an installed file the user has modified (or that it
32
+ * cannot prove it wrote). "keep" leaves the file alone and writes the new
33
+ * version to <file>.rafter-new; "replace-with-backup" saves the old file as
34
+ * <file>.bak and installs the new one, which is what --force does. Switching
35
+ * the default is a one-line change here.
36
+ */
37
+ export const MODIFIED_FILE_POLICY = "keep";
38
+ export const MANIFEST_SCHEMA = 1;
39
+ export const NEW_VERSION_SUFFIX = ".rafter-new";
40
+ export const BACKUP_SUFFIX = ".bak";
41
+ export function sha256(data) {
42
+ return crypto.createHash("sha256").update(data).digest("hex");
43
+ }
44
+ export function resourcesDir() {
45
+ // src/commands/agent -> ../../../resources (dist/ has the same depth).
46
+ return path.resolve(__dirname, "..", "..", "..", "resources");
47
+ }
48
+ export function cliVersion() {
49
+ try {
50
+ const require = createRequire(import.meta.url);
51
+ return require("../../../package.json").version;
52
+ }
53
+ catch {
54
+ return "unknown";
55
+ }
56
+ }
57
+ let shippedCache = null;
58
+ /** sha256 sets per resource key, from resources/shipped-hashes.json. Missing or bad file → empty (fail safe: files are kept). */
59
+ export function shippedHashes() {
60
+ if (shippedCache)
61
+ return shippedCache;
62
+ const table = new Map();
63
+ try {
64
+ const doc = JSON.parse(fs.readFileSync(path.join(resourcesDir(), "shipped-hashes.json"), "utf-8"));
65
+ for (const [key, shas] of Object.entries(doc?.files ?? {})) {
66
+ if (Array.isArray(shas))
67
+ table.set(key, new Set(shas));
68
+ }
69
+ }
70
+ catch {
71
+ /* fail safe */
72
+ }
73
+ shippedCache = table;
74
+ return table;
75
+ }
76
+ /** True when `p` itself is a symbolic link, dangling or not. */
77
+ export function isSymlink(p) {
78
+ try {
79
+ return fs.lstatSync(p).isSymbolicLink();
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ /**
86
+ * Write `p` without following a symlink at `p`: a temp file in the same
87
+ * directory, renamed over it. rename replaces a link instead of writing
88
+ * through it, so a link a repo planted at one of rafter's files cannot aim
89
+ * the write at ~/.bashrc; the write is atomic too.
90
+ */
91
+ function writeNoFollow(p, content) {
92
+ const tmp = path.join(path.dirname(p), `.${path.basename(p)}.${crypto.randomBytes(6).toString("hex")}.tmp`);
93
+ fs.writeFileSync(tmp, content, { flag: "wx" });
94
+ try {
95
+ fs.renameSync(tmp, p);
96
+ }
97
+ catch (e) {
98
+ fs.rmSync(tmp, { force: true });
99
+ throw e;
100
+ }
101
+ }
102
+ export function manifestPath(root) {
103
+ return path.join(root, ".rafter", "installed.json");
104
+ }
105
+ /** Forward-slash path of `dest` relative to `root` (the manifest key). */
106
+ export function manifestKey(root, dest) {
107
+ const rel = path.relative(root, dest);
108
+ const key = rel.startsWith("..") || path.isAbsolute(rel) ? path.resolve(dest) : rel;
109
+ return key.split(path.sep).join("/");
110
+ }
111
+ /**
112
+ * One init run's view of the install root: the manifest (loaded once, so a
113
+ * corrupt file warns once), the --force / --dry-run switches, and every
114
+ * outcome so far. In a dry run nothing is written; `virtual` holds what the
115
+ * run would have written so a path planned twice (Codex and Gemini share
116
+ * .agents/skills) is predicted the way the real run will see it.
117
+ */
118
+ export class InstallSession {
119
+ /**
120
+ * keepManifestVersion: save() keeps the manifest's cliVersion instead of
121
+ * stamping this CLI's. The hook's auto-update sets it: it refreshes skill and
122
+ * rule files only, so the install as a whole (hooks, MCP, instruction blocks)
123
+ * is still the old version until `rafter agent update` runs (null when the
124
+ * manifest had none).
125
+ */
126
+ constructor(opts) {
127
+ this.outcomes = [];
128
+ this.manifestCache = null;
129
+ /** cliVersion the manifest on disk names, kept on save when keepManifestVersion is set. */
130
+ this.loadedVersion = null;
131
+ this.dirty = false;
132
+ this.virtual = new Map();
133
+ this.root = opts.root;
134
+ this.contained = path.resolve(opts.root) !== path.resolve(os.homedir());
135
+ this.keepManifestVersion = !!opts.keepManifestVersion;
136
+ this.out = opts.out;
137
+ this.force = !!opts.force;
138
+ this.dryRun = !!opts.dryRun;
139
+ this.version = opts.version ?? cliVersion();
140
+ }
141
+ get manifest() {
142
+ if (this.manifestCache)
143
+ return this.manifestCache;
144
+ const empty = { schema: MANIFEST_SCHEMA, cliVersion: this.version, files: {} };
145
+ const p = manifestPath(this.root);
146
+ if (fs.existsSync(p)) {
147
+ try {
148
+ const doc = JSON.parse(fs.readFileSync(p, "utf-8"));
149
+ if (!doc || typeof doc !== "object" || typeof doc.files !== "object" || doc.files === null || Array.isArray(doc.files)) {
150
+ throw new Error("no files map");
151
+ }
152
+ empty.files = doc.files;
153
+ if (typeof doc.cliVersion === "string")
154
+ this.loadedVersion = doc.cliVersion;
155
+ }
156
+ catch (e) {
157
+ this.out.warn(fmt.warning(`Ignoring unreadable install manifest ${p} (${e.message}); ` +
158
+ `installed files are checked against shipped versions instead.`));
159
+ }
160
+ }
161
+ this.manifestCache = empty;
162
+ return empty;
163
+ }
164
+ /** True when `data` at `dest` is provably content rafter wrote. */
165
+ owns(dest, resourceKey, data) {
166
+ const sha = sha256(data);
167
+ const entry = this.manifest.files[manifestKey(this.root, dest)];
168
+ if (entry && entry.sha256 === sha)
169
+ return true;
170
+ return shippedHashes().get(resourceKey)?.has(sha) ?? false;
171
+ }
172
+ read(dest) {
173
+ const v = this.virtual.get(dest);
174
+ if (v)
175
+ return v;
176
+ try {
177
+ return fs.readFileSync(dest);
178
+ }
179
+ catch {
180
+ return null;
181
+ }
182
+ }
183
+ /** The outcome writing `a` would have, without writing anything. */
184
+ classify(a) {
185
+ const current = this.read(a.dest);
186
+ // A symlink is never written through: what sits at its target is not
187
+ // rafter's to update, and a dangling one is not a free path to create.
188
+ const link = !this.virtual.has(a.dest) && isSymlink(a.dest);
189
+ if (current === null && !link)
190
+ return "added";
191
+ if (current?.equals(a.content))
192
+ return "unchanged";
193
+ if (current !== null && !link && this.owns(a.dest, a.resourceKey, current))
194
+ return "updated";
195
+ if (this.force || MODIFIED_FILE_POLICY === "replace-with-backup")
196
+ return "replaced";
197
+ // A modified file. The user reconciles it by merging into <file>.rafter-new
198
+ // and moving that over the file (it then matches, above), or by deleting
199
+ // <file>.rafter-new to keep their own version: that is "reconciled" once,
200
+ // then "unchanged" until a release ships a different version.
201
+ const entry = this.manifest.files[manifestKey(this.root, a.dest)];
202
+ const newSha = sha256(a.content);
203
+ if (!fs.existsSync(a.dest + NEW_VERSION_SUFFIX)) {
204
+ if (entry?.reconciledWith === newSha)
205
+ return "unchanged";
206
+ if (entry?.pendingSha === newSha)
207
+ return "reconciled";
208
+ }
209
+ return "kept";
210
+ }
211
+ record(a) {
212
+ this.manifest.files[manifestKey(this.root, a.dest)] = {
213
+ sha256: sha256(a.content),
214
+ component: a.component,
215
+ platform: a.platform,
216
+ cliVersion: this.version,
217
+ };
218
+ this.dirty = true;
219
+ }
220
+ /**
221
+ * Record reconcile state for a modified file without claiming its content.
222
+ * With no prior entry, sha256 is the version just written to .rafter-new:
223
+ * rafter's content, so it never matches the user's file and owns() stays false.
224
+ */
225
+ recordReconcile(a, state) {
226
+ const key = manifestKey(this.root, a.dest);
227
+ const prev = this.manifest.files[key];
228
+ this.manifest.files[key] = {
229
+ sha256: prev?.sha256 ?? sha256(a.content),
230
+ component: a.component,
231
+ platform: a.platform,
232
+ cliVersion: prev?.cliVersion ?? this.version,
233
+ ...state,
234
+ };
235
+ this.dirty = true;
236
+ }
237
+ /**
238
+ * Whether <dest>.rafter-new may be (re)written: it is absent or holds a
239
+ * version rafter wrote. Anything else is the user's merge in progress.
240
+ */
241
+ mayWriteNewVersion(a) {
242
+ let existing;
243
+ try {
244
+ existing = fs.readFileSync(a.dest + NEW_VERSION_SUFFIX);
245
+ }
246
+ catch {
247
+ return true;
248
+ }
249
+ const sha = sha256(existing);
250
+ return existing.equals(a.content) ||
251
+ this.manifest.files[manifestKey(this.root, a.dest)]?.pendingSha === sha ||
252
+ (shippedHashes().get(a.resourceKey)?.has(sha) ?? false);
253
+ }
254
+ /** Drop a leftover <dest>.rafter-new that holds exactly what is now installed. */
255
+ dropStaleNewVersion(a) {
256
+ const pending = a.dest + NEW_VERSION_SUFFIX;
257
+ try {
258
+ if (fs.readFileSync(pending).equals(a.content))
259
+ fs.unlinkSync(pending);
260
+ }
261
+ catch {
262
+ /* absent or unreadable: nothing to drop */
263
+ }
264
+ }
265
+ /** Install one artifact under the write policy (or, in a dry run, predict it). */
266
+ apply(a) {
267
+ const outcome = this.classify(a);
268
+ this.outcomes.push({ dest: a.dest, outcome });
269
+ if (this.dryRun) {
270
+ if (outcome === "added" || outcome === "updated" || outcome === "replaced")
271
+ this.virtual.set(a.dest, a.content);
272
+ return outcome;
273
+ }
274
+ this.makeDir(path.dirname(a.dest));
275
+ switch (outcome) {
276
+ case "added":
277
+ case "updated":
278
+ writeNoFollow(a.dest, a.content);
279
+ this.record(a);
280
+ this.dropStaleNewVersion(a);
281
+ break;
282
+ case "unchanged":
283
+ // Unchanged is also a modified file already reconciled against this
284
+ // version; only a file that holds rafter's content is recorded as such.
285
+ if (this.read(a.dest)?.equals(a.content)) {
286
+ this.record(a);
287
+ this.dropStaleNewVersion(a);
288
+ }
289
+ break;
290
+ case "replaced":
291
+ // Moving the old file (or link) aside, not copying it, never reads or writes through a link.
292
+ fs.renameSync(a.dest, a.dest + BACKUP_SUFFIX);
293
+ writeNoFollow(a.dest, a.content);
294
+ this.record(a);
295
+ break;
296
+ case "reconciled":
297
+ this.recordReconcile(a, { reconciledWith: sha256(a.content) });
298
+ break;
299
+ case "kept":
300
+ if (this.mayWriteNewVersion(a)) {
301
+ writeNoFollow(a.dest + NEW_VERSION_SUFFIX, a.content);
302
+ this.recordReconcile(a, { pendingSha: sha256(a.content) });
303
+ }
304
+ break;
305
+ }
306
+ if (outcome !== "unchanged")
307
+ reportOutcome(this.out, a.dest, outcome);
308
+ return outcome;
309
+ }
310
+ /**
311
+ * mkdir -p, refusing in project scope when the directory resolves outside
312
+ * the root: a repo can make `.claude/skills` a link to anywhere.
313
+ */
314
+ makeDir(dir) {
315
+ if (!this.contained) {
316
+ fs.mkdirSync(dir, { recursive: true });
317
+ return;
318
+ }
319
+ const root = fs.realpathSync(this.root);
320
+ const check = (d) => {
321
+ const real = fs.realpathSync(d);
322
+ if (real !== root && !real.startsWith(root + path.sep)) {
323
+ throw new Error(`refusing to write in ${dir}: it resolves to ${real}, outside ${this.root}`);
324
+ }
325
+ };
326
+ let existing = dir;
327
+ while (!fs.existsSync(existing))
328
+ existing = path.dirname(existing);
329
+ check(existing);
330
+ fs.mkdirSync(dir, { recursive: true });
331
+ check(dir);
332
+ }
333
+ applyAll(artifacts) {
334
+ return artifacts.map((a) => this.apply(a));
335
+ }
336
+ forget(dest) {
337
+ const key = manifestKey(this.root, dest);
338
+ if (key in this.manifest.files) {
339
+ delete this.manifest.files[key];
340
+ this.dirty = true;
341
+ }
342
+ }
343
+ forgetUnder(dir) {
344
+ const prefix = manifestKey(this.root, dir) + "/";
345
+ for (const key of Object.keys(this.manifest.files)) {
346
+ if (key.startsWith(prefix)) {
347
+ delete this.manifest.files[key];
348
+ this.dirty = true;
349
+ }
350
+ }
351
+ }
352
+ save() {
353
+ if (this.dryRun || !this.dirty)
354
+ return;
355
+ const p = manifestPath(this.root);
356
+ this.makeDir(path.dirname(p));
357
+ const files = Object.fromEntries(Object.entries(this.manifest.files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
358
+ const version = this.keepManifestVersion ? this.loadedVersion : this.version;
359
+ const doc = { schema: MANIFEST_SCHEMA, cliVersion: version, files };
360
+ writeNoFollow(p, JSON.stringify(doc, null, 2) + "\n");
361
+ this.dirty = false;
362
+ }
363
+ count(outcome) {
364
+ return this.outcomes.filter((o) => o.outcome === outcome).length;
365
+ }
366
+ /** Files kept as modified, each once (Codex and Gemini share .agents/skills). */
367
+ keptFiles() {
368
+ return [...new Set(this.outcomes.filter((o) => o.outcome === "kept").map((o) => o.dest))];
369
+ }
370
+ }
371
+ export function outcomeLine(dest, outcome) {
372
+ const label = outcome.padEnd(9);
373
+ if (outcome === "kept")
374
+ return `${label} ${dest} (modified; new version at ${dest}${NEW_VERSION_SUFFIX})`;
375
+ if (outcome === "replaced")
376
+ return `${label} ${dest} (backup at ${dest}${BACKUP_SUFFIX})`;
377
+ if (outcome === "reconciled")
378
+ return `${label} ${dest} (${NEW_VERSION_SUFFIX} gone; your version is kept for this release)`;
379
+ return `${label} ${dest}`;
380
+ }
381
+ /**
382
+ * One line per file that changed or needs attention; unchanged files are
383
+ * summed into one line instead (reportUnchangedSummary). kept / replaced
384
+ * print even under --quiet (to stderr).
385
+ */
386
+ export function reportOutcome(out, dest, outcome) {
387
+ const line = outcomeLine(dest, outcome);
388
+ if (outcome === "kept" || outcome === "replaced")
389
+ out.warn(fmt.warning(line));
390
+ else
391
+ out.info(fmt.success(line));
392
+ }
393
+ export function unchangedLine(n) {
394
+ return `${n} file${n === 1 ? "" : "s"} unchanged`;
395
+ }
396
+ export function reportUnchangedSummary(session) {
397
+ const n = session.count("unchanged");
398
+ if (n > 0)
399
+ session.out.info(fmt.success(unchangedLine(n)));
400
+ }
401
+ export const FORCE_HINT = `re-run with --force (the old version is saved as ${BACKUP_SUFFIX})`;
402
+ /** The one-line instruction for reconciling a kept file; `updateCommand` is the command that records it. */
403
+ export function reconcileInstruction(updateCommand = "rafter agent update") {
404
+ return `To reconcile: merge your changes into <file>${NEW_VERSION_SUFFIX}, move it over <file>, then run '${updateCommand}' ` +
405
+ `(or delete <file>${NEW_VERSION_SUFFIX} to keep yours as is).`;
406
+ }
407
+ /**
408
+ * Closing hint when any modified files were kept: the reconcile instruction,
409
+ * and `replaceHint`, how to discard the local changes instead.
410
+ */
411
+ export function reportKeptSummary(session, replaceHint = FORCE_HINT, updateCommand = "rafter agent update") {
412
+ const n = session.keptFiles().length;
413
+ if (n === 0)
414
+ return;
415
+ session.out.warn(fmt.warning(`${n} installed file${n === 1 ? "" : "s"} had local changes and ${n === 1 ? "was" : "were"} kept; ` +
416
+ `rafter's new version is beside ${n === 1 ? "it" : "each"} as <file>${NEW_VERSION_SUFFIX}. ` +
417
+ `${reconcileInstruction(updateCommand)} To discard your changes instead, ${replaceHint}.`));
418
+ }
419
+ // ── artifact builders ────────────────────────────────────────────────
420
+ const SKIP_NAMES = new Set(["__init__.py", "__pycache__"]);
421
+ function walkFiles(dir) {
422
+ const out = [];
423
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
424
+ if (SKIP_NAMES.has(entry.name))
425
+ continue;
426
+ const p = path.join(dir, entry.name);
427
+ if (entry.isDirectory())
428
+ out.push(...walkFiles(p));
429
+ else if (entry.isFile())
430
+ out.push(p);
431
+ }
432
+ return out;
433
+ }
434
+ /** Every file of every shipped skill (SKILL.md plus docs/), installed under `skillsDir`. */
435
+ export function skillArtifacts(skillsDir, platform, component, out) {
436
+ const artifacts = [];
437
+ for (const name of KNOWN_SKILL_NAMES) {
438
+ const src = path.join(resourcesDir(), "skills", name);
439
+ if (!fs.existsSync(path.join(src, "SKILL.md"))) {
440
+ out?.warn(fmt.warning(`${name} skill template not found at ${path.join(src, "SKILL.md")}`));
441
+ continue;
442
+ }
443
+ for (const file of walkFiles(src)) {
444
+ const rel = path.relative(src, file).split(path.sep).join("/");
445
+ artifacts.push({
446
+ dest: path.join(skillsDir, name, ...rel.split("/")),
447
+ content: fs.readFileSync(file),
448
+ resourceKey: `skills/${name}/${rel}`,
449
+ component,
450
+ platform,
451
+ });
452
+ }
453
+ }
454
+ return artifacts;
455
+ }
456
+ export const RULE_SKILLS = ["rafter", "rafter-secure-design", "rafter-code-review", "rafter-skill-review"];
457
+ const RULE_LAYOUT = {
458
+ cursor: { resDir: "cursor-rules", destDir: [".cursor", "rules"], ext: ".mdc", component: "cursor.instructions", label: "Cursor" },
459
+ windsurf: { resDir: "windsurf-rules", destDir: [".windsurf", "rules"], ext: ".md", component: "windsurf.rules", label: "Windsurf" },
460
+ continue: { resDir: "continue-rules", destDir: [".continue", "rules"], ext: ".md", component: "continue.rules", label: "Continue.dev" },
461
+ };
462
+ export function ruleDest(kind, root, name) {
463
+ const l = RULE_LAYOUT[kind];
464
+ return path.join(root, ...l.destDir, `${name}${l.ext}`);
465
+ }
466
+ export function ruleArtifacts(kind, root, out) {
467
+ const l = RULE_LAYOUT[kind];
468
+ const srcDir = path.join(resourcesDir(), l.resDir);
469
+ if (!fs.existsSync(srcDir)) {
470
+ out?.warn(fmt.warning(`${l.label} rule templates not found in resources/${l.resDir}`));
471
+ return [];
472
+ }
473
+ const artifacts = [];
474
+ for (const name of RULE_SKILLS) {
475
+ const src = path.join(srcDir, `${name}${l.ext}`);
476
+ if (!fs.existsSync(src)) {
477
+ out?.warn(fmt.warning(`${l.label} rule template missing: ${src}`));
478
+ continue;
479
+ }
480
+ artifacts.push({
481
+ dest: ruleDest(kind, root, name),
482
+ content: fs.readFileSync(src),
483
+ resourceKey: `${l.resDir}/${name}${l.ext}`,
484
+ component: l.component,
485
+ platform: kind,
486
+ });
487
+ }
488
+ return artifacts;
489
+ }
490
+ /** Strip the Claude-Code `tools:` line from sub-agent frontmatter — Cursor doesn't have it. */
491
+ export function stripToolsFromFrontmatter(content) {
492
+ if (!content.startsWith("---\n"))
493
+ return content;
494
+ const fmEnd = content.indexOf("\n---", 4);
495
+ if (fmEnd === -1)
496
+ return content;
497
+ const frontmatter = content.slice(4, fmEnd);
498
+ const body = content.slice(fmEnd);
499
+ const cleaned = frontmatter
500
+ .split("\n")
501
+ .filter((line) => !/^tools:\s/.test(line))
502
+ .join("\n");
503
+ return `---\n${cleaned}${body}`;
504
+ }
505
+ /** Sub-agents shipped for Claude Code; keep in sync with the Python installer. */
506
+ export const CLAUDE_CODE_SUBAGENTS = ["rafter"];
507
+ export function claudeAgentArtifacts(root, out) {
508
+ const artifacts = [];
509
+ for (const name of CLAUDE_CODE_SUBAGENTS) {
510
+ const src = path.join(resourcesDir(), "agents", `${name}.md`);
511
+ if (!fs.existsSync(src)) {
512
+ out?.warn(fmt.warning(`${name} sub-agent template not found at ${src}`));
513
+ continue;
514
+ }
515
+ artifacts.push({
516
+ dest: path.join(root, ".claude", "agents", `${name}.md`),
517
+ content: fs.readFileSync(src),
518
+ resourceKey: `agents/${name}.md`,
519
+ component: "claude-code.agents",
520
+ platform: "claude-code",
521
+ });
522
+ }
523
+ return artifacts;
524
+ }
525
+ export function cursorAgentArtifacts(root, out) {
526
+ const src = path.join(resourcesDir(), "agents", "rafter.md");
527
+ if (!fs.existsSync(src)) {
528
+ out?.warn(fmt.warning(`Rafter sub-agent template not found in resources/agents`));
529
+ return [];
530
+ }
531
+ return [{
532
+ dest: path.join(root, ".cursor", "agents", "rafter.md"),
533
+ content: Buffer.from(stripToolsFromFrontmatter(fs.readFileSync(src, "utf-8")), "utf-8"),
534
+ resourceKey: "agents/rafter.md#cursor",
535
+ component: "cursor.instructions",
536
+ platform: "cursor",
537
+ }];
538
+ }
539
+ /**
540
+ * The OpenClaw skill, at the ClawHub workspace path OpenClaw discovers
541
+ * (<home>/.openclaw/workspace/skills/rafter-security/SKILL.md). User scope only.
542
+ */
543
+ export function openclawSkillArtifacts(home, out) {
544
+ const src = path.join(resourcesDir(), "rafter-security-skill.md");
545
+ if (!fs.existsSync(src)) {
546
+ out?.warn(fmt.warning(`OpenClaw skill template not found at ${src}`));
547
+ return [];
548
+ }
549
+ return [{
550
+ dest: openclawSkillPath(home),
551
+ content: fs.readFileSync(src),
552
+ resourceKey: "rafter-security-skill.md",
553
+ component: "openclaw.skills",
554
+ platform: "openclaw",
555
+ }];
556
+ }
557
+ export function openclawSkillPath(home) {
558
+ return path.join(home, ".openclaw", "workspace", "skills", "rafter-security", "SKILL.md");
559
+ }
560
+ /**
561
+ * Where rafter ≤ 0.7.7 put the OpenClaw skill, a path OpenClaw never reads.
562
+ * Removed only when it hashes to content rafter shipped.
563
+ */
564
+ export function openclawLegacySkillPath(home) {
565
+ return path.join(home, ".openclaw", "skills", "rafter-security.md");
566
+ }
567
+ // ── retired artifacts ────────────────────────────────────────────────
568
+ /** Remove the legacy OpenClaw skill file if it hashes to rafter's own content; otherwise keep and report it. */
569
+ export function cleanupLegacyOpenClaw(session) {
570
+ const result = { removed: [], kept: [] };
571
+ const dest = openclawLegacySkillPath(session.root);
572
+ if (!fs.existsSync(dest))
573
+ return result;
574
+ if (session.owns(dest, "rafter-security-skill.md", fs.readFileSync(dest))) {
575
+ result.removed.push(dest);
576
+ if (!session.dryRun) {
577
+ fs.unlinkSync(dest);
578
+ session.forget(dest);
579
+ session.out.info(fmt.info(`Removed legacy ${dest} (OpenClaw reads ${openclawSkillPath(session.root)})`));
580
+ }
581
+ }
582
+ else {
583
+ result.kept.push(dest);
584
+ if (!session.dryRun) {
585
+ session.out.warn(fmt.warning(`Kept legacy ${dest} (modified; OpenClaw never reads it, remove it yourself)`));
586
+ }
587
+ }
588
+ const dir = path.dirname(dest);
589
+ if (!session.dryRun && result.removed.length > 0) {
590
+ try {
591
+ if (fs.readdirSync(dir).length === 0)
592
+ fs.rmdirSync(dir);
593
+ }
594
+ catch {
595
+ /* best-effort */
596
+ }
597
+ }
598
+ return result;
599
+ }
600
+ /** Every file in `dir` is provably rafter's own content for skill `name`. */
601
+ function ownsSkillDir(session, dir, name) {
602
+ const files = walkFiles(dir);
603
+ return files.length > 0 && files.every((f) => {
604
+ const rel = path.relative(dir, f).split(path.sep).join("/");
605
+ return session.owns(f, `skills/${name}/${rel}`, fs.readFileSync(f));
606
+ });
607
+ }
608
+ /**
609
+ * Remove retired rafter skill directories under `skillsDir`. A directory goes
610
+ * when its SKILL.md carries rafter's publisher tag or every file in it hashes
611
+ * to content rafter shipped or recorded; anything else is the user's and is
612
+ * kept (and reported). In a dry run, reports what would happen.
613
+ */
614
+ export function cleanupRetiredSkills(session, skillsDir, names = RETIRED_SKILL_NAMES) {
615
+ const present = names.filter((n) => fs.existsSync(path.join(skillsDir, n, "SKILL.md")));
616
+ if (present.length === 0)
617
+ return { removed: [], kept: [] };
618
+ const owned = (dir, name) => ownsSkillDir(session, dir, name);
619
+ let removed;
620
+ if (session.dryRun) {
621
+ removed = present.filter((n) => wouldRemoveSkill(path.join(skillsDir, n), n, owned));
622
+ }
623
+ else {
624
+ removed = removeRetiredSkills(skillsDir, present, owned);
625
+ for (const n of removed)
626
+ session.forgetUnder(path.join(skillsDir, n));
627
+ }
628
+ const kept = present.filter((n) => !removed.includes(n));
629
+ if (!session.dryRun) {
630
+ for (const n of removed)
631
+ session.out.info(fmt.info(`Removed retired skill ${n} from ${skillsDir}`));
632
+ for (const n of kept) {
633
+ session.out.warn(fmt.warning(`Kept retired skill ${path.join(skillsDir, n)} (modified or not rafter's; remove it yourself if unused)`));
634
+ }
635
+ }
636
+ return { removed: removed.map((n) => path.join(skillsDir, n)), kept: kept.map((n) => path.join(skillsDir, n)) };
637
+ }
638
+ function wouldRemoveSkill(dir, name, owned) {
639
+ // The predicate removeRetiredSkills applies, evaluated without deleting.
640
+ return isRafterAuthoredSkillDir(dir) || owned(dir, name);
641
+ }
642
+ /** Remove retired per-skill rule files of `kind` that hash to rafter's own content; keep and report the rest. */
643
+ export function cleanupRetiredRules(session, kind, names = RETIRED_SKILL_NAMES) {
644
+ const result = { removed: [], kept: [] };
645
+ const l = RULE_LAYOUT[kind];
646
+ for (const name of names) {
647
+ const dest = ruleDest(kind, session.root, name);
648
+ if (!fs.existsSync(dest))
649
+ continue;
650
+ if (session.owns(dest, `${l.resDir}/${name}${l.ext}`, fs.readFileSync(dest))) {
651
+ result.removed.push(dest);
652
+ if (!session.dryRun) {
653
+ fs.unlinkSync(dest);
654
+ session.forget(dest);
655
+ session.out.info(fmt.info(`Removed retired rule ${dest}`));
656
+ }
657
+ }
658
+ else {
659
+ result.kept.push(dest);
660
+ if (!session.dryRun) {
661
+ session.out.warn(fmt.warning(`Kept retired rule ${dest} (modified; remove it yourself if unused)`));
662
+ }
663
+ }
664
+ }
665
+ return result;
666
+ }
667
+ // ── per-platform artifact sets ───────────────────────────────────────
668
+ /** Platforms that install whole-file artifacts, in init's install order. */
669
+ export const WHOLE_FILE_PLATFORMS = ["claude-code", "codex", "gemini", "cursor", "windsurf", "continue", "openclaw"];
670
+ /** Every whole-file artifact `agent init` installs for `platform` under `root`. */
671
+ export function platformArtifacts(platform, root) {
672
+ switch (platform) {
673
+ case "claude-code":
674
+ return [...skillArtifacts(path.join(root, ".claude", "skills"), "claude-code", "claude-code.skills"), ...claudeAgentArtifacts(root)];
675
+ case "codex":
676
+ return skillArtifacts(path.join(root, ".agents", "skills"), "codex", "codex.skills");
677
+ case "gemini":
678
+ return skillArtifacts(path.join(root, ".agents", "skills"), "gemini", "gemini.skills");
679
+ case "cursor":
680
+ return [...ruleArtifacts("cursor", root), ...cursorAgentArtifacts(root)];
681
+ case "windsurf":
682
+ case "continue":
683
+ return ruleArtifacts(platform, root);
684
+ case "openclaw":
685
+ return openclawSkillArtifacts(root);
686
+ default:
687
+ return [];
688
+ }
689
+ }