ronce-racine 0.5.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 (179) hide show
  1. package/AGENTS.md +90 -0
  2. package/LICENSE +21 -0
  3. package/README.md +281 -0
  4. package/agents/code-reviewer.md +33 -0
  5. package/agents/qa-tester.md +28 -0
  6. package/dist/hooks/README.md +182 -0
  7. package/dist/hooks/bash-npm-silent.mjs +81 -0
  8. package/dist/hooks/session-inject.mjs +53 -0
  9. package/dist/hooks/session-precompact.mjs +36 -0
  10. package/dist/hooks/session-writer.mjs +142 -0
  11. package/dist/hooks/skill-reminder.mjs +89 -0
  12. package/dist/hooks/truncate-bash-output.mjs +46 -0
  13. package/dist/hooks/truncate-output.mjs +88 -0
  14. package/dist/hooks/worktree-env-setup.mjs +123 -0
  15. package/dist/install.js +962 -0
  16. package/docs/adopting-a-repo.md +80 -0
  17. package/docs/architecture.md +76 -0
  18. package/docs/decisions.md +72 -0
  19. package/docs/developing.md +143 -0
  20. package/docs/evaluating-skills.md +41 -0
  21. package/docs/git-worktrees.md +62 -0
  22. package/docs/rules/clean-architecture-deps.md +66 -0
  23. package/docs/rules/commits.md +59 -0
  24. package/docs/rules/detection-gap-protocol.md +55 -0
  25. package/docs/rules/error-handling-discipline.md +62 -0
  26. package/docs/rules/minimal-code.md +58 -0
  27. package/docs/rules/no-raw-sql-interpolation.md +57 -0
  28. package/docs/rules/pre-commit-secret-detection.md +54 -0
  29. package/docs/rules/secure-logging.md +53 -0
  30. package/docs/rules/sql-migrations-discipline.md +58 -0
  31. package/docs/rules/subscription-cleanup.md +63 -0
  32. package/docs/rules/test-discipline.md +66 -0
  33. package/docs/rules/ui-states-complete.md +52 -0
  34. package/docs/templates/SKILL.template.md +66 -0
  35. package/docs/templates/rule.template.md +16 -0
  36. package/docs/writing-a-rule.md +43 -0
  37. package/docs/writing-a-skill.md +118 -0
  38. package/package.json +45 -0
  39. package/rules/clean-architecture-deps.md +20 -0
  40. package/rules/commits.md +16 -0
  41. package/rules/detection-gap-protocol.md +35 -0
  42. package/rules/error-handling-discipline.md +23 -0
  43. package/rules/minimal-code.md +32 -0
  44. package/rules/no-raw-sql-interpolation.md +20 -0
  45. package/rules/pre-commit-secret-detection.md +14 -0
  46. package/rules/secure-logging.md +16 -0
  47. package/rules/sql-migrations-discipline.md +18 -0
  48. package/rules/subscription-cleanup.md +22 -0
  49. package/rules/test-discipline.md +20 -0
  50. package/rules/ui-states-complete.md +23 -0
  51. package/scripts/subscription-leak-scan.ts +53 -0
  52. package/skills/adversarial-feature-challenge/README.md +65 -0
  53. package/skills/adversarial-feature-challenge/SKILL.md +96 -0
  54. package/skills/adversarial-feature-challenge/assets/fuzz-payloads.txt +60 -0
  55. package/skills/adversarial-feature-challenge/templates/challenge-report.md +42 -0
  56. package/skills/api-contract-versioning/README.md +62 -0
  57. package/skills/api-contract-versioning/SKILL.md +76 -0
  58. package/skills/api-contract-versioning/templates/consumer-inventory.md +29 -0
  59. package/skills/audit-architecture/README.md +56 -0
  60. package/skills/audit-architecture/SKILL.md +97 -0
  61. package/skills/audit-architecture/reference/ar-architecture.md +275 -0
  62. package/skills/audit-architecture/reference/di-disponibilite.md +252 -0
  63. package/skills/audit-architecture/reference/im-incidents.md +217 -0
  64. package/skills/audit-architecture/reference/pa-pannes.md +362 -0
  65. package/skills/audit-architecture/reference/re-recuperation.md +300 -0
  66. package/skills/audit-architecture/reference/sc-scalabilite.md +173 -0
  67. package/skills/audit-architecture/reference/su-support.md +180 -0
  68. package/skills/audit-ci-cd/README.md +54 -0
  69. package/skills/audit-ci-cd/SKILL.md +124 -0
  70. package/skills/audit-ci-cd/reference/artefacts.md +39 -0
  71. package/skills/audit-ci-cd/reference/deploiement.md +100 -0
  72. package/skills/audit-ci-cd/reference/dora.md +94 -0
  73. package/skills/audit-ci-cd/reference/iac.md +40 -0
  74. package/skills/audit-ci-cd/reference/pipeline-ci.md +36 -0
  75. package/skills/audit-ci-cd/reference/supply-chain.md +44 -0
  76. package/skills/audit-compliance/README.md +69 -0
  77. package/skills/audit-compliance/SKILL.md +176 -0
  78. package/skills/audit-compliance/reference/conformite-rgpd.md +295 -0
  79. package/skills/audit-compliance/reference/finops.md +318 -0
  80. package/skills/audit-compliance/reference/gouvernance-donnees.md +238 -0
  81. package/skills/audit-industrialisation/README.md +53 -0
  82. package/skills/audit-industrialisation/SKILL.md +251 -0
  83. package/skills/audit-observability/README.md +64 -0
  84. package/skills/audit-observability/SKILL.md +134 -0
  85. package/skills/audit-observability/reference/alerting.md +214 -0
  86. package/skills/audit-observability/reference/logging.md +114 -0
  87. package/skills/audit-observability/reference/metriques.md +166 -0
  88. package/skills/audit-observability/reference/traces-dashboards.md +90 -0
  89. package/skills/audit-performance-frontend/README.md +91 -0
  90. package/skills/audit-performance-frontend/SKILL.md +194 -0
  91. package/skills/audit-performance-frontend/reference/assets-cache-network.md +129 -0
  92. package/skills/audit-performance-frontend/reference/css-rendering-pipeline.md +154 -0
  93. package/skills/audit-performance-frontend/reference/html-critical-path.md +128 -0
  94. package/skills/audit-performance-frontend/reference/js-engine-runtime.md +280 -0
  95. package/skills/audit-performance-frontend/reference/memory-gc.md +126 -0
  96. package/skills/audit-performance-frontend/reference/profiling-tooling.md +98 -0
  97. package/skills/audit-quality/README.md +85 -0
  98. package/skills/audit-quality/SKILL.md +126 -0
  99. package/skills/audit-quality/reference/qa-devops.md +539 -0
  100. package/skills/audit-quality/reference/qu-qualite-donnees.md +402 -0
  101. package/skills/audit-report/README.md +72 -0
  102. package/skills/audit-report/SKILL.md +241 -0
  103. package/skills/audit-report/reference/scoring-model.md +45 -0
  104. package/skills/audit-security/README.md +72 -0
  105. package/skills/audit-security/SKILL.md +140 -0
  106. package/skills/audit-security/reference/auth-identite.md +98 -0
  107. package/skills/audit-security/reference/autorisation.md +66 -0
  108. package/skills/audit-security/reference/chiffrement-tls.md +97 -0
  109. package/skills/audit-security/reference/detection-patching.md +67 -0
  110. package/skills/audit-security/reference/incident-response.md +98 -0
  111. package/skills/audit-security/reference/reseau-conteneurs.md +72 -0
  112. package/skills/audit-security/reference/secrets.md +36 -0
  113. package/skills/audit-testing/README.md +82 -0
  114. package/skills/audit-testing/SKILL.md +131 -0
  115. package/skills/audit-testing/reference/golden-dataset.md +65 -0
  116. package/skills/audit-testing/reference/resilience-chaos.md +93 -0
  117. package/skills/audit-testing/reference/tests-contractuels.md +65 -0
  118. package/skills/audit-testing/reference/tests-e2e-flaky.md +67 -0
  119. package/skills/audit-testing/reference/tests-unit-integ-ci.md +125 -0
  120. package/skills/bug-ticket-root-cause/README.md +67 -0
  121. package/skills/bug-ticket-root-cause/SKILL.md +86 -0
  122. package/skills/bug-ticket-root-cause/templates/bug-ticket.md +43 -0
  123. package/skills/bug-triage-structured/README.md +63 -0
  124. package/skills/bug-triage-structured/SKILL.md +104 -0
  125. package/skills/bug-triage-structured/templates/bug-triage.md +38 -0
  126. package/skills/ci-pipeline-orchestration/README.md +55 -0
  127. package/skills/ci-pipeline-orchestration/SKILL.md +110 -0
  128. package/skills/commit-readiness-review/README.md +66 -0
  129. package/skills/commit-readiness-review/SKILL.md +82 -0
  130. package/skills/commit-readiness-review/scripts/precommit-scan.ts +81 -0
  131. package/skills/comprehensive-test-strategy/README.md +64 -0
  132. package/skills/comprehensive-test-strategy/SKILL.md +108 -0
  133. package/skills/comprehensive-test-strategy/reference/testing-advanced.md +85 -0
  134. package/skills/daily-workflow-optimization/README.md +56 -0
  135. package/skills/daily-workflow-optimization/SKILL.md +80 -0
  136. package/skills/database-schema-evolution/README.md +54 -0
  137. package/skills/database-schema-evolution/SKILL.md +107 -0
  138. package/skills/ddd-backend-implementation/README.md +63 -0
  139. package/skills/ddd-backend-implementation/SKILL.md +95 -0
  140. package/skills/design-system-component-lifecycle/README.md +56 -0
  141. package/skills/design-system-component-lifecycle/SKILL.md +97 -0
  142. package/skills/design-system-component-lifecycle/templates/component-contract.md +43 -0
  143. package/skills/detection-sweep/README.md +58 -0
  144. package/skills/detection-sweep/SKILL.md +93 -0
  145. package/skills/detection-sweep/scripts/sweep.ts +80 -0
  146. package/skills/domain-modeling-design/README.md +57 -0
  147. package/skills/domain-modeling-design/SKILL.md +83 -0
  148. package/skills/frontend-fullstack-implementation/README.md +60 -0
  149. package/skills/frontend-fullstack-implementation/SKILL.md +133 -0
  150. package/skills/frontend-spec-call-site-audit/README.md +66 -0
  151. package/skills/frontend-spec-call-site-audit/SKILL.md +82 -0
  152. package/skills/frontend-spec-call-site-audit/scripts/audit-entry-points.ts +79 -0
  153. package/skills/frontend-spec-call-site-audit/templates/ticket-frontend.md +32 -0
  154. package/skills/merge-request-review/README.md +60 -0
  155. package/skills/merge-request-review/SKILL.md +77 -0
  156. package/skills/merge-request-review/templates/mr-review-report.md +29 -0
  157. package/skills/production-incident-diagnostic/README.md +63 -0
  158. package/skills/production-incident-diagnostic/SKILL.md +103 -0
  159. package/skills/production-incident-diagnostic/templates/incident-report.md +33 -0
  160. package/skills/qa-session-intake/README.md +56 -0
  161. package/skills/qa-session-intake/SKILL.md +78 -0
  162. package/skills/recording-decisions/README.md +91 -0
  163. package/skills/recording-decisions/SKILL.md +84 -0
  164. package/skills/recurring-bug-root-cause/README.md +64 -0
  165. package/skills/recurring-bug-root-cause/SKILL.md +93 -0
  166. package/skills/recurring-bug-root-cause/scripts/detect-recurring-fixes.ts +46 -0
  167. package/skills/recurring-bug-root-cause/templates/postmortem-recidive.md +37 -0
  168. package/skills/refactoring-shared-component-api/README.md +50 -0
  169. package/skills/refactoring-shared-component-api/SKILL.md +84 -0
  170. package/skills/refactoring-shared-component-api/scripts/sweep-call-sites.ts +85 -0
  171. package/skills/refactoring-shared-component-api/templates/migration-checklist.md +19 -0
  172. package/skills/validating-features-end-to-end/README.md +50 -0
  173. package/skills/validating-features-end-to-end/SKILL.md +90 -0
  174. package/skills/visual-regression-check/README.md +51 -0
  175. package/skills/visual-regression-check/SKILL.md +89 -0
  176. package/skills/writing-robust-tests/README.md +53 -0
  177. package/skills/writing-robust-tests/SKILL.md +88 -0
  178. package/templates/.adopted.example +8 -0
  179. package/templates/anti-drift.gitlab-ci.yml +23 -0
