ronce-racine 0.5.2 → 0.7.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 (64) hide show
  1. package/AGENTS.md +7 -2
  2. package/README.md +213 -207
  3. package/agents/code-reviewer.md +1 -1
  4. package/dist/hooks/README.md +62 -0
  5. package/dist/hooks/readme-freshness.mjs +159 -0
  6. package/dist/hooks/truncate-output.mjs +13 -5
  7. package/dist/install.js +114 -711
  8. package/dist/src/catalog.js +80 -0
  9. package/dist/src/detect.js +140 -0
  10. package/dist/src/lock.js +200 -0
  11. package/dist/src/paths.js +25 -0
  12. package/dist/src/selector.js +324 -0
  13. package/dist/src/settings.js +55 -0
  14. package/dist/src/uninstall.js +170 -0
  15. package/docs/adopting-a-repo.md +29 -22
  16. package/docs/architecture.md +9 -10
  17. package/docs/catalog.md +86 -0
  18. package/docs/decisions.md +31 -13
  19. package/docs/developing.md +69 -29
  20. package/docs/distribution-model.md +130 -0
  21. package/docs/evaluating-skills.md +42 -2
  22. package/docs/git-worktrees.md +2 -2
  23. package/docs/quality-bar.md +55 -0
  24. package/docs/templates/rule.template.md +2 -1
  25. package/docs/writing-a-rule.md +13 -3
  26. package/docs/writing-a-skill.md +16 -7
  27. package/package.json +17 -4
  28. package/skills/adversarial-feature-challenge/SKILL.md +5 -3
  29. package/skills/api-contract-versioning/SKILL.md +6 -4
  30. package/skills/bug-ticket-root-cause/SKILL.md +5 -3
  31. package/skills/bug-triage-structured/SKILL.md +5 -3
  32. package/skills/ci-pipeline-orchestration/SKILL.md +5 -3
  33. package/skills/commit-readiness-review/SKILL.md +7 -3
  34. package/skills/commit-readiness-review/scripts/precommit-scan.ts +3 -3
  35. package/skills/comprehensive-test-strategy/SKILL.md +5 -3
  36. package/skills/daily-workflow-optimization/SKILL.md +6 -4
  37. package/skills/database-schema-evolution/SKILL.md +6 -4
  38. package/skills/ddd-backend-implementation/SKILL.md +5 -3
  39. package/skills/design-system-component-lifecycle/SKILL.md +6 -4
  40. package/skills/detection-sweep/SKILL.md +7 -3
  41. package/skills/detection-sweep/scripts/sweep.ts +3 -3
  42. package/skills/domain-glossary/README.md +44 -0
  43. package/skills/domain-glossary/SKILL.md +166 -0
  44. package/skills/frontend-fullstack-implementation/SKILL.md +6 -4
  45. package/skills/frontend-spec-call-site-audit/SKILL.md +7 -3
  46. package/skills/frontend-spec-call-site-audit/scripts/audit-entry-points.ts +4 -1
  47. package/skills/merge-request-review/SKILL.md +5 -3
  48. package/skills/performance-profiling/README.md +69 -0
  49. package/skills/performance-profiling/SKILL.md +223 -0
  50. package/skills/performance-profiling/reference/go.md +235 -0
  51. package/skills/performance-profiling/reference/native.md +148 -0
  52. package/skills/performance-profiling/reference/node-web.md +157 -0
  53. package/skills/performance-profiling/reference/statistics.md +181 -0
  54. package/skills/performance-profiling/reference/tracy.md +137 -0
  55. package/skills/production-incident-diagnostic/SKILL.md +5 -3
  56. package/skills/qa-session-intake/SKILL.md +5 -3
  57. package/skills/recording-decisions/SKILL.md +5 -3
  58. package/skills/recurring-bug-root-cause/SKILL.md +5 -3
  59. package/skills/recurring-bug-root-cause/scripts/detect-recurring-fixes.ts +1 -1
  60. package/skills/refactoring-shared-component-api/SKILL.md +7 -3
  61. package/skills/refactoring-shared-component-api/scripts/sweep-call-sites.ts +10 -3
  62. package/skills/validating-features-end-to-end/SKILL.md +5 -3
  63. package/skills/visual-regression-check/SKILL.md +6 -4
  64. package/skills/writing-robust-tests/SKILL.md +8 -4
package/dist/install.js CHANGED
@@ -13,695 +13,45 @@
13
13
  * hooks → <repo>/.claude/hooks/
14
14
  * agents → <repo>/.claude/agents/
15
15
  * and prints the settings.json snippet to wire up the hooks.
16
+ *
17
+ * The implementation is split under src/: paths, lock, catalog, detect,
18
+ * settings and selector. This file keeps the commands and the CLI parsing.
16
19
  */
17
- import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync, cpSync, realpathSync } from "node:fs";
18
- import { join, dirname, basename } from "node:path";
20
+ import { existsSync, mkdirSync, writeFileSync, realpathSync, rmSync } from "node:fs";
21
+ import { join } from "node:path";
19
22
  import { fileURLToPath } from "node:url";
