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
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The installer's catalog: what can be installed, and on which signal.
3
+ */
4
+ /**
5
+ * Catalog: the installer's "knowledge" (signal → artifact + reason).
6
+ * An artifact absent from here exists on disk and ships in the package, yet
7
+ * cannot be installed by any command. `tests/installer.test.ts` gates that.
8
+ */
9
+ export const CATALOG = [
10
+ // rules
11
+ { kind: "rule", name: "minimal-code.md", when: ["code"], reason: "YAGNI + readability, any code project" },
12
+ { kind: "rule", name: "commits.md", when: ["git"], reason: "commit message format" },
13
+ { kind: "rule", name: "secure-logging.md", when: ["code"], reason: "GDPR: never log sensitive data" },
14
+ { kind: "rule", name: "pre-commit-secret-detection.md", when: ["git"], reason: "no committed secrets" },
15
+ { kind: "rule", name: "test-discipline.md", when: ["tests"], reason: "tests detected" },
16
+ { kind: "rule", name: "error-handling-discipline.md", when: ["backend", "code"], reason: "no swallowed error / panic" },
17
+ { kind: "rule", name: "subscription-cleanup.md", when: ["frontend"], reason: "frontend: subscription teardown" },
18
+ { kind: "rule", name: "ui-states-complete.md", when: ["frontend"], reason: "frontend: loading/error/empty/success states" },
19
+ { kind: "rule", name: "clean-architecture-deps.md", when: ["backend"], reason: "backend: dependency direction" },
20
+ { kind: "rule", name: "no-raw-sql-interpolation.md", when: ["sql"], reason: "SQL detected: anti-injection" },
21
+ { kind: "rule", name: "sql-migrations-discipline.md", when: ["migrations"], reason: "migrations detected" },
22
+ { kind: "rule", name: "detection-gap-protocol.md", when: ["code"], reason: "P0 found by user = detection failure", optional: true },
23
+ { kind: "rule", name: "doc-code-parity.md", when: ["code"], reason: "docs must match the code they describe" },
24
+ // skills (process / cross-cutting)
25
+ { kind: "skill", name: "recording-decisions", when: "always", reason: "record non-obvious choices" },
26
+ { kind: "skill", name: "domain-glossary", when: ["code"], reason: "one name per concept, written down" },
27
+ { kind: "skill", name: "detection-sweep", when: ["code"], reason: "project detection sweep" },
28
+ { kind: "skill", name: "commit-readiness-review", when: ["git"], reason: "self-review before commit (+ scripts/precommit-scan.ts)" },
29
+ { kind: "skill", name: "merge-request-review", when: ["ci", "git"], reason: "review an MR/PR before merge" },
30
+ { kind: "skill", name: "bug-ticket-root-cause", when: ["git"], reason: "document a bug as a ticket" },
31
+ { kind: "skill", name: "bug-triage-structured", when: ["git"], reason: "full triage of a bug" },
32
+ { kind: "skill", name: "recurring-bug-root-cause", when: ["git"], reason: "recurring bug → root cause" },
33
+ { kind: "skill", name: "daily-workflow-optimization", when: ["code"], reason: "reduce workflow friction", optional: true },
34
+ { kind: "skill", name: "qa-session-intake", when: ["frontend"], reason: "turn a QA session into tickets", optional: true },
35
+ // test skills
36
+ { kind: "skill", name: "writing-robust-tests", when: ["tests", "code"], reason: "write robust tests" },
37
+ { kind: "skill", name: "comprehensive-test-strategy", when: ["tests", "code"], reason: "risk-based test strategy" },
38
+ { kind: "skill", name: "adversarial-feature-challenge", when: ["code"], reason: "adversarial stress-test of a feature" },
39
+ { kind: "skill", name: "validating-features-end-to-end", when: ["code"], reason: "validate a feature before closing" },
40
+ // design / impl skills
41
+ { kind: "skill", name: "domain-modeling-design", when: ["backend"], reason: "model a domain before coding" },
42
+ { kind: "skill", name: "ddd-backend-implementation", when: ["backend"], reason: "implement in DDD layers" },
43
+ { kind: "skill", name: "api-contract-versioning", when: ["backend"], reason: "evolve an API contract" },
44
+ { kind: "skill", name: "database-schema-evolution", when: ["migrations", "sql"], reason: "risky schema migration" },
45
+ // frontend skills
46
+ { kind: "skill", name: "frontend-spec-call-site-audit", when: ["frontend"], reason: "frontend spec before ticket" },
47
+ { kind: "skill", name: "frontend-fullstack-implementation", when: ["frontend"], reason: "implement a frontend feature" },
48
+ { kind: "skill", name: "refactoring-shared-component-api", when: ["frontend"], reason: "change a shared component's API" },
49
+ { kind: "skill", name: "design-system-component-lifecycle", when: ["frontend"], reason: "create/extend a DS component" },
50
+ { kind: "skill", name: "visual-regression-check", when: ["frontend"], reason: "check the rendering before commit" },
51
+ // ops skills
52
+ { kind: "skill", name: "ci-pipeline-orchestration", when: ["ci"], reason: "CI detected: check/diagnose/retry" },
53
+ { kind: "skill", name: "production-incident-diagnostic", when: ["infra"], reason: "infra/deployment: prod incident triage" },
54
+ { kind: "skill", name: "performance-profiling", when: ["code"], reason: "find a bottleneck, prove the fix helped" },
55
+ // audit skills (heavy, optional)
56
+ { kind: "skill", name: "audit-industrialisation", when: ["code"], reason: "maturity audit orchestrator", optional: true },
57
+ { kind: "skill", name: "audit-report", when: ["code"], reason: "audit report template/scoring", optional: true },
58
+ { kind: "skill", name: "audit-security", when: ["backend", "infra"], reason: "application security audit", optional: true },
59
+ { kind: "skill", name: "audit-testing", when: ["tests"], reason: "test strategy audit", optional: true },
60
+ { kind: "skill", name: "audit-ci-cd", when: ["ci"], reason: "CI/CD & release audit", optional: true },
61
+ { kind: "skill", name: "audit-quality", when: ["code"], reason: "code & data quality audit", optional: true },
62
+ { kind: "skill", name: "audit-architecture", when: ["backend"], reason: "architecture & availability audit", optional: true },
63
+ { kind: "skill", name: "audit-observability", when: ["infra", "backend"], reason: "observability & alerting audit", optional: true },
64
+ { kind: "skill", name: "audit-performance-frontend", when: ["frontend"], reason: "low-level frontend perf audit", optional: true },
65
+ { kind: "skill", name: "audit-compliance", when: ["code"], reason: "compliance/GDPR/FinOps audit", optional: true },
66
+ // scripts (standalone, read-only)
67
+ { kind: "script", name: "subscription-leak-scan.ts", when: ["frontend"], reason: "detects subscriptions/listeners/timers without teardown" },
68
+ // hooks
69
+ { kind: "hook", name: "skill-reminder.ts", when: "always", reason: "suggests the relevant skills for the prompt", wiring: [{ event: "UserPromptSubmit", commandFile: "skill-reminder.ts" }] },
70
+ { 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" }] },
71
+ { 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" }] },
72
+ { 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" }] },
73
+ { 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" }] },
74
+ // Opt-in: it spends an API call per push, so it is a cost the adopter accepts
75
+ // rather than inherits.
76
+ { kind: "hook", name: "readme-freshness.ts", when: ["git"], reason: "re-reads the README against what a push changes", optional: true, wiring: [{ event: "PreToolUse", matcher: "Bash", commandFile: "readme-freshness.ts" }] },
77
+ // agents
78
+ { kind: "agent", name: "code-reviewer.md", when: ["git", "code"], reason: "diff review agent" },
79
+ { kind: "agent", name: "qa-tester.md", when: ["tests"], reason: "E2E testing agent" },
80
+ ];
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Stack detection: walks the target repo, turns what it finds into signals, and
3
+ * maps those signals onto the catalog.
4
+ */
5
+ import { readFileSync, existsSync, readdirSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { HERE, SELF, IS_BUILT } from "./paths.js";
8
+ import { CATALOG } from "./catalog.js";
9
+ /** Bounded walk: extensions seen, presence of specs and a migrations folder. */
10
+ export function scan(repo) {
11
+ // Prune `.claude` too: the tool's own installed artifacts (hook/script .ts
12
+ // files) must not be detected as the project's code on a re-install.
13
+ const PRUNE = new Set(["node_modules", ".git", ".claude", "target", "dist", "build", "vendor", ".nuxt", ".next", "coverage"]);
14
+ const exts = new Set();
15
+ let spec = false;
16
+ let migrations = false;
17
+ let budget = 6000;
18
+ const walk = (dir) => {
19
+ if (budget <= 0)
20
+ return;
21
+ let entries;
22
+ try {
23
+ entries = readdirSync(dir, { withFileTypes: true });
24
+ }
25
+ catch {
26
+ return;
27
+ }
28
+ for (const e of entries) {
29
+ if (budget-- <= 0)
30
+ return;
31
+ if (e.isDirectory()) {
32
+ if (PRUNE.has(e.name))
33
+ continue;
34
+ if (/^migrations?$/i.test(e.name) || /^migrate$/i.test(e.name))
35
+ migrations = true;
36
+ walk(join(dir, e.name));
37
+ }
38
+ else {
39
+ const m = /\.[a-z0-9]+$/i.exec(e.name);
40
+ if (m)
41
+ exts.add(m[0].toLowerCase());
42
+ if (/\.(spec|test)\.[tj]sx?$/.test(e.name))
43
+ spec = true;
44
+ }
45
+ }
46
+ };
47
+ walk(repo);
48
+ // No silent caps: on a huge repo the walk stops at the budget - say so, a
49
+ // missed deep signal (migrations/, *.sql) would otherwise look like "not there".
50
+ return { exts, spec, migrations, truncated: budget <= 0 };
51
+ }
52
+ export function detect(repo) {
53
+ const sig = new Set();
54
+ const ev = {};
55
+ const add = (s, why) => {
56
+ if (!sig.has(s)) {
57
+ sig.add(s);
58
+ ev[s] = why;
59
+ }
60
+ };
61
+ const has = (p) => existsSync(join(repo, p));
62
+ if (has(".git"))
63
+ add("git", ".git/");
64
+ if (has(".gitlab-ci.yml") || has(".github/workflows") || has("Jenkinsfile") || has(".circleci/config.yml"))
65
+ add("ci", "CI config");
66
+ if (["Dockerfile", "docker-compose.yml", "docker-compose.yaml", "k8s", "kubernetes", "helm", "terraform"].some(has))
67
+ add("infra", "Docker/infra");
68
+ let deps = [];
69
+ if (has("package.json")) {
70
+ try {
71
+ const p = JSON.parse(readFileSync(join(repo, "package.json"), "utf8"));
72
+ deps = Object.keys({ ...p.dependencies, ...p.devDependencies });
73
+ }
74
+ catch {
75
+ /* ignore */
76
+ }
77
+ }
78
+ const dep = (re) => deps.some((d) => re.test(d));
79
+ if (dep(/^(react|vue|svelte|nuxt|next|@angular|solid-js|preact)/))
80
+ add("frontend", "frontend dependencies");
81
+ if (dep(/^(express|koa|fastify|@nestjs|hapi|@hapi)/))
82
+ add("backend", "Node backend dependencies");
83
+ if (dep(/playwright|cypress/))
84
+ add("tests", "E2E deps");
85
+ if (dep(/vitest|jest|mocha|jasmine|karma/))
86
+ add("tests", "test runner");
87
+ const { exts, spec, migrations, truncated } = scan(repo);
88
+ if (truncated)
89
+ add("scan-truncated", "large repo: detection stopped at the scan budget - deep signals may be missed; pass artifacts explicitly if needed");
90
+ const anyCode = [".ts", ".tsx", ".js", ".jsx", ".vue", ".svelte", ".rs", ".go", ".java", ".py", ".php", ".rb"].some((e) => exts.has(e));
91
+ if (anyCode)
92
+ add("code", "sources detected");
93
+ if ([".vue", ".svelte", ".tsx", ".jsx"].some((e) => exts.has(e)))
94
+ add("frontend", "UI files");
95
+ if ([".rs", ".go", ".java", ".py", ".php"].some((e) => exts.has(e)) || has("Cargo.toml") || has("go.mod") || has("pom.xml"))
96
+ add("backend", "backend sources");
97
+ if (exts.has(".sql"))
98
+ add("sql", "SQL files");
99
+ if (migrations)
100
+ add("migrations", "migrations folder");
101
+ if (spec)
102
+ add("tests", "*.spec/*.test files");
103
+ return { signals: sig, evidence: ev };
104
+ }
105
+ export function isRecommended(item, sig) {
106
+ return item.when === "always" || item.when.some((s) => sig.has(s));
107
+ }
108
+ export function plan(repo) {
109
+ const { signals, evidence } = detect(repo);
110
+ const matched = CATALOG.filter((i) => isRecommended(i, signals));
111
+ return {
112
+ picked: matched.filter((i) => !i.optional),
113
+ optional: matched.filter((i) => i.optional),
114
+ signals,
115
+ evidence,
116
+ };
117
+ }
118
+ export const KIND_LABEL = { rule: "Rules", skill: "Skills", script: "Scripts", hook: "Hooks", agent: "Agents" };
119
+ export function printGroup(title, items) {
120
+ if (!items.length)
121
+ return;
122
+ console.log(`\n${title}`);
123
+ for (const k of ["rule", "skill", "script", "hook", "agent"]) {
124
+ const g = items.filter((i) => i.kind === k);
125
+ if (!g.length)
126
+ continue;
127
+ console.log(` ${KIND_LABEL[k]} (${g.length}) :`);
128
+ for (const i of g)
129
+ console.log(` • ${i.name.replace(/\.md$/, "")} - ${i.reason}`);
130
+ }
131
+ }
132
+ export function doPlan(repo) {
133
+ const { picked, optional, signals, evidence } = plan(repo);
134
+ console.log(`Analysis of ${repo}`);
135
+ console.log(`Signals: ${[...signals].map((s) => `${s} (${evidence[s]})`).join(", ") || "none"}`);
136
+ printGroup("✓ Recommended (installed by default):", picked);
137
+ printGroup("• Optional (add with --all):", optional);
138
+ const invocation = IS_BUILT ? `node ${join(HERE, "install.js")}` : `npx tsx ${join(SELF, "install.ts")}`;
139
+ console.log(`\n→ To install: ${invocation} install ${repo} (add --all for the optional ones)`);
140
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Lockfile, canonical fingerprinting and the copy primitive the installer uses.
3
+ */
4
+ import { readFileSync, existsSync, readdirSync, mkdirSync, copyFileSync, lstatSync, readlinkSync, symlinkSync, rmSync } from "node:fs";
5
+ import { join, dirname } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { SELF, BUILT_HOOKS, LOCKFILE, shippedHookName } from "./paths.js";
8
+ /**
9
+ * Shape a token must have to be turned into a path.
10
+ *
11
+ * The lockfile is a committed file in the TARGET repository, so its tokens are
12
+ * not ours to trust: they arrive from whatever branch the user checked out. A
13
+ * name is therefore a single path segment with no separator and no `..`, which
14
+ * is what keeps `uninstall` from being handed `hook:../../../etc/something` and
15
+ * deleting it.
16
+ */
17
+ const TOKEN_SHAPE = /^(rule|skill|agent|script|hook):[A-Za-z0-9_][A-Za-z0-9._-]*$/;
18
+ export function isValidToken(token) {
19
+ return TOKEN_SHAPE.test(token) && !token.includes("..");
20
+ }
21
+ /** Resolves canonical + target for a "kind:name" token. */
22
+ export function tokenPaths(token, repo) {
23
+ // Callers reading a lockfile filter with isValidToken first and report what
24
+ // they dropped; reaching here with a bad token is a bug, not user input.
25
+ if (!isValidToken(token))
26
+ throw new Error(`refusing to resolve a malformed token: ${JSON.stringify(token)}`);
27
+ const [kind, name] = token.split(":");
28
+ if (kind === "rule")
29
+ return { canon: join(SELF, "rules", name), inst: join(repo, ".claude/rules/shared", name), isDir: false };
30
+ if (kind === "skill")
31
+ return { canon: join(SELF, "skills", name), inst: join(repo, ".claude/skills", name), isDir: true };
32
+ if (kind === "agent")
33
+ return { canon: join(SELF, "agents", name), inst: join(repo, ".claude/agents", name), isDir: false };
34
+ if (kind === "script")
35
+ return { canon: join(SELF, "scripts", name), inst: join(repo, ".claude/scripts", name), isDir: false };
36
+ // kind === "hook": one token per individual file
37
+ return { canon: join(BUILT_HOOKS, shippedHookName(name)), inst: join(repo, ".claude/hooks", shippedHookName(name)), isDir: false };
38
+ }
39
+ /**
40
+ * Fingerprint of the canonical content behind a set of tokens. The lockfile
41
+ * records it next to the package version: with the version alone, `check`
42
+ * compares "0.4.0" to "0.4.0" and reports nothing even when the package
43
+ * content changed under the same number.
44
+ * A missing canonical file (e.g. a hook token before `dist/` is built) is
45
+ * folded in as an explicit absence marker rather than silently skipped, so
46
+ * an unbuilt checkout cannot hash the same as a built one.
47
+ */
48
+ export function canonicalHash(tokens) {
49
+ const h = createHash("sha256");
50
+ for (const token of [...tokens].sort()) {
51
+ const { canon, isDir } = tokenPaths(token, "");
52
+ h.update(token);
53
+ if (!existsSync(canon)) {
54
+ h.update("\0absent");
55
+ continue;
56
+ }
57
+ if (isDir) {
58
+ for (const rel of listFiles(canon).filter((f) => !f.endsWith(".test.ts") && f !== "eval.yaml" && f !== "README.md")) {
59
+ h.update(rel);
60
+ h.update(readFileSync(join(canon, rel)));
61
+ }
62
+ }
63
+ else {
64
+ h.update(readFileSync(canon));
65
+ }
66
+ }
67
+ return `sha256-${h.digest("hex")}`;
68
+ }
69
+ /** Version of the package this CLI belongs to. */
70
+ export function selfVersion() {
71
+ try {
72
+ return JSON.parse(readFileSync(join(SELF, "package.json"), "utf8")).version ?? "0.0.0";
73
+ }
74
+ catch {
75
+ return "0.0.0";
76
+ }
77
+ }
78
+ export function describeSource(s) {
79
+ return typeof s === "string" ? `clone ${s.slice(0, 8)}` : `${s.package}@${s.version}`;
80
+ }
81
+ /** A clone-era lockfile has no version to compare, so it is never stale. */
82
+ export function isStale(s, tokens) {
83
+ if (typeof s === "string")
84
+ return false;
85
+ return s.version !== selfVersion() || s.contentHash !== canonicalHash(tokens);
86
+ }
87
+ /** Names which part actually drifted, so the message is truthful and actionable. */
88
+ export function staleMessage(s, repo) {
89
+ const reinstall = `re-run 'ronce-racine install ${repo}'`;
90
+ if (typeof s !== "string" && s.version !== selfVersion()) {
91
+ return `↑ stale: installed from ${describeSource(s)}, now running ${selfVersion()} - ${reinstall}.`;
92
+ }
93
+ const ver = typeof s === "string" ? describeSource(s) : s.version;
94
+ return `↑ stale: same version (${ver}) but the canonical content changed - ${reinstall}.`;
95
+ }
96
+ /**
97
+ * Recursive copy that overwrites - deliberately NOT fs.cpSync.
98
+ *
99
+ * cpSync fails when the destination already exists AND the absolute path
100
+ * contains a non-ASCII character on Windows: its native override path calls
101
+ * unlink and reports `errno 0, code '', syscall 'unlink'` (reported on
102
+ * Node 24.13.0 / Windows 10, any accented user name - issue #1). Copying onto
103
+ * a non-existent destination works, which is why a first install got far
104
+ * enough to look successful. `copyFileSync` overwrites through a different
105
+ * binding and is unaffected, so every copy here goes through it.
106
+ *
107
+ * `filter` keeps cpSync's semantics: it receives the SOURCE path, and a
108
+ * directory it rejects prunes that whole subtree.
109
+ *
110
+ * `lstat`, not `stat`, and symlinks recreated rather than followed - also
111
+ * cpSync's behavior without `dereference`. This matters on the backup call,
112
+ * which walks the TARGET repo: user content we do not control. A dangling
113
+ * symlink there made `stat` throw ENOENT and aborted the whole install.
114
+ */
115
+ export function copyPath(src, dst, filter) {
116
+ if (filter && !filter(src))
117
+ return;
118
+ const stats = lstatSync(src);
119
+ if (stats.isSymbolicLink()) {
120
+ mkdirSync(dirname(dst), { recursive: true });
121
+ if (existsSync(dst) || lstatSync(dst, { throwIfNoEntry: false }))
122
+ rmSync(dst, { force: true });
123
+ symlinkSync(readlinkSync(src), dst);
124
+ return;
125
+ }
126
+ if (stats.isDirectory()) {
127
+ mkdirSync(dst, { recursive: true });
128
+ for (const e of readdirSync(src, { withFileTypes: true })) {
129
+ copyPath(join(src, e.name), join(dst, e.name), filter);
130
+ }
131
+ return;
132
+ }
133
+ mkdirSync(dirname(dst), { recursive: true });
134
+ copyFileSync(src, dst);
135
+ }
136
+ export function listFiles(root) {
137
+ const out = [];
138
+ const walk = (d, rel) => {
139
+ for (const e of readdirSync(d, { withFileTypes: true })) {
140
+ const r = rel ? `${rel}/${e.name}` : e.name;
141
+ if (e.isDirectory())
142
+ walk(join(d, e.name), r);
143
+ else
144
+ out.push(r);
145
+ }
146
+ };
147
+ if (existsSync(root))
148
+ walk(root, "");
149
+ return out.sort();
150
+ }
151
+ /** null if compliant, otherwise a description of the drift. */
152
+ export function compareToken(token, repo) {
153
+ const { canon, inst, isDir } = tokenPaths(token, repo);
154
+ if (!existsSync(inst))
155
+ return "absent";
156
+ if (!existsSync(canon))
157
+ return "canonical-removed";
158
+ if (!isDir)
159
+ return readFileSync(canon).equals(readFileSync(inst)) ? null : "modified";
160
+ // Test procedures and eval manifests are never distributed (see copyToken) - exclude them from drift.
161
+ const canonFiles = listFiles(canon).filter((f) => !f.endsWith(".test.ts") && f !== "eval.yaml" && f !== "README.md");
162
+ const probs = [
163
+ ...canonFiles.filter((f) => !existsSync(join(inst, f))).map((f) => `-${f}`),
164
+ ...canonFiles.filter((f) => existsSync(join(inst, f)) && !readFileSync(join(canon, f)).equals(readFileSync(join(inst, f)))).map((f) => `~${f}`),
165
+ ...listFiles(inst).filter((f) => !canonFiles.includes(f)).map((f) => `+${f}`),
166
+ ];
167
+ return probs.length ? probs.join(" ") : null;
168
+ }
169
+ const isStringList = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
170
+ /**
171
+ * The single parsing boundary for the lockfile, validation included.
172
+ *
173
+ * Validating inside one command is not enough: the file is committed in the
174
+ * target repository, so every command reads untrusted content and each one that
175
+ * skipped the check either crashed with a stack trace or copied a malformed
176
+ * token forward into a fresh lockfile.
177
+ */
178
+ export function loadLock(repo) {
179
+ const p = join(repo, LOCKFILE);
180
+ if (!existsSync(p))
181
+ return { status: "absent" };
182
+ let parsed;
183
+ try {
184
+ parsed = JSON.parse(readFileSync(p, "utf8"));
185
+ }
186
+ catch (err) {
187
+ return { status: "unreadable", reason: `not valid JSON (${err.message})` };
188
+ }
189
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
190
+ return { status: "unreadable", reason: "not a JSON object" };
191
+ const l = parsed;
192
+ if (!isStringList(l.installed) || !isStringList(l.detached)) {
193
+ return { status: "unreadable", reason: "'installed' and 'detached' must both be lists of strings" };
194
+ }
195
+ const malformed = [...l.installed, ...l.detached].filter((t) => !isValidToken(t));
196
+ if (malformed.length) {
197
+ return { status: "unreadable", reason: `malformed token(s): ${malformed.map((t) => JSON.stringify(t)).join(", ")}` };
198
+ }
199
+ return { status: "ok", lock: { source: l.source, installed: l.installed, detached: l.detached } };
200
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Filesystem anchors shared by every installer module.
3
+ *
4
+ * They live apart from the CLI entrypoint so a split module never has to import
5
+ * install.ts back for a path, which would make the import graph circular.
6
+ */
7
+ import { basename, dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
10
+ // This module runs as src/paths.ts from the repo root, and as dist/src/paths.js
11
+ // once built for npm. Artifacts always live at the root, so climb out of dist/.
12
+ export const IS_BUILT = basename(dirname(MODULE_DIR)) === "dist";
13
+ export const SELF = IS_BUILT ? join(MODULE_DIR, "..", "..") : join(MODULE_DIR, "..");
14
+ /** Directory the CLI entrypoint itself runs from. */
15
+ export const HERE = IS_BUILT ? join(SELF, "dist") : SELF;
16
+ /** How the user invoked this CLI: `install.ts` from a clone, `ronce-racine` from the package. */
17
+ export const INVOCATION = IS_BUILT ? "ronce-racine" : "install.ts";
18
+ export const LOCKFILE = ".claude/.ronce-racine.json";
19
+ /** Header of the generated rules manifest. Written on install, rewritten on uninstall. */
20
+ export const ADOPTED_HEADER = `# Generic rules adopted (ronce-racine). Resync: ${INVOCATION} install --rules-only .\n`;
21
+ // Hooks ship BUILT (dist/hooks/*.mjs), never as TypeScript. Compiling them at
22
+ // run time cost ~490 ms on every prompt and forced tsx onto the target repo;
23
+ // built JS runs in 34 ms on plain node. Build: tools/build.ts.
24
+ export const BUILT_HOOKS = join(SELF, "dist", "hooks");
25
+ export const shippedHookName = (f) => f.replace(/\.ts$/, ".mjs");