@@ -0,0 +1,962 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Smart installer of the generic Claude config into a target repo.
4
+ *
5
+ * npx tsx install.ts plan <repo> analyzes the project and SUGGESTS what to install (read-only)
6
+ * npx tsx install.ts install <repo> [--all] [--yes] interactive selector (TTY); --all pre-checks everything, --yes installs the default without prompting
7
+ *
8
+ * "Smart" = detects the stack (frontend/backend/tests/SQL/migrations/CI/infra/git)
9
+ * and recommends only the relevant artifacts, each with a reason. Copies:
10
+ * rules → <repo>/.claude/rules/shared/ (+ .adopted manifest)
11
+ * skills → <repo>/.claude/skills/<name>/
12
+ * scripts → <repo>/.claude/scripts/
13
+ * hooks → <repo>/.claude/hooks/
14
+ * agents → <repo>/.claude/agents/
15
+ * and prints the settings.json snippet to wire up the hooks.
16
+ */
17
+ import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync, cpSync, realpathSync } from "node:fs";
18
+ import { join, dirname, basename } from "node:path";
19
+ 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
+ }
616
+ /**
617
+ * Applies one keypress to the selector state (mutated in place).
618
+ * Returns "continue", "confirm" (enter) or "cancel" (q / ctrl-c).
619
+ */
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);
631
+ }
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)));
637
+ }
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
+ });
705
+ }
706
+ async function doInstall(repo, opts) {
707
+ if (opts.pickFlag && opts.pick.length === 0) {
708
+ console.error("--pick requires at least one token (kind:name), e.g. --pick skill:detection-sweep");
709
+ process.exit(2);
710
+ }
711
+ let { picked, optional } = plan(repo);
712
+ if (opts.rulesOnly) {
713
+ picked = picked.filter((i) => i.kind === "rule");
714
+ optional = optional.filter((i) => i.kind === "rule");
715
+ }
716
+ if (opts.pick.length) {
717
+ const tokenOf = (i) => `${i.kind}:${i.name.replace(/\.md$/, "")}`;
718
+ const unknown = opts.pick.filter((t) => !CATALOG.some((i) => tokenOf(i) === t || `${i.kind}:${i.name}` === t));
719
+ if (unknown.length) {
720
+ console.error(`Unknown pick token(s): ${unknown.join(", ")}`);
721
+ process.exit(2);
722
+ }
723
+ // --rules-only restricts --pick to the rules-only set: a non-rule pick token errors rather than being silently installed anyway.
724
+ if (opts.rulesOnly) {
725
+ const nonRule = opts.pick.filter((t) => !t.startsWith("rule:"));
726
+ if (nonRule.length) {
727
+ console.error(`--rules-only restricts --pick to rule:* tokens; got: ${nonRule.join(", ")}`);
728
+ process.exit(2);
729
+ }
730
+ }
731
+ picked = CATALOG.filter((i) => opts.pick.some((t) => tokenOf(i) === t || `${i.kind}:${i.name}` === t));
732
+ optional = [];
733
+ }
734
+ const candidates = [...picked, ...optional];
735
+ const preChecked = new Set(opts.all ? candidates : picked);
736
+ let items;
737
+ if (opts.yes || !process.stdin.isTTY) {
738
+ items = [...preChecked];
739
+ }
740
+ else {
741
+ const sel = await interactiveSelect(candidates, preChecked);
742
+ if (sel === null) {
743
+ console.log("Cancelled - nothing installed.");
744
+ return;
745
+ }
746
+ items = sel;
747
+ }
748
+ if (!items.length) {
749
+ console.log("No item selected - nothing installed.");
750
+ return;
751
+ }
752
+ const dotclaude = join(repo, ".claude");
753
+ if (items.some((i) => i.kind === "hook") && !existsSync(BUILT_HOOKS)) {
754
+ console.error("Hooks are not built. Run 'npm install' (or 'npm run build') in the ronce-racine checkout first.");
755
+ process.exit(2);
756
+ }
757
+ // Preserve deliberately customized (detached) items: never overwrite them on
758
+ // re-install. They stay recorded as installed but their files are left as-is.
759
+ const prevLock = readLock(repo);
760
+ const detached = new Set(prevLock?.detached ?? []);
761
+ // Pre-existing content we never installed (first install, or a token added since)
762
+ // is user work: back it up before overwriting instead of silently clobbering it.
763
+ const installedBefore = new Set(prevLock?.installed ?? []);
764
+ let nPreserved = 0;
765
+ let nBackedUp = 0;
766
+ const copyToken = (token, src, dst, recursive = false) => {
767
+ if (detached.has(token)) {
768
+ nPreserved++;
769
+ return;
770
+ }
771
+ if (!installedBefore.has(token) && existsSync(dst)) {
772
+ cpSync(dst, dst + ".pre-install.bak", { recursive: true });
773
+ nBackedUp++;
774
+ }
775
+ // 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);
777
+ };
778
+ const adopted = [];
779
+ const tokens = [];
780
+ let nRules = 0;
781
+ let nSkills = 0;
782
+ let nScripts = 0;
783
+ let nAgents = 0;
784
+ let nHooks = 0;
785
+ const collectedWirings = [];
786
+ for (const i of items) {
787
+ if (i.kind === "rule") {
788
+ tokens.push(`rule:${i.name}`);
789
+ const dst = join(dotclaude, "rules/shared");
790
+ mkdirSync(dst, { recursive: true });
791
+ copyToken(`rule:${i.name}`, join(SELF, "rules", i.name), join(dst, i.name));
792
+ adopted.push(i.name);
793
+ nRules++;
794
+ }
795
+ else if (i.kind === "skill") {
796
+ tokens.push(`skill:${i.name}`);
797
+ const dst = join(dotclaude, "skills", i.name);
798
+ copyToken(`skill:${i.name}`, join(SELF, "skills", i.name), dst, true);
799
+ nSkills++;
800
+ }
801
+ else if (i.kind === "agent") {
802
+ tokens.push(`agent:${i.name}`);
803
+ const dst = join(dotclaude, "agents");
804
+ mkdirSync(dst, { recursive: true });
805
+ copyToken(`agent:${i.name}`, join(SELF, "agents", i.name), join(dst, i.name));
806
+ nAgents++;
807
+ }
808
+ else if (i.kind === "script") {
809
+ tokens.push(`script:${i.name}`);
810
+ const dst = join(dotclaude, "scripts");
811
+ mkdirSync(dst, { recursive: true });
812
+ copyToken(`script:${i.name}`, join(SELF, "scripts", i.name), join(dst, i.name));
813
+ nScripts++;
814
+ }
815
+ else if (i.kind === "hook") {
816
+ // One token per copied file (no generic token, to avoid duplicates)
817
+ const hookDir = join(dotclaude, "hooks");
818
+ mkdirSync(hookDir, { recursive: true });
819
+ for (const fileName of i.files ?? [i.name]) {
820
+ copyToken(`hook:${fileName}`, join(BUILT_HOOKS, shippedHookName(fileName)), join(hookDir, shippedHookName(fileName)));
821
+ tokens.push(`hook:${fileName}`);
822
+ }
823
+ if (i.wiring)
824
+ collectedWirings.push(...i.wiring);
825
+ nHooks++;
826
+ }
827
+ }
828
+ // Copy README.md once if at least one hook is installed
829
+ if (nHooks > 0) {
830
+ const hookDir = join(dotclaude, "hooks");
831
+ mkdirSync(hookDir, { recursive: true });
832
+ const readmeSrc = join(BUILT_HOOKS, "README.md");
833
+ if (existsSync(readmeSrc))
834
+ cpSync(readmeSrc, join(hookDir, "README.md"));
835
+ }
836
+ if (adopted.length) {
837
+ 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");
840
+ }
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
+ console.log(`Installed into ${dotclaude}: ${nRules} rules, ${nSkills} skills, ${nScripts} scripts, ${nAgents} agents${nHooks > 0 ? `, ${nHooks} hook(s)` : ""}.`);
849
+ if (nPreserved > 0)
850
+ console.log(`Preserved ${nPreserved} detached (customized) item(s) - left untouched.`);
851
+ if (nBackedUp > 0)
852
+ 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
+ if (adopted.length)
855
+ console.log(`Rules manifest: .claude/rules/shared/.adopted (${adopted.length} rules)`);
856
+ if (collectedWirings.length > 0) {
857
+ const settingsPath = join(dotclaude, "settings.json");
858
+ const { added, backedUp, malformed } = mergeHookSettings(dotclaude, collectedWirings);
859
+ if (malformed)
860
+ console.log(`\n⚠ ${settingsPath} was not valid JSON (or its hooks section had an unexpected shape) - backed up to settings.json.bak and rewritten.`);
861
+ if (added > 0)
862
+ console.log(`${malformed ? "" : "\n"}Wired ${added} hook(s) into ${settingsPath}${backedUp && !malformed ? " (backup: settings.json.bak)" : ""}.`);
863
+ else if (!malformed)
864
+ console.log(`\nHooks already wired in ${settingsPath} - no change.`);
865
+ console.log(`(details: .claude/hooks/README.md)`);
866
+ }
867
+ console.log(`\nReview the diff then commit (.claude/ travels via git → team + CI).`);
868
+ }
869
+ /** Drift control (lenient: warns; --strict: exit 1) and staleness check. */
870
+ 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
+ }
876
+ const checked = lock.installed.filter((t) => !lock.detached.includes(t));
877
+ const drift = checked
878
+ .map((t) => ({ t, d: compareToken(t, repo) }))
879
+ .filter((x) => x.d !== null);
880
+ for (const { t, d } of drift)
881
+ console.log(`⚠ drift ${t}: ${d}`);
882
+ if (lock.detached.length)
883
+ console.log(`(${lock.detached.length} detached item(s) ignored: ${lock.detached.join(", ")})`);
884
+ // The stored hash covers the FULL installed set (see doInstall), so detaching
885
+ // items must not change the comparison basis - compare against lock.installed,
886
+ // not the detach-filtered `checked` list, or staleness would never clear.
887
+ const stale = isStale(lock.source, lock.installed);
888
+ if (stale)
889
+ console.log(staleMessage(lock.source, repo));
890
+ if (!drift.length) {
891
+ console.log(`✓ ${checked.length} artifacts match the canonical source${stale ? " (but stale)" : ""}.`);
892
+ return;
893
+ }
894
+ console.log(`\n${drift.length} drifted artifact(s). To make a customization official: '${INVOCATION} detach ${repo} <token>'. To resync: '${INVOCATION} install ${repo}'.`);
895
+ if (strict)
896
+ process.exit(1);
897
+ }
898
+ /** Detaches items (removes them from drift control - deliberate customization). */
899
+ function doDetach(repo, tokensToDetach) {
900
+ const lock = readLock(repo);
901
+ if (!lock) {
902
+ console.error(`No lockfile (${LOCKFILE}).`);
903
+ process.exit(2);
904
+ }
905
+ const unknown = tokensToDetach.filter((t) => !lock.installed.includes(t));
906
+ if (unknown.length) {
907
+ console.error(`Unknown token(s) (format kind:name): ${unknown.join(", ")}\nInstalled: ${lock.installed.join(", ")}`);
908
+ process.exit(2);
909
+ }
910
+ lock.detached = [...new Set([...lock.detached, ...tokensToDetach])].sort();
911
+ writeFileSync(join(repo, LOCKFILE), JSON.stringify(lock, null, 2) + "\n");
912
+ console.log(`Detached: ${tokensToDetach.join(", ")} - excluded from drift control.`);
913
+ }
914
+ /** Collects only the args following "--pick", stopping at the next flag (arg starting with "-"). */
915
+ function pickTokens(rest) {
916
+ const start = rest.indexOf("--pick");
917
+ if (start === -1)
918
+ return [];
919
+ const tokens = [];
920
+ for (let i = start + 1; i < rest.length && !rest[i].startsWith("-"); i++)
921
+ tokens.push(rest[i]);
922
+ return tokens;
923
+ }
924
+ // Only run the CLI when launched directly (the module stays importable in tests).
925
+ // Compares REAL paths: npm/npx install `bin` as a symlink, so process.argv[1]
926
+ // stays the symlink path while import.meta.url is already resolved - a direct
927
+ // string comparison never matches through that symlink and the CLI silently
928
+ // no-ops (exit 0, nothing printed).
929
+ const isMain = (() => {
930
+ try {
931
+ return realpathSync(process.argv[1] ?? "") === realpathSync(fileURLToPath(import.meta.url));
932
+ }
933
+ catch {
934
+ return false;
935
+ }
936
+ })();
937
+ if (isMain) {
938
+ const [cmd, repo, ...rest] = process.argv.slice(2);
939
+ const COMMANDS = ["plan", "install", "check", "detach"];
940
+ if (!repo || !COMMANDS.includes(cmd)) {
941
+ console.error(`usage: ${INVOCATION} <plan|install|check|detach> <repo> [--all|--yes|--rules-only|--strict|<token...>]`);
942
+ process.exit(2);
943
+ }
944
+ if (!existsSync(repo)) {
945
+ console.error(`repo not found: ${repo}`);
946
+ process.exit(2);
947
+ }
948
+ if (cmd === "plan")
949
+ doPlan(repo);
950
+ else if (cmd === "install")
951
+ await doInstall(repo, {
952
+ all: rest.includes("--all"),
953
+ yes: rest.includes("--yes") || rest.includes("-y"),
954
+ rulesOnly: rest.includes("--rules-only"),
955
+ pick: pickTokens(rest),
956
+ pickFlag: rest.includes("--pick"),
957
+ });
958
+ else if (cmd === "check")
959
+ doCheck(repo, rest.includes("--strict"));
960
+ else
961
+ doDetach(repo, rest.filter((a) => !a.startsWith("--")));
962
+ }