20
- import { emitKeypressEvents } from "node:readline";
21
- import { createHash } from "node:crypto";
22
- const HERE = dirname(fileURLToPath(import.meta.url));
23
- // The CLI runs as install.ts from the repo root, and as dist/install.js once
24
- // built for npm. Artifacts always live at the root, so climb out of dist/.
25
- const SELF = basename(HERE) === "dist" ? join(HERE, "..") : HERE;
26
- /** How the user invoked this CLI: `install.ts` from a clone, `ronce-racine` from the package. */
27
- const INVOCATION = basename(HERE) === "dist" ? "ronce-racine" : "install.ts";
28
- const LOCKFILE = ".claude/.ronce-racine.json";
29
- // Hooks ship BUILT (dist/hooks/*.mjs), never as TypeScript. Compiling them at
30
- // run time cost ~490 ms on every prompt and forced tsx onto the target repo;
31
- // built JS runs in 34 ms on plain node. Build: tools/build.ts.
32
- const BUILT_HOOKS = join(SELF, "dist", "hooks");
33
- const shippedHookName = (f) => f.replace(/\.ts$/, ".mjs");
34
- /** Resolves canonical + target for a "kind:name" token. */
35
- function tokenPaths(token, repo) {
36
- const [kind, name] = token.split(":");
37
- if (kind === "rule")
38
- return { canon: join(SELF, "rules", name), inst: join(repo, ".claude/rules/shared", name), isDir: false };
39
- if (kind === "skill")
40
- return { canon: join(SELF, "skills", name), inst: join(repo, ".claude/skills", name), isDir: true };
41
- if (kind === "agent")
42
- return { canon: join(SELF, "agents", name), inst: join(repo, ".claude/agents", name), isDir: false };
43
- if (kind === "script")
44
- return { canon: join(SELF, "scripts", name), inst: join(repo, ".claude/scripts", name), isDir: false };
45
- // kind === "hook": one token per individual file
46
- return { canon: join(BUILT_HOOKS, shippedHookName(name)), inst: join(repo, ".claude/hooks", shippedHookName(name)), isDir: false };
47
- }
48
- /**
49
- * Fingerprint of the canonical content behind a set of tokens. The lockfile
50
- * records it next to the package version: with the version alone, `check`
51
- * compares "0.4.0" to "0.4.0" and reports nothing even when the package
52
- * content changed under the same number.
53
- * A missing canonical file (e.g. a hook token before `dist/` is built) is
54
- * folded in as an explicit absence marker rather than silently skipped, so
55
- * an unbuilt checkout cannot hash the same as a built one.
56
- */
57
- export function canonicalHash(tokens) {
58
- const h = createHash("sha256");
59
- for (const token of [...tokens].sort()) {
60
- const { canon, isDir } = tokenPaths(token, "");
61
- h.update(token);
62
- if (!existsSync(canon)) {
63
- h.update("\0absent");
64
- continue;
65
- }
66
- if (isDir) {
67
- for (const rel of listFiles(canon).filter((f) => !f.endsWith(".test.ts") && f !== "eval.yaml" && f !== "README.md")) {
68
- h.update(rel);
69
- h.update(readFileSync(join(canon, rel)));
70
- }
71
- }
72
- else {
73
- h.update(readFileSync(canon));
74
- }
75
- }
76
- return `sha256-${h.digest("hex")}`;
77
- }
78
- /** Version of the package this CLI belongs to. */
79
- function selfVersion() {
80
- try {
81
- return JSON.parse(readFileSync(join(SELF, "package.json"), "utf8")).version ?? "0.0.0";
82
- }
83
- catch {
84
- return "0.0.0";
85
- }
86
- }
87
- export function describeSource(s) {
88
- return typeof s === "string" ? `clone ${s.slice(0, 8)}` : `${s.package}@${s.version}`;
89
- }
90
- /** A clone-era lockfile has no version to compare, so it is never stale. */
91
- export function isStale(s, tokens) {
92
- if (typeof s === "string")
93
- return false;
94
- return s.version !== selfVersion() || s.contentHash !== canonicalHash(tokens);
95
- }
96
- /** Names which part actually drifted, so the message is truthful and actionable. */
97
- function staleMessage(s, repo) {
98
- const reinstall = `re-run 'ronce-racine install ${repo}'`;
99
- if (typeof s !== "string" && s.version !== selfVersion()) {
100
- return `↑ stale: installed from ${describeSource(s)}, now running ${selfVersion()} - ${reinstall}.`;
101
- }
102
- const ver = typeof s === "string" ? describeSource(s) : s.version;
103
- return `↑ stale: same version (${ver}) but the canonical content changed - ${reinstall}.`;
104
- }
105
- function listFiles(root) {
106
- const out = [];
107
- const walk = (d, rel) => {
108
- for (const e of readdirSync(d, { withFileTypes: true })) {
109
- const r = rel ? `${rel}/${e.name}` : e.name;
110
- if (e.isDirectory())
111
- walk(join(d, e.name), r);
112
- else
113
- out.push(r);
114
- }
115
- };
116
- if (existsSync(root))
117
- walk(root, "");
118
- return out.sort();
119
- }
120
- /** null if compliant, otherwise a description of the drift. */
121
- function compareToken(token, repo) {
122
- const { canon, inst, isDir } = tokenPaths(token, repo);
123
- if (!existsSync(inst))
124
- return "absent";
125
- if (!existsSync(canon))
126
- return "canonical-removed";
127
- if (!isDir)
128
- return readFileSync(canon).equals(readFileSync(inst)) ? null : "modified";
129
- // Test procedures and eval manifests are never distributed (see copyToken) - exclude them from drift.
130
- const canonFiles = listFiles(canon).filter((f) => !f.endsWith(".test.ts") && f !== "eval.yaml" && f !== "README.md");
131
- const probs = [
132
- ...canonFiles.filter((f) => !existsSync(join(inst, f))).map((f) => `-${f}`),
133
- ...canonFiles.filter((f) => existsSync(join(inst, f)) && !readFileSync(join(canon, f)).equals(readFileSync(join(inst, f)))).map((f) => `~${f}`),
134
- ...listFiles(inst).filter((f) => !canonFiles.includes(f)).map((f) => `+${f}`),
135
- ];
136
- return probs.length ? probs.join(" ") : null;
137
- }
138
- function readLock(repo) {
139
- const p = join(repo, LOCKFILE);
140
- if (!existsSync(p))
141
- return null;
142
- try {
143
- return JSON.parse(readFileSync(p, "utf8"));
144
- }
145
- catch {
146
- return null;
147
- }
148
- }
149
- /** Catalog: the installer's "knowledge" (signal → artifact + reason). */
150
- const CATALOG = [
151
- // rules
152
- { kind: "rule", name: "minimal-code.md", when: ["code"], reason: "YAGNI + readability, any code project" },
153
- { kind: "rule", name: "commits.md", when: ["git"], reason: "commit message format" },
154
- { kind: "rule", name: "secure-logging.md", when: ["code"], reason: "GDPR: never log sensitive data" },
155
- { kind: "rule", name: "pre-commit-secret-detection.md", when: ["git"], reason: "no committed secrets" },
156
- { kind: "rule", name: "test-discipline.md", when: ["tests"], reason: "tests detected" },
157
- { kind: "rule", name: "error-handling-discipline.md", when: ["backend", "code"], reason: "no swallowed error / panic" },
158
- { kind: "rule", name: "subscription-cleanup.md", when: ["frontend"], reason: "frontend: subscription teardown" },
159
- { kind: "rule", name: "ui-states-complete.md", when: ["frontend"], reason: "frontend: loading/error/empty/success states" },
160
- { kind: "rule", name: "clean-architecture-deps.md", when: ["backend"], reason: "backend: dependency direction" },
161
- { kind: "rule", name: "no-raw-sql-interpolation.md", when: ["sql"], reason: "SQL detected: anti-injection" },
162
- { kind: "rule", name: "sql-migrations-discipline.md", when: ["migrations"], reason: "migrations detected" },
163
- { kind: "rule", name: "detection-gap-protocol.md", when: ["code"], reason: "P0 found by user = detection failure", optional: true },
164
- // skills (process / cross-cutting)
165
- { kind: "skill", name: "recording-decisions", when: "always", reason: "record non-obvious choices" },
166
- { kind: "skill", name: "detection-sweep", when: ["code"], reason: "project detection sweep" },
167
- { kind: "skill", name: "commit-readiness-review", when: ["git"], reason: "self-review before commit (+ scripts/precommit-scan.ts)" },
168
- { kind: "skill", name: "merge-request-review", when: ["ci", "git"], reason: "review an MR/PR before merge" },
169
- { kind: "skill", name: "bug-ticket-root-cause", when: ["git"], reason: "document a bug as a ticket" },
170
- { kind: "skill", name: "bug-triage-structured", when: ["git"], reason: "full triage of a bug" },
171
- { kind: "skill", name: "recurring-bug-root-cause", when: ["git"], reason: "recurring bug → root cause" },
172
- { kind: "skill", name: "daily-workflow-optimization", when: ["code"], reason: "reduce workflow friction", optional: true },
173
- { kind: "skill", name: "qa-session-intake", when: ["frontend"], reason: "turn a QA session into tickets", optional: true },
174
- // test skills
175
- { kind: "skill", name: "writing-robust-tests", when: ["tests", "code"], reason: "write robust tests" },
176
- { kind: "skill", name: "comprehensive-test-strategy", when: ["tests", "code"], reason: "risk-based test strategy" },
177
- { kind: "skill", name: "adversarial-feature-challenge", when: ["code"], reason: "adversarial stress-test of a feature" },
178
- { kind: "skill", name: "validating-features-end-to-end", when: ["code"], reason: "validate a feature before closing" },
179
- // design / impl skills
180
- { kind: "skill", name: "domain-modeling-design", when: ["backend"], reason: "model a domain before coding" },
181
- { kind: "skill", name: "ddd-backend-implementation", when: ["backend"], reason: "implement in DDD layers" },
182
- { kind: "skill", name: "api-contract-versioning", when: ["backend"], reason: "evolve an API contract" },
183
- { kind: "skill", name: "database-schema-evolution", when: ["migrations", "sql"], reason: "risky schema migration" },
184
- // frontend skills
185
- { kind: "skill", name: "frontend-spec-call-site-audit", when: ["frontend"], reason: "frontend spec before ticket" },
186
- { kind: "skill", name: "frontend-fullstack-implementation", when: ["frontend"], reason: "implement a frontend feature" },
187
- { kind: "skill", name: "refactoring-shared-component-api", when: ["frontend"], reason: "change a shared component's API" },
188
- { kind: "skill", name: "design-system-component-lifecycle", when: ["frontend"], reason: "create/extend a DS component" },
189
- { kind: "skill", name: "visual-regression-check", when: ["frontend"], reason: "check the rendering before commit" },
190
- // ops skills
191
- { kind: "skill", name: "ci-pipeline-orchestration", when: ["ci"], reason: "CI detected: check/diagnose/retry" },
192
- { kind: "skill", name: "production-incident-diagnostic", when: ["infra"], reason: "infra/deployment: prod incident triage" },
193
- // audit skills (heavy, optional)
194
- { kind: "skill", name: "audit-industrialisation", when: ["code"], reason: "maturity audit orchestrator", optional: true },
195
- { kind: "skill", name: "audit-report", when: ["code"], reason: "audit report template/scoring", optional: true },
196
- { kind: "skill", name: "audit-security", when: ["backend", "infra"], reason: "application security audit", optional: true },
197
- { kind: "skill", name: "audit-testing", when: ["tests"], reason: "test strategy audit", optional: true },
198
- { kind: "skill", name: "audit-ci-cd", when: ["ci"], reason: "CI/CD & release audit", optional: true },
199
- { kind: "skill", name: "audit-quality", when: ["code"], reason: "code & data quality audit", optional: true },
200
- { kind: "skill", name: "audit-architecture", when: ["backend"], reason: "architecture & availability audit", optional: true },
201
- { kind: "skill", name: "audit-observability", when: ["infra", "backend"], reason: "observability & alerting audit", optional: true },
202
- { kind: "skill", name: "audit-performance-frontend", when: ["frontend"], reason: "low-level frontend perf audit", optional: true },
203
- { kind: "skill", name: "audit-compliance", when: ["code"], reason: "compliance/GDPR/FinOps audit", optional: true },
204
- // scripts (standalone, read-only)
205
- { kind: "script", name: "subscription-leak-scan.ts", when: ["frontend"], reason: "detects subscriptions/listeners/timers without teardown" },
206
- // hooks
207
- { kind: "hook", name: "skill-reminder.ts", when: "always", reason: "suggests the relevant skills for the prompt", wiring: [{ event: "UserPromptSubmit", commandFile: "skill-reminder.ts" }] },
208
- { kind: "hook", name: "bash-npm-silent.ts", when: ["code"], reason: "silences npm install/ci (less noise)", wiring: [{ event: "PreToolUse", matcher: "Bash", commandFile: "bash-npm-silent.ts" }] },
209
- { kind: "hook", name: "truncate-output.ts", when: ["code"], reason: "caps verbose output (cargo/git/docker…)", files: ["truncate-output.ts", "truncate-bash-output.ts"], wiring: [{ event: "PreToolUse", matcher: "Bash", commandFile: "truncate-output.ts" }] },
210
- { kind: "hook", name: "session-writer.ts", when: "always", reason: "per-branch session memo (writer/inject/precompact)", optional: true, files: ["session-writer.ts", "session-inject.ts", "session-precompact.ts"], wiring: [{ event: "Stop", commandFile: "session-writer.ts" }, { event: "SessionStart", matcher: "compact", commandFile: "session-inject.ts" }, { event: "PreCompact", commandFile: "session-precompact.ts" }] },
211
- { kind: "hook", name: "worktree-env-setup.ts", when: "always", reason: "symlink .env into git worktrees", optional: true, wiring: [{ event: "SessionStart", commandFile: "worktree-env-setup.ts" }] },
212
- // agents
213
- { kind: "agent", name: "code-reviewer.md", when: ["git", "code"], reason: "diff review agent" },
214
- { kind: "agent", name: "qa-tester.md", when: ["tests"], reason: "E2E testing agent" },
215
- ];
216
- /** Bounded walk: extensions seen, presence of specs and a migrations folder. */
217
- function scan(repo) {
218
- // Prune `.claude` too: the tool's own installed artifacts (hook/script .ts
219
- // files) must not be detected as the project's code on a re-install.
220
- const PRUNE = new Set(["node_modules", ".git", ".claude", "target", "dist", "build", "vendor", ".nuxt", ".next", "coverage"]);
221
- const exts = new Set();
222
- let spec = false;
223
- let migrations = false;
224
- let budget = 6000;
225
- const walk = (dir) => {
226
- if (budget <= 0)
227
- return;
228
- let entries;
229
- try {
230
- entries = readdirSync(dir, { withFileTypes: true });
231
- }
232
- catch {
233
- return;
234
- }
235
- for (const e of entries) {
236
- if (budget-- <= 0)
237
- return;
238
- if (e.isDirectory()) {
239
- if (PRUNE.has(e.name))
240
- continue;
241
- if (/^migrations?$/i.test(e.name) || /^migrate$/i.test(e.name))
242
- migrations = true;
243
- walk(join(dir, e.name));
244
- }
245
- else {
246
- const m = /\.[a-z0-9]+$/i.exec(e.name);
247
- if (m)
248
- exts.add(m[0].toLowerCase());
249
- if (/\.(spec|test)\.[tj]sx?$/.test(e.name))
250
- spec = true;
251
- }
252
- }
253
- };
254
- walk(repo);
255
- // No silent caps: on a huge repo the walk stops at the budget - say so, a
256
- // missed deep signal (migrations/, *.sql) would otherwise look like "not there".
257
- return { exts, spec, migrations, truncated: budget <= 0 };
258
- }
259
- function detect(repo) {
260
- const sig = new Set();
261
- const ev = {};
262
- const add = (s, why) => {
263
- if (!sig.has(s)) {
264
- sig.add(s);
265
- ev[s] = why;
266
- }
267
- };
268
- const has = (p) => existsSync(join(repo, p));
269
- if (has(".git"))
270
- add("git", ".git/");
271
- if (has(".gitlab-ci.yml") || has(".github/workflows") || has("Jenkinsfile") || has(".circleci/config.yml"))
272
- add("ci", "CI config");
273
- if (["Dockerfile", "docker-compose.yml", "docker-compose.yaml", "k8s", "kubernetes", "helm", "terraform"].some(has))
274
- add("infra", "Docker/infra");
275
- let deps = [];
276
- if (has("package.json")) {
277
- try {
278
- const p = JSON.parse(readFileSync(join(repo, "package.json"), "utf8"));
279
- deps = Object.keys({ ...p.dependencies, ...p.devDependencies });
280
- }
281
- catch {
282
- /* ignore */
283
- }
284
- }
285
- const dep = (re) => deps.some((d) => re.test(d));
286
- if (dep(/^(react|vue|svelte|nuxt|next|@angular|solid-js|preact)/))
287
- add("frontend", "frontend dependencies");
288
- if (dep(/^(express|koa|fastify|@nestjs|hapi|@hapi)/))
289
- add("backend", "Node backend dependencies");
290
- if (dep(/playwright|cypress/))
291
- add("tests", "E2E deps");
292
- if (dep(/vitest|jest|mocha|jasmine|karma/))
293
- add("tests", "test runner");
294
- const { exts, spec, migrations, truncated } = scan(repo);
295
- if (truncated)
296
- add("scan-truncated", "large repo: detection stopped at the scan budget - deep signals may be missed; pass artifacts explicitly if needed");
297
- const anyCode = [".ts", ".tsx", ".js", ".jsx", ".vue", ".svelte", ".rs", ".go", ".java", ".py", ".php", ".rb"].some((e) => exts.has(e));
298
- if (anyCode)
299
- add("code", "sources detected");
300
- if ([".vue", ".svelte", ".tsx", ".jsx"].some((e) => exts.has(e)))
301
- add("frontend", "UI files");
302
- if ([".rs", ".go", ".java", ".py", ".php"].some((e) => exts.has(e)) || has("Cargo.toml") || has("go.mod") || has("pom.xml"))
303
- add("backend", "backend sources");
304
- if (exts.has(".sql"))
305
- add("sql", "SQL files");
306
- if (migrations)
307
- add("migrations", "migrations folder");
308
- if (spec)
309
- add("tests", "*.spec/*.test files");
310
- return { signals: sig, evidence: ev };
311
- }
312
- function isRecommended(item, sig) {
313
- return item.when === "always" || item.when.some((s) => sig.has(s));
314
- }
315
- function plan(repo) {
316
- const { signals, evidence } = detect(repo);
317
- const matched = CATALOG.filter((i) => isRecommended(i, signals));
318
- return {
319
- picked: matched.filter((i) => !i.optional),
320
- optional: matched.filter((i) => i.optional),
321
- signals,
322
- evidence,
323
- };
324
- }
325
- const KIND_LABEL = { rule: "Rules", skill: "Skills", script: "Scripts", hook: "Hooks", agent: "Agents" };
326
- function printGroup(title, items) {
327
- if (!items.length)
328
- return;
329
- console.log(`\n${title}`);
330
- for (const k of ["rule", "skill", "script", "hook", "agent"]) {
331
- const g = items.filter((i) => i.kind === k);
332
- if (!g.length)
333
- continue;
334
- console.log(` ${KIND_LABEL[k]} (${g.length}) :`);
335
- for (const i of g)
336
- console.log(` • ${i.name.replace(/\.md$/, "")} - ${i.reason}`);
337
- }
338
- }
339
- function doPlan(repo) {
340
- const { picked, optional, signals, evidence } = plan(repo);
341
- console.log(`Analysis of ${repo}`);
342
- console.log(`Signals: ${[...signals].map((s) => `${s} (${evidence[s]})`).join(", ") || "none"}`);
343
- printGroup("✓ Recommended (installed by default):", picked);
344
- printGroup("• Optional (add with --all):", optional);
345
- const invocation = basename(HERE) === "dist" ? `node ${join(HERE, "install.js")}` : `npx tsx ${join(SELF, "install.ts")}`;
346
- console.log(`\n→ To install: ${invocation} install ${repo}` + ` (add --all for the optional ones)`);
347
- }
348
- function mergeHookSettings(dotclaude, wirings) {
349
- const settingsPath = join(dotclaude, "settings.json");
350
- const existed = existsSync(settingsPath);
351
- let settings = {};
352
- let malformed = false;
353
- if (existed) {
354
- try {
355
- settings = JSON.parse(readFileSync(settingsPath, "utf8"));
356
- }
357
- catch {
358
- malformed = true; // keep {} but back up the original before overwriting
359
- }
360
- }
361
- // A hooks section with an unexpected shape (array, string…) cannot be merged
362
- // into: treat it like malformed JSON - back up the file and rebuild the section.
363
- if (settings.hooks !== undefined && (typeof settings.hooks !== "object" || settings.hooks === null || Array.isArray(settings.hooks))) {
364
- malformed = true;
365
- delete settings.hooks;
366
- }
367
- const hooks = (settings.hooks ??= {});
368
- let added = 0;
369
- for (const w of wirings) {
370
- const command = `node $CLAUDE_PROJECT_DIR/.claude/hooks/${shippedHookName(w.commandFile)}`;
371
- if (!Array.isArray(hooks[w.event])) {
372
- if (hooks[w.event] !== undefined)
373
- malformed = true;
374
- hooks[w.event] = [];
375
- }
376
- const entries = hooks[w.event];
377
- let entry = entries.find((e) => e && typeof e === "object" && Array.isArray(e.hooks) && (e.matcher ?? "") === (w.matcher ?? ""));
378
- if (!entry) {
379
- entry = { ...(w.matcher ? { matcher: w.matcher } : {}), hooks: [] };
380
- entries.push(entry);
381
- }
382
- if (!entry.hooks.some((h) => h.command === command)) {
383
- entry.hooks.push({ type: "command", command });
384
- added++;
385
- }
386
- }
387
- const backedUp = existed && (added > 0 || malformed);
388
- if (added > 0 || malformed) {
389
- if (backedUp)
390
- cpSync(settingsPath, settingsPath + ".bak");
391
- writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
392
- }
393
- return { added, backedUp, malformed };
394
- }
395
- const KIND_ORDER = ["rule", "skill", "script", "hook", "agent"];
396
- // ─── Layout constants ─────────────────────────────────────────────────────────
397
- const HEADER_LINES = 2;
398
- const LEGEND_LINES = 2;
399
- const DETAIL_LINES = 4;
400
- const MIN_VIEWPORT_ROWS = 5;
401
- const ITEM_LINE_WIDTH = 50;
402
- // ─── ANSI helpers ─────────────────────────────────────────────────────────────
403
- const DIM = (s) => `\x1b[2m${s}\x1b[0m`;
404
- const INVERSE = (s) => `\x1b[7m${s}\x1b[0m`;
405
- const BOLD = (s) => `\x1b[1m${s}\x1b[0m`;
406
- // ─── Description precomputation ───────────────────────────────────────────────
407
- /**
408
- * Reads the real description of each item from its source file.
409
- * Called once before the selector loop.
410
- */
411
- function buildDetailMap(items) {
412
- const map = new Map();
413
- for (const item of items) {
414
- map.set(item, readItemDescription(item));
415
- }
416
- return map;
417
- }
418
- function readItemDescription(item) {
419
- try {
420
- if (item.kind === "skill") {
421
- const skillFile = join(SELF, "skills", item.name, "SKILL.md");
422
- if (existsSync(skillFile)) {
423
- const content = readFileSync(skillFile, "utf8");
424
- const desc = extractFrontmatterField(content, "description");
425
- if (desc)
426
- return desc;
427
- }
428
- }
429
- else if (item.kind === "rule") {
430
- const ruleFile = join(SELF, "rules", item.name);
431
- if (existsSync(ruleFile)) {
432
- const content = readFileSync(ruleFile, "utf8");
433
- // Look for the first # line after the frontmatter (or at the start of the file)
434
- const afterFront = skipFrontmatter(content);
435
- const m = /^#\s+(.+)/m.exec(afterFront);
436
- if (m)
437
- return m[1].trim();
438
- }
439
- }
440
- else if (item.kind === "script") {
441
- const scriptFile = join(SELF, "scripts", item.name);
442
- if (existsSync(scriptFile)) {
443
- const content = readFileSync(scriptFile, "utf8");
444
- const desc = extractJsDocFirstSentence(content);
445
- if (desc)
446
- return desc;
447
- }
448
- }
449
- else if (item.kind === "hook") {
450
- const hookFile = join(SELF, "hooks", item.name);
451
- if (existsSync(hookFile)) {
452
- const content = readFileSync(hookFile, "utf8");
453
- const desc = extractJsDocFirstSentence(content);
454
- if (desc)
455
- return desc;
456
- }
457
- }
458
- else if (item.kind === "agent") {
459
- const agentFile = join(SELF, "agents", item.name);
460
- if (existsSync(agentFile)) {
461
- const content = readFileSync(agentFile, "utf8");
462
- const desc = extractFrontmatterField(content, "description");
463
- if (desc)
464
- return desc;
465
- // Fallback: first line of the file
466
- const firstLine = content.split("\n").find((l) => l.trim().length > 0);
467
- if (firstLine)
468
- return firstLine.replace(/^#\s*/, "").trim();
469
- }
470
- }
471
- }
472
- catch {
473
- // Cannot read - fall back to the default
474
- }
475
- return item.reason;
476
- }
477
- function skipFrontmatter(content) {
478
- if (!content.startsWith("---"))
479
- return content;
480
- const end = content.indexOf("\n---", 3);
481
- if (end === -1)
482
- return content;
483
- return content.slice(end + 4);
484
- }
485
- function extractFrontmatterField(content, field) {
486
- if (!content.startsWith("---"))
487
- return null;
488
- const end = content.indexOf("\n---", 3);
489
- if (end === -1)
490
- return null;
491
- const front = content.slice(0, end);
492
- const re = new RegExp(`^${field}:\\s*(.+)`, "m");
493
- const m = re.exec(front);
494
- if (!m)
495
- return null;
496
- // Strip any surrounding quotes
497
- return m[1].trim().replace(/^["']|["']$/g, "");
498
- }
499
- function extractJsDocFirstSentence(content) {
500
- const start = content.indexOf("/**");
501
- if (start === -1)
502
- return null;
503
- const end = content.indexOf("*/", start);
504
- const block = end === -1 ? content.slice(start) : content.slice(start, end);
505
- // Remove /** and the leading * on each line
506
- const text = block
507
- .replace(/\/\*\*/, "")
508
- .replace(/\*\/$/, "")
509
- .split("\n")
510
- .map((l) => l.replace(/^\s*\*\s?/, "").trim())
511
- .filter(Boolean)
512
- .join(" ");
513
- // Take up to the first period or the end of the first "sentence"
514
- const m = /^([^.\n]+\.?)/.exec(text);
515
- return m ? m[1].trim() : text.slice(0, 120) || null;
516
- }
517
- // ─── Rendering sub-functions (pure) ───────────────────────────────────────────
518
- function buildHeader(checkedCount, total) {
519
- const title = BOLD("⚙ Installing ronce-racine");
520
- const counter = `${checkedCount}/${total} selected`;
521
- return ` ${title} ${counter}\n`;
522
- }
523
- function buildGroupHeader(kind, checkedInGroup, totalInGroup) {
524
- const label = `${KIND_LABEL[kind]} (${checkedInGroup}/${totalInGroup})`;
525
- const dashes = "─".repeat(Math.max(0, ITEM_LINE_WIDTH - label.length - 4));
526
- return ` ─── ${label} ${dashes}`;
527
- }
528
- function buildItemLine(item, isChecked, isCursor) {
529
- const box = isChecked ? "[x]" : "[ ]";
530
- const baseName = item.name.replace(/\.md$/, "");
531
- const optTag = item.optional ? " · opt" : "";
532
- const nameField = (baseName + optTag).padEnd(28);
533
- const line = ` ${isCursor ? "›" : " "} ${box} ${nameField} - ${item.reason}`;
534
- if (isCursor)
535
- return INVERSE(line);
536
- if (item.optional)
537
- return DIM(line);
538
- return line;
539
- }
540
- function buildDetailPanel(item, detail) {
541
- const kindLabel = KIND_LABEL[item.kind];
542
- const baseName = item.name.replace(/\.md$/, "");
543
- const token = `${item.kind}:${baseName}`;
544
- const badge = item.optional ? " · optional" : " · recommended";
545
- const desc = detail.get(item) ?? item.reason;
546
- const header = ` Detail: ${kindLabel} › ${baseName} [token: ${token}]${badge}`;
547
- const body = ` ${desc.slice(0, 120)}${desc.length > 120 ? "…" : ""}`;
548
- return `\n${header}\n${body}\n`;
549
- }
550
- function buildLegend() {
551
- return `\n ${DIM("↑↓ move · space toggle · a (un)check the group · enter confirm · q cancel")}`;
552
- }
553
- // ─── Main frame ────────────────────────────────────────────────────────────────
554
- /**
555
- * Builds the complete selector frame (pure function, no I/O).
556
- * Returns the string to write after \x1b[2J\x1b[H.
557
- */
558
- function buildSelectorFrame(opts) {
559
- const { flat, checked, cursor, detail, rows } = opts;
560
- // Viewport computation
561
- const viewportRows = Math.max(MIN_VIEWPORT_ROWS, rows - HEADER_LINES - LEGEND_LINES - DETAIL_LINES);
562
- // Header
563
- const header = buildHeader(checked.size, flat.length);
564
- // Build the list lines (with group headers)
565
- const listLines = [];
566
- let lastKind = null;
567
- for (let i = 0; i < flat.length; i++) {
568
- const item = flat[i];
569
- if (item.kind !== lastKind) {
570
- // Group header
571
- const groupItems = flat.filter((x) => x.kind === item.kind);
572
- const checkedInGroup = groupItems.filter((x) => checked.has(x)).length;
573
- listLines.push(buildGroupHeader(item.kind, checkedInGroup, groupItems.length));
574
- lastKind = item.kind;
575
- }
576
- listLines.push(buildItemLine(item, checked.has(item), i === cursor));
577
- }
578
- // Viewport: find the index in listLines corresponding to the cursor item
579
- // We rebuild an item-index → line-index mapping
580
- const itemLineIndices = [];
581
- let lineIdx = 0;
582
- let prevKind = null;
583
- for (const item of flat) {
584
- if (item.kind !== prevKind) {
585
- lineIdx++; // group line
586
- prevKind = item.kind;
587
- }
588
- itemLineIndices.push(lineIdx);
589
- lineIdx++;
590
- }
591
- const cursorLineIdx = itemLineIndices[cursor] ?? 0;
592
- // Compute the viewport start: keeps the cursor visible with a margin on both sides
593
- const MARGIN = 2; // context lines kept around the cursor
594
- const lineViewportStart = Math.max(0, Math.min(cursorLineIdx - MARGIN, listLines.length - viewportRows));
595
- const visibleLines = listLines.slice(lineViewportStart, lineViewportStart + viewportRows);
596
- // Overflow indicators
597
- const overflowTop = lineViewportStart > 0 ? lineViewportStart : 0;
598
- const overflowBottom = Math.max(0, listLines.length - (lineViewportStart + viewportRows));
599
- const topIndicator = overflowTop > 0 ? ` ▲ ${overflowTop} more\n` : "";
600
- const bottomIndicator = overflowBottom > 0 ? ` ▼ ${overflowBottom} more\n` : "";
601
- // Detail panel
602
- const currentItem = flat[cursor];
603
- const detailPanel = currentItem ? buildDetailPanel(currentItem, detail) : "\n\n\n\n";
604
- // Legend
605
- const legend = buildLegend();
606
- return (header +
607
- "\n" +
608
- topIndicator +
609
- visibleLines.join("\n") +
610
- "\n" +
611
- bottomIndicator +
612
- detailPanel +
613
- legend +
614
- "\n");
615
- }
23
+ import { SELF, INVOCATION, LOCKFILE, BUILT_HOOKS, ADOPTED_HEADER, shippedHookName } from "./src/paths.js";
24
+ import { CATALOG } from "./src/catalog.js";
25
+ import { canonicalHash, compareToken, copyPath, describeSource, isStale, loadLock, selfVersion, staleMessage } from "./src/lock.js";
26
+ import { doPlan, plan } from "./src/detect.js";
27
+ import { mergeHookSettings } from "./src/settings.js";
28
+ import { unwireHookSettings, removeArtifacts, cleanupLayout } from "./src/uninstall.js";
29
+ import { interactiveSelect } from "./src/selector.js";
30
+ // Re-exported so importers (and the test suite) keep a single entry point.
31
+ export { canonicalHash, copyPath, describeSource, isStale } from "./src/lock.js";
32
+ export { CATALOG } from "./src/catalog.js";
33
+ export { applySelectorKey } from "./src/selector.js";
616
34
  /**
617
- * Applies one keypress to the selector state (mutated in place).
618
- * Returns "continue", "confirm" (enter) or "cancel" (q / ctrl-c).
35
+ * Reads the lockfile, or exits 2 saying why.
36
+ *
37
+ * An unreadable lockfile is never treated as an absent one: the difference is
38
+ * "nothing to do" versus "an installation is on disk that no command can act on
39
+ * safely", and guessing the first is how a command destroys or duplicates work.
619
40
  */
620
- export function applySelectorKey(state, key) {
621
- const k = key?.name;
622
- if ((key?.ctrl && k === "c") || k === "q")
623
- return "cancel";
624
- if (k === "up" || k === "k")
625
- state.cursor = (state.cursor - 1 + state.flat.length) % state.flat.length;
626
- else if (k === "down" || k === "j")
627
- state.cursor = (state.cursor + 1) % state.flat.length;
628
- else if (k === "space") {
629
- const it = state.flat[state.cursor];
630
- state.checked.has(it) ? state.checked.delete(it) : state.checked.add(it);
41
+ function lockOrExit(repo, required) {
42
+ const read = loadLock(repo);
43
+ if (read.status === "unreadable") {
44
+ console.error(`Lockfile ${LOCKFILE} is unusable: ${read.reason}.`);
45
+ console.error(`Fix or delete it by hand. Acting on it would risk touching files outside ${join(repo, ".claude")}.`);
46
+ process.exit(2);
631
47
  }
632
- else if (k === "a") {
633
- const kind = state.flat[state.cursor].kind;
634
- const group = state.flat.filter((i) => i.kind === kind);
635
- const allOn = group.every((i) => state.checked.has(i));
636
- group.forEach((i) => (allOn ? state.checked.delete(i) : state.checked.add(i)));
48
+ if (read.status === "absent") {
49
+ if (!required)
50
+ return null;
51
+ console.error(`No lockfile (${LOCKFILE}) - run '${INVOCATION} install ${repo}' first.`);
52
+ process.exit(2);
637
53
  }
638
- else if (k === "return")
639
- return "confirm";
640
- return "continue";
641
- }
642
- function interactiveSelect(items, preChecked) {
643
- const flat = KIND_ORDER.flatMap((k) => items.filter((i) => i.kind === k));
644
- const checked = new Set(preChecked);
645
- let cursor = 0;
646
- // Precompute the descriptions (once)
647
- const detail = buildDetailMap(items);
648
- const render = () => {
649
- const frame = buildSelectorFrame({
650
- flat,
651
- checked,
652
- cursor,
653
- detail,
654
- rows: process.stdout.rows ?? 24,
655
- });
656
- process.stdout.write("\x1b[2J\x1b[H" + frame);
657
- };
658
- return new Promise((resolve) => {
659
- const stdin = process.stdin;
660
- emitKeypressEvents(stdin);
661
- let cleaned = false;
662
- const cleanup = () => {
663
- if (cleaned)
664
- return;
665
- cleaned = true;
666
- process.stdout.write("\x1b[?25h\n");
667
- stdin.setRawMode(false);
668
- stdin.pause();
669
- stdin.removeListener("keypress", onKey);
670
- };
671
- const state = { flat, checked, cursor };
672
- const onKey = (_s, key) => {
673
- try {
674
- const outcome = applySelectorKey(state, key);
675
- cursor = state.cursor; // render() reads the outer binding
676
- if (outcome === "cancel") {
677
- cleanup();
678
- resolve(null);
679
- return;
680
- }
681
- if (outcome === "confirm") {
682
- cleanup();
683
- resolve(flat.filter((i) => checked.has(i)));
684
- return;
685
- }
686
- render();
687
- }
688
- catch {
689
- cleanup();
690
- resolve(null);
691
- }
692
- };
693
- try {
694
- stdin.setRawMode(true);
695
- stdin.resume();
696
- process.stdout.write("\x1b[?25l"); // hide the cursor
697
- render();
698
- stdin.on("keypress", onKey);
699
- }
700
- catch {
701
- cleanup();
702
- resolve(null);
703
- }
704
- });
54
+ return read.lock;
705
55
  }
706
56
  async function doInstall(repo, opts) {
707
57
  if (opts.pickFlag && opts.pick.length === 0) {
@@ -756,7 +106,7 @@ async function doInstall(repo, opts) {
756
106
  }
757
107
  // Preserve deliberately customized (detached) items: never overwrite them on
758
108
  // re-install. They stay recorded as installed but their files are left as-is.
759
- const prevLock = readLock(repo);
109
+ const prevLock = lockOrExit(repo, false);
760
110
  const detached = new Set(prevLock?.detached ?? []);
761
111
  // Pre-existing content we never installed (first install, or a token added since)
762
112
  // is user work: back it up before overwriting instead of silently clobbering it.
@@ -768,12 +118,21 @@ async function doInstall(repo, opts) {
768
118
  nPreserved++;
769
119
  return;
770
120
  }
771
- if (!installedBefore.has(token) && existsSync(dst)) {
772
- cpSync(dst, dst + ".pre-install.bak", { recursive: true });
121
+ // The FIRST backup is the only one that can hold user work; every later one
122
+ // can only degrade it. Any run that does not reach the lockfile - hook
123
+ // wiring throwing, a Ctrl-C, a lockfile deleted by hand - leaves this repo
124
+ // looking untouched on the next run, while `dst` already holds OUR content.
125
+ // Backing up again would then overwrite the real backup with the canonical
126
+ // file, and on a skill directory it silently produces a HYBRID (the user's
127
+ // extra files kept, the same-named ones canonical) - all under a message
128
+ // telling the user to review the backup before deleting it.
129
+ const backup = `${dst}.pre-install.bak`;
130
+ if (!installedBefore.has(token) && existsSync(dst) && !existsSync(backup)) {
131
+ copyPath(dst, backup);
773
132
  nBackedUp++;
774
133
  }
775
134
  // Test procedures (*.test.ts) and eval manifests (eval.yaml) stay in the canonical repo - never distributed.
776
- cpSync(src, dst, recursive ? { recursive: true, filter: (s) => !s.endsWith(".test.ts") && !s.endsWith("eval.yaml") && !s.endsWith("README.md") } : undefined);
135
+ copyPath(src, dst, recursive ? (s) => !s.endsWith(".test.ts") && !s.endsWith("eval.yaml") && !s.endsWith("README.md") : undefined);
777
136
  };
778
137
  const adopted = [];
779
138
  const tokens = [];
@@ -831,28 +190,23 @@ async function doInstall(repo, opts) {
831
190
  mkdirSync(hookDir, { recursive: true });
832
191
  const readmeSrc = join(BUILT_HOOKS, "README.md");
833
192
  if (existsSync(readmeSrc))
834
- cpSync(readmeSrc, join(hookDir, "README.md"));
193
+ copyPath(readmeSrc, join(hookDir, "README.md"));
835
194
  }
836
195
  if (adopted.length) {
837
196
  const manifest = join(dotclaude, "rules/shared/.adopted");
838
- const header = `# Generic rules adopted (ronce-racine). Resync: ${INVOCATION} install --rules-only .\n`;
839
- writeFileSync(manifest, header + adopted.sort().join("\n") + "\n");
197
+ writeFileSync(manifest, `${ADOPTED_HEADER + adopted.sort().join("\n")}\n`);
840
198
  }
841
- // Lockfile: preserves the existing detached list (deliberately customized items).
842
- const lock = {
843
- source: { package: "ronce-racine", version: selfVersion(), contentHash: canonicalHash(tokens) },
844
- installed: tokens.sort(),
845
- detached: prevLock?.detached ?? [],
846
- };
847
- writeFileSync(join(repo, LOCKFILE), JSON.stringify(lock, null, 2) + "\n");
848
199
  console.log(`Installed into ${dotclaude}: ${nRules} rules, ${nSkills} skills, ${nScripts} scripts, ${nAgents} agents${nHooks > 0 ? `, ${nHooks} hook(s)` : ""}.`);
849
200
  if (nPreserved > 0)
850
201
  console.log(`Preserved ${nPreserved} detached (customized) item(s) - left untouched.`);
851
202
  if (nBackedUp > 0)
852
203
  console.log(`⚠ Backed up ${nBackedUp} pre-existing item(s) to *.pre-install.bak - review before deleting (or 'detach' them to keep your version).`);
853
- console.log(`Lockfile: ${LOCKFILE} (${describeSource(lock.source)}) - drift via 'ronce-racine check .'`);
854
204
  if (adopted.length)
855
205
  console.log(`Rules manifest: .claude/rules/shared/.adopted (${adopted.length} rules)`);
206
+ // Hooks BEFORE the lockfile, on purpose. Written first, the lockfile records a
207
+ // complete install even when the wiring below throws, so `check` reports no
208
+ // drift while the hooks the user asked for are absent - a half-install that
209
+ // announces itself as healthy, and stays that way (issue #1).
856
210
  if (collectedWirings.length > 0) {
857
211
  const settingsPath = join(dotclaude, "settings.json");
858
212
  const { added, backedUp, malformed } = mergeHookSettings(dotclaude, collectedWirings);
@@ -864,15 +218,19 @@ async function doInstall(repo, opts) {
864
218
  console.log(`\nHooks already wired in ${settingsPath} - no change.`);
865
219
  console.log(`(details: .claude/hooks/README.md)`);
866
220
  }
221
+ // Lockfile: preserves the existing detached list (deliberately customized items).
222
+ const lock = {
223
+ source: { package: "ronce-racine", version: selfVersion(), contentHash: canonicalHash(tokens) },
224
+ installed: tokens.sort(),
225
+ detached: prevLock?.detached ?? [],
226
+ };
227
+ writeFileSync(join(repo, LOCKFILE), `${JSON.stringify(lock, null, 2)}\n`);
228
+ console.log(`Lockfile: ${LOCKFILE} (${describeSource(lock.source)}) - drift via 'ronce-racine check .'`);
867
229
  console.log(`\nReview the diff then commit (.claude/ travels via git → team + CI).`);
868
230
  }
869
231
  /** Drift control (lenient: warns; --strict: exit 1) and staleness check. */
870
232
  function doCheck(repo, strict) {
871
- const lock = readLock(repo);
872
- if (!lock) {
873
- console.error(`No lockfile (${LOCKFILE}) - run '${INVOCATION} install ${repo}' first.`);
874
- process.exit(2);
875
- }
233
+ const lock = lockOrExit(repo, true);
876
234
  const checked = lock.installed.filter((t) => !lock.detached.includes(t));
877
235
  const drift = checked
878
236
  .map((t) => ({ t, d: compareToken(t, repo) }))
@@ -897,20 +255,63 @@ function doCheck(repo, strict) {
897
255
  }
898
256
  /** Detaches items (removes them from drift control - deliberate customization). */
899
257
  function doDetach(repo, tokensToDetach) {
900
- const lock = readLock(repo);
901
- if (!lock) {
902
- console.error(`No lockfile (${LOCKFILE}).`);
903
- process.exit(2);
904
- }
258
+ const lock = lockOrExit(repo, true);
905
259
  const unknown = tokensToDetach.filter((t) => !lock.installed.includes(t));
906
260
  if (unknown.length) {
907
261
  console.error(`Unknown token(s) (format kind:name): ${unknown.join(", ")}\nInstalled: ${lock.installed.join(", ")}`);
908
262
  process.exit(2);
909
263
  }
910
264
  lock.detached = [...new Set([...lock.detached, ...tokensToDetach])].sort();
911
- writeFileSync(join(repo, LOCKFILE), JSON.stringify(lock, null, 2) + "\n");
265
+ writeFileSync(join(repo, LOCKFILE), `${JSON.stringify(lock, null, 2)}\n`);
912
266
  console.log(`Detached: ${tokensToDetach.join(", ")} - excluded from drift control.`);
913
267
  }
268
+ /**
269
+ * Removes what the lockfile says was installed, and only that.
270
+ *
271
+ * Deliberately not destructive by default in the ways that would hurt: detached
272
+ * items stay, a `.pre-install.bak` is restored over the file it backed up, and
273
+ * the lockfile goes last, so an interruption leaves a state a re-run can finish
274
+ * rather than an orphaned installation no command can find again.
275
+ */
276
+ function doUninstall(repo, opts) {
277
+ // Shape and token validation happen in loadLock, for every command at once.
278
+ const lock = lockOrExit(repo, true);
279
+ const detached = new Set(lock.detached);
280
+ const removable = lock.installed.filter((t) => !detached.has(t));
281
+ // A detached hook is the one the user customized and wants to keep running,
282
+ // so its wiring stays too: unwiring it would leave a hook that never fires.
283
+ const hookFiles = removable.filter((t) => t.startsWith("hook:")).map((t) => t.slice("hook:".length));
284
+ if (opts.dryRun) {
285
+ console.log(`Would remove ${removable.length} artifact(s) from ${join(repo, ".claude")}:`);
286
+ for (const t of removable)
287
+ console.log(` - ${t}${compareToken(t, repo) !== null ? " (locally modified: kept as *.pre-uninstall.bak)" : ""}`);
288
+ if (lock.detached.length)
289
+ console.log(`Would keep ${lock.detached.length} detached item(s), wiring included: ${lock.detached.join(", ")}`);
290
+ console.log(`Would unwire ${hookFiles.length} hook(s) from .claude/settings.json and delete ${LOCKFILE}.`);
291
+ return;
292
+ }
293
+ // Unwire BEFORE deleting, mirroring doInstall: a failure here leaves the
294
+ // lockfile in place, so the command can simply be run again.
295
+ const { removed: unwired, unreadable } = unwireHookSettings(join(repo, ".claude"), hookFiles);
296
+ const result = removeArtifacts(repo, lock.installed, lock.detached);
297
+ // The lockfile goes before the layout sweep, not after: it lives in .claude/
298
+ // itself, so leaving it for last would keep the directory it is meant to let
299
+ // us remove. Everything destructive is already done by this point.
300
+ rmSync(join(repo, LOCKFILE), { force: true });
301
+ cleanupLayout(repo, lock.detached.filter((t) => t.startsWith("rule:")).map((t) => t.slice("rule:".length)));
302
+ console.log(`Removed ${result.removed.length} artifact(s) from ${join(repo, ".claude")}.`);
303
+ if (unwired > 0)
304
+ console.log(`Unwired ${unwired} hook(s) from .claude/settings.json.`);
305
+ if (unreadable)
306
+ console.log(`⚠ .claude/settings.json is not valid JSON - left untouched. Remove the .claude/hooks/*.mjs commands from it by hand, or they will fail on every event.`);
307
+ if (result.backedUp.length)
308
+ console.log(`⚠ ${result.backedUp.length} artifact(s) had local edits - kept as *.pre-uninstall.bak: ${result.backedUp.join(", ")}`);
309
+ if (result.restored.length)
310
+ console.log(`Restored ${result.restored.length} pre-install backup(s) over the file they backed up.`);
311
+ if (result.preserved.length)
312
+ console.log(`Kept ${result.preserved.length} detached (customized) item(s): ${result.preserved.join(", ")}`);
313
+ console.log(`Lockfile deleted. Review the diff then commit.`);
314
+ }
914
315
  /** Collects only the args following "--pick", stopping at the next flag (arg starting with "-"). */
915
316
  function pickTokens(rest) {
916
317
  const start = rest.indexOf("--pick");
@@ -936,9 +337,9 @@ const isMain = (() => {
936
337
  })();
937
338
  if (isMain) {
938
339
  const [cmd, repo, ...rest] = process.argv.slice(2);
939
- const COMMANDS = ["plan", "install", "check", "detach"];
340
+ const COMMANDS = ["plan", "install", "check", "detach", "uninstall"];
940
341
  if (!repo || !COMMANDS.includes(cmd)) {
941
- console.error(`usage: ${INVOCATION} <plan|install|check|detach> <repo> [--all|--yes|--rules-only|--strict|<token...>]`);
342
+ console.error(`usage: ${INVOCATION} <plan|install|check|detach|uninstall> <repo> [--all|--yes|--rules-only|--strict|--dry-run|<token...>]`);
942
343
  process.exit(2);
943
344
  }
944
345
  if (!existsSync(repo)) {
@@ -957,6 +358,8 @@ if (isMain) {
957
358
  });
958
359
  else if (cmd === "check")
959
360
  doCheck(repo, rest.includes("--strict"));
361
+ else if (cmd === "uninstall")
362
+ doUninstall(repo, { dryRun: rest.includes("--dry-run") });
960
363
  else
961
364
  doDetach(repo, rest.filter((a) => !a.startsWith("--")));
962
365
  }