@primitive.ai/prim 0.1.0-alpha.12 → 0.1.0-alpha.121

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 (57) hide show
  1. package/README.md +550 -38
  2. package/SKILL.md +320 -75
  3. package/assets/primitive-gameplan/SKILL.md +134 -0
  4. package/assets/primitive-gameplan/claude-hooks.json +28 -0
  5. package/assets/primitive-gameplan/scripts/activate.mjs +37 -0
  6. package/dist/chunk-2DNC2MUN.js +503 -0
  7. package/dist/chunk-2PFJJO2M.js +262 -0
  8. package/dist/chunk-4GLVJLEQ.js +55 -0
  9. package/dist/chunk-4GYJHN26.js +1440 -0
  10. package/dist/chunk-6DEROXLM.js +22695 -0
  11. package/dist/chunk-7LXRFXZG.js +1992 -0
  12. package/dist/chunk-AKGRY7OU.js +1572 -0
  13. package/dist/chunk-BHT6X3T5.js +1450 -0
  14. package/dist/chunk-DQ4I3FLF.js +164 -0
  15. package/dist/chunk-DVHD6LBQ.js +258 -0
  16. package/dist/chunk-EZXEWFDG.js +210 -0
  17. package/dist/chunk-HG7FJK7R.js +253 -0
  18. package/dist/chunk-JSBRDJBE.js +30 -0
  19. package/dist/chunk-JXRJLHE4.js +168 -0
  20. package/dist/chunk-JZC2LHS6.js +209 -0
  21. package/dist/chunk-KZB4ABIB.js +13 -0
  22. package/dist/chunk-LQLP26RL.js +459 -0
  23. package/dist/chunk-M4NZJCPQ.js +135 -0
  24. package/dist/chunk-MRDY7VQP.js +96 -0
  25. package/dist/chunk-NMZSCSMY.js +157 -0
  26. package/dist/chunk-NQZLXYTW.js +36 -0
  27. package/dist/chunk-OXW6PSPT.js +439 -0
  28. package/dist/chunk-OYHYCK4K.js +13 -0
  29. package/dist/chunk-S3ZIMGXV.js +844 -0
  30. package/dist/chunk-WN7OURQ3.js +175 -0
  31. package/dist/daemon/server.js +26506 -0
  32. package/dist/hook-runtime/daemon/server.js +26507 -0
  33. package/dist/hook-runtime/hooks/post-commit.js +23898 -0
  34. package/dist/hook-runtime/hooks/post-rewrite.js +23797 -0
  35. package/dist/hook-runtime/hooks/post-tool-use.js +36213 -0
  36. package/dist/hook-runtime/hooks/pre-commit.js +1741 -0
  37. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +35071 -0
  38. package/dist/hook-runtime/hooks/pre-tool-use.js +96 -0
  39. package/dist/hook-runtime/hooks/prim-hook.js +36273 -0
  40. package/dist/hook-runtime/hooks/session-end.js +1250 -0
  41. package/dist/hook-runtime/hooks/session-start.js +34021 -0
  42. package/dist/hook-runtime/index.js +71700 -0
  43. package/dist/hook-runtime/statusline-main.js +954 -0
  44. package/dist/hooks/post-commit.js +197 -0
  45. package/dist/hooks/post-rewrite.js +206 -0
  46. package/dist/hooks/post-tool-use.js +295 -0
  47. package/dist/hooks/pre-commit.js +16 -108
  48. package/dist/hooks/pre-tool-use-worker.js +238 -0
  49. package/dist/hooks/pre-tool-use.js +87 -0
  50. package/dist/hooks/prim-hook.js +245 -0
  51. package/dist/hooks/session-end.js +67 -0
  52. package/dist/hooks/session-start.js +312 -0
  53. package/dist/index.js +11249 -572
  54. package/dist/statusline-main.js +953 -0
  55. package/package.json +51 -17
  56. package/skills/prim-welcome/SKILL.md +197 -0
  57. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,1992 @@
1
+ import {
2
+ unattendedEnv
3
+ } from "./chunk-OYHYCK4K.js";
4
+ import {
5
+ GIT_HOOK_CONTRACT_VERSION,
6
+ blockMarkers,
7
+ canonicalHookBlock,
8
+ cursorConfigDirectory,
9
+ hookBlockContractVersion,
10
+ inspectGitHookEntrypoint,
11
+ managedHookBlock
12
+ } from "./chunk-AKGRY7OU.js";
13
+ import {
14
+ HttpError,
15
+ getClient
16
+ } from "./chunk-S3ZIMGXV.js";
17
+ import {
18
+ atomicWriteFile,
19
+ binFile,
20
+ compareSemver,
21
+ gitToplevel,
22
+ githubRepositoryFullName,
23
+ isValidRepoSyncId,
24
+ pinnedHookCommand,
25
+ pinnedNpxCommand,
26
+ primConfigDirectory,
27
+ setRepoSyncId,
28
+ setRepositoryBindingState,
29
+ withFileLock
30
+ } from "./chunk-4GYJHN26.js";
31
+
32
+ // src/commands/skill.ts
33
+ import { createHash as createHash3 } from "crypto";
34
+ import {
35
+ constants as constants2,
36
+ closeSync as closeSync2,
37
+ existsSync as existsSync3,
38
+ fstatSync as fstatSync2,
39
+ lstatSync as lstatSync3,
40
+ openSync as openSync2,
41
+ readFileSync as readFileSync3,
42
+ readSync as readSync2,
43
+ readdirSync as readdirSync3,
44
+ rmdirSync as rmdirSync3,
45
+ unlinkSync as unlinkSync2
46
+ } from "fs";
47
+ import { homedir as homedir3 } from "os";
48
+ import { dirname as dirname3, join as join3, resolve as resolve2 } from "path";
49
+ import { fileURLToPath as fileURLToPath2 } from "url";
50
+ import { createPatch } from "diff";
51
+ import { parse as parseYaml2 } from "yaml";
52
+
53
+ // src/output.ts
54
+ function printJson(data) {
55
+ console.log(JSON.stringify(data, null, 2));
56
+ }
57
+
58
+ // src/commands/claude-plugin.ts
59
+ import { createHash as createHash2 } from "crypto";
60
+ import {
61
+ constants,
62
+ closeSync,
63
+ existsSync as existsSync2,
64
+ fstatSync,
65
+ lstatSync as lstatSync2,
66
+ mkdirSync,
67
+ openSync,
68
+ readFileSync as readFileSync2,
69
+ readSync,
70
+ readdirSync as readdirSync2,
71
+ realpathSync,
72
+ rmSync,
73
+ rmdirSync as rmdirSync2
74
+ } from "fs";
75
+ import { homedir as homedir2 } from "os";
76
+ import { dirname as dirname2, isAbsolute, join as join2, relative, resolve, sep } from "path";
77
+ import { fileURLToPath } from "url";
78
+ import { parse as parseYaml } from "yaml";
79
+
80
+ // src/commands/welcome-skill.ts
81
+ import { createHash } from "crypto";
82
+ import { existsSync, lstatSync, readFileSync, readdirSync, rmdirSync, unlinkSync } from "fs";
83
+ import { homedir } from "os";
84
+ import { dirname, join } from "path";
85
+ var WELCOME_SKILL_SOURCE = join("skills", "prim-welcome", "SKILL.md");
86
+ var OWNER = "@primitive.ai/prim";
87
+ var MANIFEST = ".prim-owned.json";
88
+ var digest = (content) => createHash("sha256").update(content).digest("hex");
89
+ var manifestPath = (skillPath) => join(dirname(skillPath), MANIFEST);
90
+ function leafKind(path) {
91
+ try {
92
+ return lstatSync(path).isFile() ? "file" : "foreign";
93
+ } catch (error) {
94
+ if (error.code === "ENOENT") return "missing";
95
+ throw error;
96
+ }
97
+ }
98
+ function codexWelcomeSkillPath() {
99
+ return join(homedir(), ".agents", "skills", "prim-welcome", "SKILL.md");
100
+ }
101
+ function welcomeSkillStatus(skillPath) {
102
+ const skillKind = leafKind(skillPath);
103
+ const manifestKind = leafKind(manifestPath(skillPath));
104
+ let manifest;
105
+ if (manifestKind === "file")
106
+ try {
107
+ const value = JSON.parse(readFileSync(manifestPath(skillPath), "utf8"));
108
+ if (value.version === 1 && value.owner === OWNER && /^[a-f0-9]{64}$/u.test(value.contentSha256 ?? ""))
109
+ manifest = value;
110
+ } catch {
111
+ }
112
+ const content = skillKind === "file" ? readFileSync(skillPath, "utf8") : void 0;
113
+ const owned = manifest !== void 0;
114
+ const installed = manifest !== void 0 && content !== void 0 && digest(content) === manifest.contentSha256;
115
+ return {
116
+ installed,
117
+ owned,
118
+ edited: owned && content !== void 0 && !installed,
119
+ target: skillPath,
120
+ content,
121
+ unsafe: skillKind === "foreign" || manifestKind === "foreign"
122
+ };
123
+ }
124
+ function installWelcomeSkill(skillPath, content, dryRun = false) {
125
+ const status = welcomeSkillStatus(skillPath);
126
+ const foreignManifest = existsSync(manifestPath(skillPath)) && !status.owned;
127
+ if (status.unsafe || foreignManifest || status.edited || !status.owned && status.content !== void 0 && status.content !== content) {
128
+ console.error(`Refusing to overwrite a foreign or edited welcome skill at ${skillPath}`);
129
+ return 1;
130
+ }
131
+ if (status.installed && status.content === content) return 0;
132
+ if (dryRun) {
133
+ console.log(`Would write welcome skill to ${skillPath}`);
134
+ return 0;
135
+ }
136
+ const manifest = { version: 1, owner: OWNER, contentSha256: digest(content) };
137
+ atomicWriteFile(skillPath, content, { ensureParent: true });
138
+ atomicWriteFile(manifestPath(skillPath), `${JSON.stringify(manifest, null, 2)}
139
+ `, {
140
+ ensureParent: true
141
+ });
142
+ console.log(`Installed prim-welcome skill at ${skillPath}`);
143
+ return 0;
144
+ }
145
+ function uninstallWelcomeSkill(skillPath) {
146
+ const status = welcomeSkillStatus(skillPath);
147
+ if (status.unsafe) {
148
+ console.error(`Refusing to remove a non-file welcome skill at ${skillPath}`);
149
+ return 1;
150
+ }
151
+ if (!status.owned) return 0;
152
+ if (status.edited) {
153
+ console.error(`Refusing to remove an edited welcome skill at ${skillPath}`);
154
+ return 1;
155
+ }
156
+ if (existsSync(skillPath)) unlinkSync(skillPath);
157
+ unlinkSync(manifestPath(skillPath));
158
+ if (readdirSync(dirname(skillPath)).length === 0) rmdirSync(dirname(skillPath));
159
+ console.log(`Removed prim-welcome skill from ${skillPath}`);
160
+ return 0;
161
+ }
162
+
163
+ // src/commands/claude-plugin.ts
164
+ var __dirname = dirname2(fileURLToPath(import.meta.url));
165
+ var PLUGIN_DESCRIPTION = "Primitive decision-graph guidance for the prim CLI \u2014 a model-invoked skill installed by prim skill install.";
166
+ var MAX_MANIFEST_BYTES = 64 * 1024;
167
+ var MAX_SKILL_BYTES = 1024 * 1024;
168
+ var REFRESH_LOCK_TIMEOUT_MS = 150;
169
+ var REFRESH_LOCK_POLL_MS = 10;
170
+ function pluginDirFor(cwd, scope) {
171
+ const base = scope === "user" ? join2(homedir2(), ".claude") : join2(gitToplevel(cwd) ?? cwd, ".claude");
172
+ return join2(base, "skills", "prim");
173
+ }
174
+ function resolvePluginDir(cwd, scope) {
175
+ if (scope && scope !== "user" && scope !== "project") {
176
+ console.error(`Unknown --scope "${scope}" (expected user or project)`);
177
+ return null;
178
+ }
179
+ return pluginDirFor(cwd, scope === "user" ? "user" : "project");
180
+ }
181
+ function packageVersion() {
182
+ let dir = __dirname;
183
+ while (dir !== dirname2(dir)) {
184
+ const p = resolve(dir, "package.json");
185
+ if (existsSync2(p)) return JSON.parse(readFileSync2(p, "utf-8")).version;
186
+ dir = dirname2(dir);
187
+ }
188
+ return "0.0.0";
189
+ }
190
+ function pluginManifest(version) {
191
+ const manifest = { name: "prim", description: PLUGIN_DESCRIPTION, version };
192
+ return `${JSON.stringify(manifest, null, 2)}
193
+ `;
194
+ }
195
+ function renderClaudePlugin() {
196
+ const version = packageVersion();
197
+ return { manifest: pluginManifest(version), skill: loadSkill(), version };
198
+ }
199
+ function welcomeSkillPath(pluginDir) {
200
+ return join2(dirname2(pluginDir), "prim-welcome", "SKILL.md");
201
+ }
202
+ function welcomeSkillPathFor(cwd, scope) {
203
+ return welcomeSkillPath(pluginDirFor(cwd, scope));
204
+ }
205
+ function removeDirIfEmpty(dir) {
206
+ if (existsSync2(dir) && readdirSync2(dir).length === 0) rmdirSync2(dir);
207
+ }
208
+ function pluginPaths(dir) {
209
+ return {
210
+ manifestPath: join2(dir, ".claude-plugin", "plugin.json"),
211
+ skillPath: join2(dir, "SKILL.md")
212
+ };
213
+ }
214
+ function pathIsInside(root, path) {
215
+ const rel = relative(root, path);
216
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
217
+ }
218
+ function managedPathsAreSafe(paths, projectRoot) {
219
+ try {
220
+ const managed = [paths.manifestPath, paths.skillPath];
221
+ if (managed.some((path) => !lstatSync2(path).isFile())) return false;
222
+ if (projectRoot === void 0) return true;
223
+ const realRoot = realpathSync(projectRoot);
224
+ return managed.every((path) => pathIsInside(realRoot, realpathSync(path)));
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
229
+ function readBoundedRegularFile(path, maxBytes) {
230
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
231
+ try {
232
+ const stat = fstatSync(fd);
233
+ if (!stat.isFile() || stat.size > maxBytes) throw new Error("unsafe managed file");
234
+ const chunks = [];
235
+ let total = 0;
236
+ while (total <= maxBytes) {
237
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1 - total));
238
+ const bytesRead = readSync(fd, chunk, 0, chunk.length, null);
239
+ if (bytesRead === 0) break;
240
+ chunks.push(chunk.subarray(0, bytesRead));
241
+ total += bytesRead;
242
+ }
243
+ if (total > maxBytes) throw new Error("unsafe managed file");
244
+ return Buffer.concat(chunks, total).toString("utf8");
245
+ } finally {
246
+ closeSync(fd);
247
+ }
248
+ }
249
+ function hasUsablePrimFrontmatter(skill) {
250
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/u.exec(skill);
251
+ if (!match) return false;
252
+ try {
253
+ const parsed = parseYaml(match[1]);
254
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
255
+ const frontmatter = parsed;
256
+ return frontmatter.name === "prim" && typeof frontmatter.description === "string" && frontmatter.description.trim().length > 0 && match[2].trim().length > 0;
257
+ } catch {
258
+ return false;
259
+ }
260
+ }
261
+ function inspectRecognizedInstallation(paths, projectRoot) {
262
+ if (!existsSync2(paths.manifestPath) || !existsSync2(paths.skillPath)) return;
263
+ if (!managedPathsAreSafe(paths, projectRoot)) return;
264
+ const manifest = readBoundedRegularFile(paths.manifestPath, MAX_MANIFEST_BYTES);
265
+ const parsed = JSON.parse(manifest);
266
+ if (parsed.name !== "prim") return;
267
+ const skill = readBoundedRegularFile(paths.skillPath, MAX_SKILL_BYTES);
268
+ return {
269
+ manifest,
270
+ manifestVersion: parsed.version,
271
+ skill,
272
+ usable: hasUsablePrimFrontmatter(skill)
273
+ };
274
+ }
275
+ function refreshLockDir(physicalPluginDir) {
276
+ const cacheRoot = process.env.XDG_CACHE_HOME || join2(homedir2(), ".cache");
277
+ const identity = createHash2("sha256").update(physicalPluginDir).digest("hex");
278
+ return join2(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
279
+ }
280
+ async function refreshClaudePlugins(cwd, options = {}) {
281
+ const result = { installed: 0, refreshed: 0 };
282
+ const candidates = [];
283
+ if (options.includeProject !== false) {
284
+ const projectRoot = options.projectRoot ?? gitToplevel(cwd);
285
+ if (projectRoot !== null && isAbsolute(projectRoot)) {
286
+ candidates.push({ dir: join2(projectRoot, ".claude", "skills", "prim"), projectRoot });
287
+ }
288
+ }
289
+ candidates.push({ dir: pluginDirFor(cwd, "user") });
290
+ const seen = /* @__PURE__ */ new Set();
291
+ let desired;
292
+ for (const { dir, projectRoot } of candidates) {
293
+ let counted = false;
294
+ const markInstalled = () => {
295
+ if (!counted) {
296
+ result.installed += 1;
297
+ counted = true;
298
+ }
299
+ };
300
+ const refreshCandidate = () => {
301
+ const { manifestPath: manifestPath2, skillPath } = pluginPaths(dir);
302
+ const paths = { manifestPath: manifestPath2, skillPath };
303
+ try {
304
+ let changed = false;
305
+ const current = inspectRecognizedInstallation(paths, projectRoot);
306
+ if (!current) return;
307
+ desired ??= renderClaudePlugin();
308
+ if (projectRoot !== void 0 && current.usable && compareSemver(current.manifestVersion, desired.version) === 1) {
309
+ markInstalled();
310
+ return;
311
+ }
312
+ if (current.manifest !== desired.manifest) {
313
+ if (!managedPathsAreSafe(paths, projectRoot)) throw new Error("unsafe managed path");
314
+ atomicWrite(manifestPath2, desired.manifest);
315
+ if (!changed) result.refreshed += 1;
316
+ changed = true;
317
+ }
318
+ if (current.skill !== desired.skill) {
319
+ if (!managedPathsAreSafe(paths, projectRoot)) throw new Error("unsafe managed path");
320
+ atomicWrite(skillPath, desired.skill);
321
+ if (!changed) result.refreshed += 1;
322
+ changed = true;
323
+ }
324
+ markInstalled();
325
+ } catch {
326
+ try {
327
+ if (inspectRecognizedInstallation(paths, projectRoot)?.usable) markInstalled();
328
+ } catch {
329
+ }
330
+ }
331
+ };
332
+ try {
333
+ const paths = pluginPaths(dir);
334
+ if (!existsSync2(paths.manifestPath) || !existsSync2(paths.skillPath)) continue;
335
+ const physicalPluginDir = realpathSync(dir);
336
+ if (seen.has(physicalPluginDir)) continue;
337
+ seen.add(physicalPluginDir);
338
+ await withFileLock(refreshLockDir(physicalPluginDir), refreshCandidate, {
339
+ timeoutMs: REFRESH_LOCK_TIMEOUT_MS,
340
+ pollMs: REFRESH_LOCK_POLL_MS
341
+ });
342
+ } catch {
343
+ }
344
+ }
345
+ return result;
346
+ }
347
+ function installClaudePlugin(cwd, opts) {
348
+ const dir = resolvePluginDir(cwd, opts.scope);
349
+ if (dir === null) return 1;
350
+ const { manifestPath: manifestPath2, skillPath } = pluginPaths(dir);
351
+ const { manifest, skill } = renderClaudePlugin();
352
+ const welcomePath = opts.scope === "user" ? welcomeSkillPath(dir) : null;
353
+ const welcome = welcomePath ? loadSkill(WELCOME_SKILL_SOURCE) : null;
354
+ const manifestCurrent = existsSync2(manifestPath2) ? readFileSync2(manifestPath2, "utf-8") : null;
355
+ const skillCurrent = existsSync2(skillPath) ? readFileSync2(skillPath, "utf-8") : null;
356
+ const welcomeStatus = welcomePath ? welcomeSkillStatus(welcomePath) : null;
357
+ if (manifestCurrent === manifest && skillCurrent === skill && (!welcomePath || welcomeStatus?.installed && welcomeStatus.content === welcome)) {
358
+ console.log("No changes \u2014 prim skill plugin already up to date.");
359
+ return 0;
360
+ }
361
+ if (welcomePath && welcome !== null && installWelcomeSkill(welcomePath, welcome, opts.dryRun) !== 0)
362
+ return 1;
363
+ if (opts.dryRun) {
364
+ console.log(`Would write plugin to ${dir} (.claude-plugin/plugin.json + SKILL.md)`);
365
+ return 0;
366
+ }
367
+ mkdirSync(join2(dir, ".claude-plugin"), { recursive: true });
368
+ atomicWrite(manifestPath2, manifest);
369
+ atomicWrite(skillPath, skill);
370
+ console.log(`Installed prim skill plugin at ${dir}`);
371
+ console.log("Restart Claude Code or run /reload-plugins to load it.");
372
+ if (opts.scope !== "user") {
373
+ console.log("Project-scope plugins load only when Claude Code launches from this directory.");
374
+ }
375
+ return 0;
376
+ }
377
+ function uninstallClaudePlugin(cwd, opts) {
378
+ const dir = resolvePluginDir(cwd, opts.scope);
379
+ if (dir === null) return 1;
380
+ const { manifestPath: manifestPath2, skillPath } = pluginPaths(dir);
381
+ if (opts.scope === "user" && uninstallWelcomeSkill(welcomeSkillPath(dir)) !== 0) return 1;
382
+ if (!existsSync2(manifestPath2) && !existsSync2(skillPath)) {
383
+ console.log(`prim skill plugin not present at ${dir}`);
384
+ return 0;
385
+ }
386
+ rmSync(manifestPath2, { force: true });
387
+ rmSync(skillPath, { force: true });
388
+ removeDirIfEmpty(join2(dir, ".claude-plugin"));
389
+ removeDirIfEmpty(dir);
390
+ console.log(`Removed prim skill plugin from ${dir}`);
391
+ return 0;
392
+ }
393
+ function statusClaudePlugin(cwd, opts) {
394
+ const dir = resolvePluginDir(cwd, opts.scope);
395
+ if (dir === null) return 1;
396
+ const { skillPath } = pluginPaths(dir);
397
+ const welcome = opts.scope === "user" ? welcomeSkillStatus(welcomeSkillPath(dir)) : void 0;
398
+ const installed = existsSync2(skillPath) && (!welcome || welcome.installed);
399
+ if (opts.json) {
400
+ printJson({ installed, target: dir, ...welcome ? { welcomeSkill: welcome.installed } : {} });
401
+ return installed ? 0 : 1;
402
+ }
403
+ if (installed) {
404
+ console.log(`prim skill plugin installed at ${dir}`);
405
+ return 0;
406
+ }
407
+ console.log(`No prim skill plugin at ${dir}`);
408
+ return 1;
409
+ }
410
+
411
+ // src/commands/skill.ts
412
+ var __dirname2 = dirname3(fileURLToPath2(import.meta.url));
413
+ var SKILL_BEGIN = "<!-- BEGIN PRIM SKILL v1 -->";
414
+ var SKILL_END = "<!-- END PRIM SKILL v1 -->";
415
+ var CODEX_GUIDANCE_LIMIT_BYTES = 1024 * 1024;
416
+ var CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES = 32 * 1024;
417
+ var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
418
+ var SKILL_END_BUFFER = Buffer.from(SKILL_END);
419
+ function readCodexGuidance(path) {
420
+ try {
421
+ const entry = lstatSync3(path);
422
+ if (entry.isSymbolicLink() || !entry.isFile()) return null;
423
+ const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
424
+ try {
425
+ const opened = fstatSync2(fd);
426
+ if (!opened.isFile() || opened.size > CODEX_GUIDANCE_LIMIT_BYTES) return null;
427
+ const bytes = Buffer.allocUnsafe(CODEX_GUIDANCE_LIMIT_BYTES + 1);
428
+ let length = 0;
429
+ while (length < bytes.length) {
430
+ const read = readSync2(fd, bytes, length, bytes.length - length, length);
431
+ if (read === 0) break;
432
+ length += read;
433
+ }
434
+ return length > CODEX_GUIDANCE_LIMIT_BYTES ? null : bytes.subarray(0, length);
435
+ } finally {
436
+ closeSync2(fd);
437
+ }
438
+ } catch (error) {
439
+ const code = error.code;
440
+ return code === "ENOENT" || code === "ENOTDIR" ? void 0 : null;
441
+ }
442
+ }
443
+ function effectiveCodexGuidance(scope) {
444
+ const override = readCodexGuidance(join3(scope, "AGENTS.override.md"));
445
+ if (override === null) return null;
446
+ if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
447
+ const base = readCodexGuidance(join3(scope, "AGENTS.md"));
448
+ return base ?? null;
449
+ }
450
+ function hasUsablePrimBlock(content, visibleBytes) {
451
+ const begin = content.indexOf(SKILL_BEGIN_BUFFER);
452
+ const end = content.indexOf(SKILL_END_BUFFER);
453
+ if (begin === -1 || end <= begin + SKILL_BEGIN_BUFFER.length || end + SKILL_END_BUFFER.length > visibleBytes || content.indexOf(SKILL_BEGIN_BUFFER, begin + SKILL_BEGIN_BUFFER.length) !== -1 || content.indexOf(SKILL_END_BUFFER, end + SKILL_END_BUFFER.length) !== -1) {
454
+ return false;
455
+ }
456
+ const block = content.subarray(begin + SKILL_BEGIN_BUFFER.length, end).toString("utf8").trim();
457
+ const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/u.exec(block);
458
+ if (!match || match[2].trim().length === 0) return false;
459
+ try {
460
+ const metadata = parseYaml2(match[1]);
461
+ if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return false;
462
+ const fields = metadata;
463
+ return fields.name === "prim" && typeof fields.description === "string" && fields.description.trim().length > 0;
464
+ } catch {
465
+ return false;
466
+ }
467
+ }
468
+ function hasUsableCodexGuidance(projectRoot) {
469
+ try {
470
+ const codexHome = process.env.CODEX_HOME?.trim() ? resolve2(process.env.CODEX_HOME) : join3(homedir3(), ".codex");
471
+ const scopes = [
472
+ { path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
473
+ { path: projectRoot, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
474
+ ];
475
+ return scopes.some(({ path, visibleBytes }) => {
476
+ const guidance = effectiveCodexGuidance(path);
477
+ return guidance !== null && hasUsablePrimBlock(guidance, visibleBytes);
478
+ });
479
+ } catch {
480
+ return false;
481
+ }
482
+ }
483
+ var TARGET_CANDIDATES = [
484
+ "CLAUDE.md",
485
+ "AGENTS.md",
486
+ ".hermes.md",
487
+ ".cursor/rules",
488
+ ".windsurfrules",
489
+ ".github/instructions/primitive.md"
490
+ ];
491
+ var DEFAULT_TARGET = "CLAUDE.md";
492
+ var AGENT_TARGET = {
493
+ claude: "CLAUDE.md",
494
+ codex: "AGENTS.md",
495
+ hermes: ".hermes.md"
496
+ };
497
+ var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
498
+ var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
499
+ function sha256(content) {
500
+ return createHash3("sha256").update(content).digest("hex");
501
+ }
502
+ function cursorSkillDirectory(cwd, scope) {
503
+ const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
504
+ return join3(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
505
+ }
506
+ function cursorSkillPaths(cwd, scope) {
507
+ const directory = cursorSkillDirectory(cwd, scope);
508
+ return {
509
+ directory,
510
+ skill: join3(directory, "SKILL.md"),
511
+ manifest: join3(directory, CURSOR_SKILL_MANIFEST)
512
+ };
513
+ }
514
+ function readCursorSkillManifest(path) {
515
+ try {
516
+ const value = JSON.parse(readFileSync3(path, "utf8"));
517
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
518
+ const record = value;
519
+ if (record.version !== 1 || record.owner !== CURSOR_SKILL_OWNER || typeof record.contentSha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record.contentSha256)) {
520
+ return;
521
+ }
522
+ return record;
523
+ } catch {
524
+ return;
525
+ }
526
+ }
527
+ function cursorSkillStatus(cwd, scope) {
528
+ const paths = cursorSkillPaths(cwd, scope);
529
+ const manifest = readCursorSkillManifest(paths.manifest);
530
+ const content = existsSync3(paths.skill) ? readFileSync3(paths.skill, "utf8") : void 0;
531
+ const owned = manifest !== void 0;
532
+ const installed = owned && content !== void 0 && sha256(content) === manifest.contentSha256;
533
+ return {
534
+ installed,
535
+ owned,
536
+ edited: owned && content !== void 0 && !installed,
537
+ target: paths.skill
538
+ };
539
+ }
540
+ function validCursorSkillScope(scope) {
541
+ if (scope === void 0 || scope === "project" || scope === "user") return true;
542
+ console.error(`Unknown --scope "${scope}" (expected user or project)`);
543
+ return false;
544
+ }
545
+ function installCursorSkill(cwd, opts) {
546
+ const paths = cursorSkillPaths(cwd, opts.scope);
547
+ const status = cursorSkillStatus(cwd, opts.scope);
548
+ const manifestExists = existsSync3(paths.manifest);
549
+ const skillExists = existsSync3(paths.skill);
550
+ if (manifestExists && !status.owned || !manifestExists && skillExists || status.edited) {
551
+ console.error(`Refusing to overwrite a foreign or edited Cursor skill at ${paths.skill}`);
552
+ return 1;
553
+ }
554
+ const content = loadSkill();
555
+ const manifest = {
556
+ version: 1,
557
+ owner: CURSOR_SKILL_OWNER,
558
+ contentSha256: sha256(content)
559
+ };
560
+ if (status.installed && readFileSync3(paths.skill, "utf8") === content) {
561
+ console.log(`No changes \u2014 Cursor skill already up to date at ${paths.skill}`);
562
+ return 0;
563
+ }
564
+ if (opts.dryRun) {
565
+ const existing = skillExists ? readFileSync3(paths.skill, "utf8") : "";
566
+ process.stdout.write(createPatch(paths.skill, existing, content, "current", "proposed"));
567
+ return 0;
568
+ }
569
+ atomicWriteFile(paths.skill, content, { ensureParent: true });
570
+ atomicWriteFile(paths.manifest, `${JSON.stringify(manifest, null, 2)}
571
+ `, { ensureParent: true });
572
+ console.log(`Installed Cursor skill at ${paths.skill}`);
573
+ return 0;
574
+ }
575
+ function uninstallCursorSkill(cwd, scope) {
576
+ const paths = cursorSkillPaths(cwd, scope);
577
+ const status = cursorSkillStatus(cwd, scope);
578
+ if (!status.owned) {
579
+ console.log(`No Primitive-owned Cursor skill at ${paths.skill}`);
580
+ return 0;
581
+ }
582
+ if (status.edited) {
583
+ console.error(`Refusing to remove an edited Cursor skill at ${paths.skill}`);
584
+ return 1;
585
+ }
586
+ if (existsSync3(paths.skill)) unlinkSync2(paths.skill);
587
+ if (existsSync3(paths.manifest)) unlinkSync2(paths.manifest);
588
+ try {
589
+ if (readdirSync3(paths.directory).length === 0) rmdirSync3(paths.directory);
590
+ } catch {
591
+ }
592
+ console.log(`Removed Primitive-owned Cursor skill from ${paths.skill}`);
593
+ return 0;
594
+ }
595
+ function hasUsableCursorSkill(projectRoot) {
596
+ return cursorSkillStatus(projectRoot, "project").installed || cursorSkillStatus(projectRoot, "user").installed;
597
+ }
598
+ function userTargetFor(agent) {
599
+ if (agent === "claude") return join3(homedir3(), ".claude", "CLAUDE.md");
600
+ if (agent === "codex") {
601
+ const home = process.env.CODEX_HOME?.trim() ? resolve2(process.env.CODEX_HOME) : join3(homedir3(), ".codex");
602
+ return join3(home, "AGENTS.md");
603
+ }
604
+ if (agent === "hermes") {
605
+ return join3(process.env.HERMES_HOME ?? join3(homedir3(), ".hermes"), ".hermes.md");
606
+ }
607
+ return null;
608
+ }
609
+ function loadSkill(file = "SKILL.md") {
610
+ let dir = __dirname2;
611
+ while (dir !== dirname3(dir)) {
612
+ const p = resolve2(dir, file);
613
+ if (existsSync3(p)) return readFileSync3(p, "utf-8");
614
+ dir = dirname3(dir);
615
+ }
616
+ throw new Error(`${file} not found in package`);
617
+ }
618
+ function detectTargets(cwd) {
619
+ return TARGET_CANDIDATES.filter((p) => existsSync3(resolve2(cwd, p)));
620
+ }
621
+ function detectNewline(content) {
622
+ return content.includes("\r\n") ? "\r\n" : "\n";
623
+ }
624
+ function composeBlock(skill, eol) {
625
+ const body = skill.replace(/\r?\n/g, eol);
626
+ return `${SKILL_BEGIN}${eol}${body}${eol}${SKILL_END}`;
627
+ }
628
+ function applyBlock(existing, block, eol) {
629
+ const b = existing.indexOf(SKILL_BEGIN);
630
+ const e = existing.indexOf(SKILL_END);
631
+ if (b !== -1 && e !== -1) {
632
+ return existing.slice(0, b) + block + existing.slice(e + SKILL_END.length);
633
+ }
634
+ if (existing.length === 0) return `${block}${eol}`;
635
+ const sep3 = existing.endsWith(eol) ? "" : eol;
636
+ return `${existing}${sep3}${block}${eol}`;
637
+ }
638
+ function removeBlock(existing) {
639
+ const b = existing.indexOf(SKILL_BEGIN);
640
+ const e = existing.indexOf(SKILL_END);
641
+ if (b === -1 || e === -1) return null;
642
+ const out = existing.slice(0, b) + existing.slice(e + SKILL_END.length);
643
+ return out.replace(/(\r?\n){2,}$/, "$1");
644
+ }
645
+ function atomicWrite(target, content) {
646
+ atomicWriteFile(target, content, { ensureParent: true });
647
+ }
648
+ function resolveTarget(cwd, opts) {
649
+ if (opts.scope && opts.scope !== "user" && opts.scope !== "project") {
650
+ console.error(`Unknown --scope "${opts.scope}" (expected user or project)`);
651
+ return null;
652
+ }
653
+ if (opts.target) return resolve2(cwd, opts.target);
654
+ if (opts.scope === "user") {
655
+ if (!opts.agent) {
656
+ console.error("--scope user requires --agent (claude, codex, cursor, or hermes)");
657
+ return null;
658
+ }
659
+ const userTarget = userTargetFor(opts.agent);
660
+ if (userTarget) return userTarget;
661
+ console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
662
+ return null;
663
+ }
664
+ if (opts.agent) {
665
+ const mapped = AGENT_TARGET[opts.agent];
666
+ if (typeof mapped === "string") return resolve2(cwd, mapped);
667
+ console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
668
+ return null;
669
+ }
670
+ const matches = detectTargets(cwd);
671
+ if (matches.length === 0) return resolve2(cwd, DEFAULT_TARGET);
672
+ if (matches.length === 1) return resolve2(cwd, matches[0]);
673
+ console.error("Multiple rules files detected. Use --target to disambiguate:");
674
+ for (const m of matches) console.error(` ${m}`);
675
+ return null;
676
+ }
677
+ function runInstall(cwd, opts) {
678
+ if (opts.agent === "claude" && !opts.target) return installClaudePlugin(cwd, opts);
679
+ if (opts.agent === "cursor" && !opts.target) {
680
+ if (!validCursorSkillScope(opts.scope)) return 1;
681
+ return installCursorSkill(cwd, opts);
682
+ }
683
+ const target = resolveTarget(cwd, opts);
684
+ if (target === null) return 1;
685
+ const existing = existsSync3(target) ? readFileSync3(target, "utf-8") : "";
686
+ const eol = existing ? detectNewline(existing) : "\n";
687
+ const block = composeBlock(loadSkill(), eol);
688
+ const next = applyBlock(existing, block, eol);
689
+ const installCodexWelcome = () => opts.agent === "codex" && opts.scope === "user" && !opts.target ? installWelcomeSkill(codexWelcomeSkillPath(), loadSkill(WELCOME_SKILL_SOURCE), opts.dryRun) : 0;
690
+ if (next === existing) {
691
+ if (installCodexWelcome() !== 0) return 1;
692
+ console.log("No changes \u2014 skill block already up to date.");
693
+ return 0;
694
+ }
695
+ if (opts.dryRun) {
696
+ if (installCodexWelcome() !== 0) return 1;
697
+ process.stdout.write(createPatch(target, existing, next, "current", "proposed"));
698
+ return 0;
699
+ }
700
+ if (installCodexWelcome() !== 0) return 1;
701
+ atomicWrite(target, next);
702
+ console.log(`Wrote ${Buffer.byteLength(next)} bytes to ${target}`);
703
+ return 0;
704
+ }
705
+ function runUninstall(cwd, opts) {
706
+ if (opts.agent === "claude" && !opts.target) return uninstallClaudePlugin(cwd, opts);
707
+ if (opts.agent === "cursor" && !opts.target) {
708
+ if (!validCursorSkillScope(opts.scope)) return 1;
709
+ return uninstallCursorSkill(cwd, opts.scope);
710
+ }
711
+ if (opts.agent === "codex" && opts.scope === "user" && !opts.target) {
712
+ if (uninstallWelcomeSkill(codexWelcomeSkillPath()) !== 0) return 1;
713
+ }
714
+ const target = resolveTarget(cwd, opts);
715
+ if (target === null) return 1;
716
+ if (!existsSync3(target)) {
717
+ console.log(`Skill block not present at ${target}`);
718
+ return 0;
719
+ }
720
+ const existing = readFileSync3(target, "utf-8");
721
+ const next = removeBlock(existing);
722
+ if (next === null) {
723
+ console.log(`Skill block not present at ${target}`);
724
+ return 0;
725
+ }
726
+ atomicWrite(target, next);
727
+ console.log(`Removed skill block from ${target}`);
728
+ return 0;
729
+ }
730
+ function runStatus(cwd, opts) {
731
+ if (opts.agent === "claude" && !opts.target) return statusClaudePlugin(cwd, opts);
732
+ if (opts.agent === "cursor" && !opts.target) {
733
+ if (!validCursorSkillScope(opts.scope)) return 1;
734
+ const status = cursorSkillStatus(cwd, opts.scope);
735
+ if (opts.json) printJson(status);
736
+ else
737
+ console.log(
738
+ status.installed ? `Primitive Cursor skill installed at ${status.target}` : `No intact Primitive-owned Cursor skill at ${status.target}`
739
+ );
740
+ return status.installed ? 0 : 1;
741
+ }
742
+ const target = resolveTarget(cwd, opts);
743
+ if (target === null) return 1;
744
+ const fileExists = existsSync3(target);
745
+ let mainInstalled = false;
746
+ if (fileExists) {
747
+ const content = readFileSync3(target, "utf-8");
748
+ mainInstalled = content.includes(SKILL_BEGIN) && content.includes(SKILL_END);
749
+ }
750
+ const welcome = opts.agent === "codex" && opts.scope === "user" && !opts.target ? welcomeSkillStatus(codexWelcomeSkillPath()) : void 0;
751
+ const installed = mainInstalled && (!welcome || welcome.installed);
752
+ if (opts.json) {
753
+ printJson({
754
+ installed,
755
+ target,
756
+ ...welcome ? { welcomeSkill: welcome.installed } : {}
757
+ });
758
+ return installed ? 0 : 1;
759
+ }
760
+ if (!fileExists) {
761
+ console.log(`No rules file at ${target}`);
762
+ return 1;
763
+ }
764
+ if (installed) {
765
+ console.log(`PRIM SKILL v1 installed at ${target}`);
766
+ return 0;
767
+ }
768
+ if (mainInstalled && welcome && !welcome.installed) {
769
+ console.log(`No intact prim-welcome skill at ${welcome.target}`);
770
+ return 1;
771
+ }
772
+ console.log(`No PRIM SKILL block at ${target}`);
773
+ return 1;
774
+ }
775
+ function registerSkillCommands(program) {
776
+ const skill = program.command("skill").description("Manage the prim skill in your project rules file");
777
+ skill.command("install").description("Install the prim skill block into your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--dry-run", "Print a unified diff without writing").action((opts) => {
778
+ try {
779
+ process.exit(runInstall(process.cwd(), opts));
780
+ } catch (err) {
781
+ console.error(err instanceof Error ? err.message : String(err));
782
+ process.exit(2);
783
+ }
784
+ });
785
+ skill.command("uninstall").description("Remove the prim skill block from your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").action((opts) => {
786
+ process.exit(runUninstall(process.cwd(), opts));
787
+ });
788
+ skill.command("status").description("Report whether the prim skill block is installed").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--json", "Output as JSON").action((opts) => {
789
+ process.exit(runStatus(process.cwd(), opts));
790
+ });
791
+ }
792
+
793
+ // src/lib/bin-cache.ts
794
+ import { chmodSync, mkdirSync as mkdirSync2 } from "fs";
795
+ import { homedir as homedir4 } from "os";
796
+ import { join as join4 } from "path";
797
+ var GIT_HOOK_CACHE_SHELL_DIR = "${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin";
798
+ var GIT_HOOK_CACHE_TTL_MINUTES = 1440;
799
+ var GIT_HOOK_CACHED_BINS = ["prim-post-commit", "prim-post-rewrite"];
800
+ function binCacheDir() {
801
+ const base = process.env.XDG_CACHE_HOME || join4(homedir4(), ".cache");
802
+ return join4(base, "prim", "bin");
803
+ }
804
+ function writeAtomic(path, content) {
805
+ atomicWriteFile(path, content, { mode: 384 });
806
+ }
807
+ function warmBinCache() {
808
+ try {
809
+ if (process.env.PRIM_BIN_CACHE === "0") {
810
+ return;
811
+ }
812
+ const dir = binCacheDir();
813
+ mkdirSync2(dir, { recursive: true, mode: 448 });
814
+ chmodSync(dir, 448);
815
+ writeAtomic(join4(dir, "node"), process.execPath);
816
+ for (const bin of GIT_HOOK_CACHED_BINS) {
817
+ const file = binFile(bin);
818
+ if (file) {
819
+ writeAtomic(join4(dir, bin), file);
820
+ }
821
+ }
822
+ } catch {
823
+ }
824
+ }
825
+
826
+ // src/lib/git-hook-legacy.ts
827
+ import { isAbsolute as isAbsolute2 } from "path";
828
+ var PRIM_MANAGED_MARK = "prim-managed-hook";
829
+ var PRE_COMMIT = { hookName: "pre-commit", binName: "prim-pre-commit" };
830
+ var POST_COMMIT = { hookName: "post-commit", binName: "prim-post-commit" };
831
+ var POST_REWRITE = { hookName: "post-rewrite", binName: "prim-post-rewrite" };
832
+ function blockMarkers2(spec) {
833
+ return {
834
+ start: `# >>> prim ${spec.hookName} hook >>>`,
835
+ end: `# <<< prim ${spec.hookName} hook <<<`
836
+ };
837
+ }
838
+ function hookShim(binName) {
839
+ return `{ ${pinnedHookCommand(binName)}; } || true`;
840
+ }
841
+ function gatedShim(binName) {
842
+ return `if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then
843
+ ${hookShim(binName)}
844
+ fi`;
845
+ }
846
+ function legacyPostCommitBlock() {
847
+ return `# >>> prim post-commit hook >>>
848
+ if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then
849
+ prim_commit_sha=$(git rev-parse --verify HEAD 2>/dev/null) || prim_commit_sha=
850
+ case "$prim_commit_sha" in *[!0-9a-f]*|"") prim_commit_sha= ;; esac
851
+ case "\${#prim_commit_sha}" in 40|64) ;; *) prim_commit_sha= ;; esac
852
+ if [ -n "$prim_commit_sha" ]; then
853
+ prim_commit_observed_file=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_commit_observed_file=
854
+ prim_commit_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_commit_branch=
855
+ prim_cache_dir="${GIT_HOOK_CACHE_SHELL_DIR}"
856
+ prim_post_commit_ran=0
857
+ if [ "\${PRIM_BIN_CACHE:-1}" != "0" ] && [ -f "$prim_cache_dir/prim-post-commit" ] && [ -f "$prim_cache_dir/node" ] && [ -n "$(find "$prim_cache_dir/prim-post-commit" -mmin "-\${PRIM_BIN_CACHE_TTL_MIN:-${GIT_HOOK_CACHE_TTL_MINUTES}}" 2>/dev/null)" ]; then
858
+ prim_node=$(cat "$prim_cache_dir/node")
859
+ prim_entry=$(cat "$prim_cache_dir/prim-post-commit")
860
+ if [ -x "$prim_node" ] && [ -f "$prim_entry" ]; then
861
+ ( trap '' HUP; trap 'if [ -n "$prim_commit_observed_file" ]; then rm -f "$prim_commit_observed_file"; fi' 0; export PRIM_COMMIT_SHA="$prim_commit_sha" PRIM_COMMIT_BRANCH="$prim_commit_branch" PRIM_COMMIT_OBSERVED_FILE="$prim_commit_observed_file"; "$prim_node" "$prim_entry" ) </dev/null >/dev/null 2>&1 &
862
+ prim_post_commit_ran=1
863
+ fi
864
+ fi
865
+ if [ "$prim_post_commit_ran" -eq 0 ] && command -v npx >/dev/null 2>&1; then
866
+ ( trap '' HUP; trap 'if [ -n "$prim_commit_observed_file" ]; then rm -f "$prim_commit_observed_file"; fi' 0; export PRIM_COMMIT_SHA="$prim_commit_sha" PRIM_COMMIT_BRANCH="$prim_commit_branch" PRIM_COMMIT_OBSERVED_FILE="$prim_commit_observed_file"; ${pinnedNpxCommand("prim-post-commit")} ) </dev/null >/dev/null 2>&1 &
867
+ prim_post_commit_ran=1
868
+ fi
869
+ if [ "$prim_post_commit_ran" -eq 0 ] && [ -n "$prim_commit_observed_file" ]; then
870
+ rm -f "$prim_commit_observed_file"
871
+ fi
872
+ unset prim_cache_dir prim_post_commit_ran prim_node prim_entry prim_commit_branch prim_commit_observed_file
873
+ fi
874
+ unset prim_commit_sha
875
+ fi
876
+ # <<< prim post-commit hook <<<`;
877
+ }
878
+ function legacyPostRewriteBlock() {
879
+ return `# >>> prim post-rewrite hook >>>
880
+ if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then
881
+ case "$1" in amend|rebase) prim_rewrite_source="$1" ;; *) prim_rewrite_source= ;; esac
882
+ if [ -n "$prim_rewrite_source" ]; then
883
+ prim_rewrite_pairs_file=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || prim_rewrite_pairs_file=
884
+ if [ -n "$prim_rewrite_pairs_file" ] && ! chmod 600 "$prim_rewrite_pairs_file" 2>/dev/null; then
885
+ rm -f "$prim_rewrite_pairs_file"
886
+ prim_rewrite_pairs_file=
887
+ fi
888
+ if [ -n "$prim_rewrite_pairs_file" ]; then
889
+ if cat > "$prim_rewrite_pairs_file"; then
890
+ exec < "$prim_rewrite_pairs_file"
891
+ prim_rewrite_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_rewrite_branch=
892
+ prim_cache_dir="${GIT_HOOK_CACHE_SHELL_DIR}"
893
+ prim_post_rewrite_ran=0
894
+ if [ "\${PRIM_BIN_CACHE:-1}" != "0" ] && [ -f "$prim_cache_dir/prim-post-rewrite" ] && [ -f "$prim_cache_dir/node" ] && [ -n "$(find "$prim_cache_dir/prim-post-rewrite" -mmin "-\${PRIM_BIN_CACHE_TTL_MIN:-${GIT_HOOK_CACHE_TTL_MINUTES}}" 2>/dev/null)" ]; then
895
+ prim_node=$(cat "$prim_cache_dir/node")
896
+ prim_entry=$(cat "$prim_cache_dir/prim-post-rewrite")
897
+ if [ -x "$prim_node" ] && [ -f "$prim_entry" ]; then
898
+ ( trap '' HUP; trap 'if [ -n "$prim_rewrite_pairs_file" ]; then rm -f "$prim_rewrite_pairs_file"; fi' 0; export PRIM_REWRITE_SOURCE="$prim_rewrite_source" PRIM_REWRITE_BRANCH="$prim_rewrite_branch" PRIM_REWRITE_PAIRS_FILE="$prim_rewrite_pairs_file"; "$prim_node" "$prim_entry" ) </dev/null >/dev/null 2>&1 &
899
+ prim_post_rewrite_ran=1
900
+ fi
901
+ fi
902
+ if [ "$prim_post_rewrite_ran" -eq 0 ] && command -v npx >/dev/null 2>&1; then
903
+ ( trap '' HUP; trap 'if [ -n "$prim_rewrite_pairs_file" ]; then rm -f "$prim_rewrite_pairs_file"; fi' 0; export PRIM_REWRITE_SOURCE="$prim_rewrite_source" PRIM_REWRITE_BRANCH="$prim_rewrite_branch" PRIM_REWRITE_PAIRS_FILE="$prim_rewrite_pairs_file"; ${pinnedNpxCommand("prim-post-rewrite")} ) </dev/null >/dev/null 2>&1 &
904
+ prim_post_rewrite_ran=1
905
+ fi
906
+ if [ "$prim_post_rewrite_ran" -eq 0 ]; then
907
+ rm -f "$prim_rewrite_pairs_file"
908
+ fi
909
+ unset prim_cache_dir prim_post_rewrite_ran prim_node prim_entry prim_rewrite_branch
910
+ else
911
+ rm -f "$prim_rewrite_pairs_file"
912
+ fi
913
+ unset prim_rewrite_pairs_file
914
+ fi
915
+ fi
916
+ unset prim_rewrite_source
917
+ fi
918
+ # <<< prim post-rewrite hook <<<`;
919
+ }
920
+ function legacyGlobalHookScript(spec) {
921
+ const chainExit = spec.hookName === PRE_COMMIT.hookName ? "|| exit $?" : "|| true";
922
+ const managedBlock = spec.hookName === POST_COMMIT.hookName ? legacyPostCommitBlock() : spec.hookName === POST_REWRITE.hookName ? legacyPostRewriteBlock() : void 0;
923
+ const invocation = managedBlock ?? gatedShim(spec.binName);
924
+ const managedRepoGuard = managedBlock ? ` && ! grep -Fq '${blockMarkers2(spec).start.slice(0, -3)}'">>>" "$repo_hook" 2>/dev/null` : "";
925
+ const beforeComments = managedBlock ? `${invocation}
926
+ ` : "";
927
+ const afterComments = managedBlock ? "" : `${invocation}
928
+ `;
929
+ return `#!/bin/sh
930
+ ${beforeComments}# prim global ${spec.hookName} hook (core.hooksPath) \u2014 managed by prim; do not edit.
931
+ # Install/uninstall: prim hooks install|uninstall --scope user
932
+ # Runs prim only where activated \u2014 'prim enable' (this repo) or
933
+ # 'git config --global prim.active true' (every repo). Chains to the repo's own
934
+ # hook regardless, so inactive repos are unaffected.
935
+ ${afterComments}common_dir=$(git rev-parse --git-common-dir 2>/dev/null) || exit 0
936
+ repo_hook="$common_dir/hooks/${spec.hookName}"
937
+ if [ -x "$repo_hook" ] && ! grep -q '${PRIM_MANAGED_MARK}' "$repo_hook" 2>/dev/null${managedRepoGuard}; then
938
+ "$repo_hook" "$@" ${chainExit}
939
+ fi
940
+ exit 0
941
+ `;
942
+ }
943
+ var PRE_COMMIT_GATE = 'if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then';
944
+ function preCommitLadder(fallback, failSoft) {
945
+ const soft = failSoft ? " || true" : "";
946
+ return `if command -v prim-pre-commit >/dev/null 2>&1; then
947
+ prim-pre-commit${soft}
948
+ elif [ -f "./node_modules/.bin/prim-pre-commit" ]; then
949
+ ./node_modules/.bin/prim-pre-commit${soft}
950
+ else
951
+ ${fallback} 2>/dev/null || true
952
+ fi`;
953
+ }
954
+ var LADDER_ALPHA_2 = preCommitLadder("npx --yes @primitive.ai/prim pre-commit-hook", false);
955
+ var LADDER_ALPHA_9 = preCommitLadder("npx --yes -p @primitive.ai/prim prim-pre-commit", false);
956
+ var LADDER_ALPHA_35 = preCommitLadder("npx --yes -p @primitive.ai/prim prim-pre-commit", true);
957
+ var PINNED_NPX_PRE_COMMIT = String.raw`npx --yes(?: --ignore-scripts)? -p @primitive\.ai/prim@[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)? prim-pre-commit`;
958
+ var PINNED_PRE_COMMIT_RE = new RegExp(
959
+ String.raw`^\{ (?:${PINNED_NPX_PRE_COMMIT}|if \[ -x (?<node>'.*') \] && \[ -f (?<entry>'.*') \]; then \k<node> \k<entry>; else ${PINNED_NPX_PRE_COMMIT}; fi); \} \|\| true$`,
960
+ "u"
961
+ );
962
+ var SHELL_QUOTED_RE = /^'(?:[^']|'"'"')*'$/u;
963
+ function decodePinnedPath(token) {
964
+ if (!token || !SHELL_QUOTED_RE.test(token)) return void 0;
965
+ const value = token.slice(1, -1).replaceAll(`'"'"'`, "'");
966
+ if (!isAbsolute2(value) || value.includes("\0") || value.includes("\n") || value.includes("\r")) {
967
+ return void 0;
968
+ }
969
+ return value;
970
+ }
971
+ function isPinnedPreCommitInvocation(line) {
972
+ const match = PINNED_PRE_COMMIT_RE.exec(line);
973
+ if (!match) return false;
974
+ if (match.groups?.node === void 0) return true;
975
+ return Boolean(
976
+ decodePinnedPath(match.groups.node) && decodePinnedPath(match.groups.entry)?.endsWith("/dist/hooks/pre-commit.js")
977
+ );
978
+ }
979
+ function isLegacyPreCommitBody(body) {
980
+ if (body === LADDER_ALPHA_2 || body === LADDER_ALPHA_9 || body === LADDER_ALPHA_35) return true;
981
+ if (isPinnedPreCommitInvocation(body)) return true;
982
+ const prefix = `${PRE_COMMIT_GATE}
983
+ `;
984
+ if (!body.startsWith(prefix) || !body.endsWith("\nfi")) return false;
985
+ const inner = body.slice(prefix.length, -"\nfi".length);
986
+ return inner === LADDER_ALPHA_35 || isPinnedPreCommitInvocation(inner);
987
+ }
988
+ function isLegacyOwnedPreCommitScript(content) {
989
+ const original = (ladder) => `#!/bin/sh
990
+ # prim pre-commit hook \u2014 auto-syncs affected specs on commit
991
+ # Installed by: prim hooks install
992
+
993
+ # Find the nearest node_modules/.bin with prim, or use npx
994
+ ${ladder}
995
+ `;
996
+ if (content === original(LADDER_ALPHA_2) || content === original(LADDER_ALPHA_9)) return true;
997
+ if (content === `#!/bin/sh
998
+ # prim pre-commit hook \u2014 installed by: prim hooks install
999
+
1000
+ ${LADDER_ALPHA_9}
1001
+ `) {
1002
+ return true;
1003
+ }
1004
+ const prefix = `#!/bin/sh
1005
+ # prim pre-commit hook \u2014 installed by: prim hooks install (${PRIM_MANAGED_MARK})
1006
+
1007
+ `;
1008
+ if (!content.startsWith(prefix) || !content.endsWith("\n")) return false;
1009
+ const body = content.slice(prefix.length, -1);
1010
+ return body === LADDER_ALPHA_35 || isPinnedPreCommitInvocation(body);
1011
+ }
1012
+ var PINNED_PACKAGE_VERSION_RE = /@primitive\.ai\/prim@[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/gu;
1013
+ function normalizeOwnedGlobalHook(content, hookName) {
1014
+ if (hookName === PRE_COMMIT.hookName) {
1015
+ const lines = content.split("\n");
1016
+ const invocationIndexes = lines.flatMap(
1017
+ (line, index) => line.startsWith("{ ") && line.endsWith("; } || true") ? [index] : []
1018
+ );
1019
+ if (invocationIndexes.length !== 1) return null;
1020
+ const invocationIndex = invocationIndexes[0];
1021
+ if (!isPinnedPreCommitInvocation(lines[invocationIndex])) return null;
1022
+ lines[invocationIndex] = "{ <recognized Prim pre-commit invocation>; } || true";
1023
+ return lines.join("\n");
1024
+ }
1025
+ return content.replace(PINNED_PACKAGE_VERSION_RE, "@primitive.ai/prim@<version>");
1026
+ }
1027
+ function isLegacyOwnedGlobalHook(content, hookName) {
1028
+ const spec = [PRE_COMMIT, POST_COMMIT, POST_REWRITE].find((s) => s.hookName === hookName);
1029
+ if (!spec) return false;
1030
+ const expected = legacyGlobalHookScript(spec);
1031
+ if (content === expected) return true;
1032
+ if (spec === PRE_COMMIT && content === expected.replace(gatedShim(spec.binName), `${PRE_COMMIT_GATE}
1033
+ ${LADDER_ALPHA_35}
1034
+ fi`)) {
1035
+ return true;
1036
+ }
1037
+ const normalized = normalizeOwnedGlobalHook(content, hookName);
1038
+ return normalized !== null && normalized === normalizeOwnedGlobalHook(expected, hookName);
1039
+ }
1040
+ function legacyInlineHookBlock(hookName) {
1041
+ return hookName === "post-commit" ? legacyPostCommitBlock() : legacyPostRewriteBlock();
1042
+ }
1043
+ function isRecognizedLegacyBlock(hookName, block) {
1044
+ if (hookName === "pre-commit") {
1045
+ const { start, end } = blockMarkers2(PRE_COMMIT);
1046
+ const prefix = `${start}
1047
+ `;
1048
+ const suffix = `
1049
+ ${end}`;
1050
+ if (!block.startsWith(prefix) || !block.endsWith(suffix)) return false;
1051
+ return isLegacyPreCommitBody(block.slice(prefix.length, -suffix.length));
1052
+ }
1053
+ const expected = legacyInlineHookBlock(hookName);
1054
+ const normalize = (text) => text.replace(PINNED_PACKAGE_VERSION_RE, "@primitive.ai/prim@<version>");
1055
+ return normalize(block) === normalize(expected);
1056
+ }
1057
+
1058
+ // src/lib/git-hooks.ts
1059
+ import { execFileSync } from "child_process";
1060
+ import { createHash as createHash4, randomUUID } from "crypto";
1061
+ import {
1062
+ constants as constants3,
1063
+ closeSync as closeSync3,
1064
+ existsSync as existsSync4,
1065
+ fchmodSync,
1066
+ fsyncSync,
1067
+ lstatSync as lstatSync4,
1068
+ mkdirSync as mkdirSync3,
1069
+ openSync as openSync3,
1070
+ readFileSync as readFileSync4,
1071
+ realpathSync as realpathSync2,
1072
+ renameSync,
1073
+ unlinkSync as unlinkSync3,
1074
+ writeFileSync
1075
+ } from "fs";
1076
+ import { basename, dirname as dirname4, isAbsolute as isAbsolute3, join as join5, relative as relative2, resolve as resolve3, sep as sep2 } from "path";
1077
+ var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
1078
+ var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
1079
+ var LEGACY_GLOBAL_OWNED_HEADER = "# prim global post-commit hook (core.hooksPath) \u2014 managed by prim; do not edit.";
1080
+ var MAX_HOOK_BYTES = 1048576;
1081
+ var GIT_TIMEOUT_MS = 1e3;
1082
+ var SUPPORTED_SHEBANGS = /* @__PURE__ */ new Set([
1083
+ "#!/bin/sh",
1084
+ "#!/usr/bin/env sh",
1085
+ "#!/bin/bash",
1086
+ "#!/usr/bin/env bash",
1087
+ "#!/bin/zsh",
1088
+ "#!/usr/bin/env zsh"
1089
+ ]);
1090
+ var HUSKY_V9_DISPATCHERS = /* @__PURE__ */ new Set([
1091
+ '#!/usr/bin/env sh\n. "${0%/*}/h"',
1092
+ '#!/usr/bin/env sh\n. "$(dirname "$0")/h"'
1093
+ ]);
1094
+ var HUSKY_DIRECT_DISPATCHER = '#!/bin/sh\nexec sh "$(dirname "$0")/../post-commit"\n';
1095
+ var HUSKY_V9_RUNTIME_HASHES = /* @__PURE__ */ new Set([
1096
+ "d6aaa6f3f7c11008c525e649161df4a93152f1e55d0887fa1d7b8d622735d380",
1097
+ "b02cb91cab7125a9e906be723a1b85297fc435a8307d429ae845546b4ee0ecde",
1098
+ "9db5d129c4eb822a773157d98cd8fb8f1b156b85e3193117fefe527ca6d45e91",
1099
+ "3b2cb21335e544b4ebce658ca47af4a69d2c77026cc4d3f8b2227c34d062b207",
1100
+ "548990e1c11285694096184993d907b258d41235461a7ca2551e3b53ff9d3a38",
1101
+ "c029a943acea5d6e2ddbaa271a1fb22c2da55d56b5c6fb59ca804ac9a4018708",
1102
+ "ae3413a8fe2b39372de48bdc9691f42055f089c0c7529834b2fb07a131585b6a",
1103
+ "70200b200ca709b0622784f93839a5b2872333a917a09afddefd7dc2d8cdc680"
1104
+ ]);
1105
+ function managedHookSpecFor(hookName) {
1106
+ const { start, end } = blockMarkers(hookName);
1107
+ return {
1108
+ hookName,
1109
+ blockStart: start,
1110
+ blockEnd: end,
1111
+ createdMark: `prim-created-${hookName}-hook`
1112
+ };
1113
+ }
1114
+ var MANAGED_HOOK_SPECS = {
1115
+ "pre-commit": managedHookSpecFor("pre-commit"),
1116
+ "post-commit": managedHookSpecFor("post-commit"),
1117
+ "post-rewrite": managedHookSpecFor("post-rewrite")
1118
+ };
1119
+ function managedHookSpec(hookName) {
1120
+ return MANAGED_HOOK_SPECS[hookName];
1121
+ }
1122
+ function gitHooksMode(options = {}) {
1123
+ try {
1124
+ const value = execFileSync(
1125
+ "git",
1126
+ ["config", ...options.global ? ["--global"] : [], "--get", "prim.gitHooks"],
1127
+ {
1128
+ cwd: options.cwd,
1129
+ encoding: "utf8",
1130
+ stdio: ["ignore", "pipe", "ignore"],
1131
+ timeout: GIT_TIMEOUT_MS
1132
+ }
1133
+ ).trim();
1134
+ return value === "manual" ? "manual" : "auto";
1135
+ } catch {
1136
+ return "auto";
1137
+ }
1138
+ }
1139
+ function legacyFloatingInvocation() {
1140
+ return `if command -v prim-post-commit >/dev/null 2>&1; then
1141
+ prim-post-commit || true
1142
+ elif [ -f "./node_modules/.bin/prim-post-commit" ]; then
1143
+ ./node_modules/.bin/prim-post-commit || true
1144
+ else
1145
+ npx --yes -p @primitive.ai/prim prim-post-commit 2>/dev/null || true
1146
+ fi`;
1147
+ }
1148
+ function legacyGlobalGate() {
1149
+ return Buffer.from(`if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then
1150
+ ${legacyFloatingInvocation()}
1151
+ fi
1152
+ `);
1153
+ }
1154
+ var PINNED_INVOCATION_RE = /^\{ if \[ -x (?<node>'.*') \] && \[ -f (?<entry>'.*') \]; then \k<node> \k<entry>; else npx --yes -p @primitive\.ai\/prim@(?<version>[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?) prim-post-commit; fi; \} \|\| true$/u;
1155
+ function isPinnedInvocation(value) {
1156
+ const match = PINNED_INVOCATION_RE.exec(value);
1157
+ const node = decodePinnedPath(match?.groups?.node);
1158
+ const entry = decodePinnedPath(match?.groups?.entry);
1159
+ return Boolean(node && entry?.endsWith("/dist/hooks/post-commit.js"));
1160
+ }
1161
+ function legacyProjectPrefixLength(existing) {
1162
+ const prefix = Buffer.from(`#!/bin/sh
1163
+ ${LEGACY_PRIM_OWNED_HEADER}
1164
+
1165
+ `);
1166
+ if (!existing.subarray(0, prefix.length).equals(prefix)) return void 0;
1167
+ const floating = Buffer.from(`${legacyFloatingInvocation()}
1168
+ `);
1169
+ if (existing.subarray(prefix.length, prefix.length + floating.length).equals(floating)) {
1170
+ return prefix.length + floating.length;
1171
+ }
1172
+ const invocationEnd = existing.indexOf(10, prefix.length);
1173
+ if (invocationEnd === -1) return void 0;
1174
+ const invocation = existing.subarray(prefix.length, invocationEnd).toString("utf8");
1175
+ return isPinnedInvocation(invocation) ? invocationEnd + 1 : void 0;
1176
+ }
1177
+ function isKnownLegacyGlobalGate(value) {
1178
+ if (value.equals(legacyGlobalGate())) return true;
1179
+ const prefix = Buffer.from(
1180
+ 'if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then\n'
1181
+ );
1182
+ const suffix = Buffer.from("\nfi\n");
1183
+ return value.subarray(0, prefix.length).equals(prefix) && value.subarray(-suffix.length).equals(suffix) && isPinnedInvocation(value.subarray(prefix.length, -suffix.length).toString("utf8"));
1184
+ }
1185
+ function createdScaffold(spec) {
1186
+ return Buffer.from(`#!/bin/sh
1187
+ ${managedHookBlock(spec.hookName)}
1188
+ # ${spec.createdMark}
1189
+ `);
1190
+ }
1191
+ function oldCreatedPrefixes(spec) {
1192
+ return [
1193
+ Buffer.from(`#!/bin/sh
1194
+ # ${spec.createdMark}
1195
+
1196
+ `),
1197
+ Buffer.from(`#!/bin/sh
1198
+ # ${LEGACY_PRIM_CREATED_MARK}
1199
+
1200
+ `)
1201
+ ];
1202
+ }
1203
+ function isOwnedStandalonePreCommit(content) {
1204
+ return content === "#!/bin/sh\nprim-pre-commit\n" || isLegacyOwnedPreCommitScript(content);
1205
+ }
1206
+ function realpathLoose(path) {
1207
+ const missing = [];
1208
+ let current = resolve3(path);
1209
+ for (; ; ) {
1210
+ try {
1211
+ return join5(realpathSync2.native(current), ...missing);
1212
+ } catch {
1213
+ const parent = dirname4(current);
1214
+ if (parent === current) return resolve3(path);
1215
+ missing.unshift(basename(current));
1216
+ current = parent;
1217
+ }
1218
+ }
1219
+ }
1220
+ function isWithin(path, directory) {
1221
+ const rel = relative2(directory, path);
1222
+ return rel === "" || !isAbsolute3(rel) && rel !== ".." && !rel.startsWith(`..${sep2}`);
1223
+ }
1224
+ function primGitHooksDirectory() {
1225
+ try {
1226
+ return join5(primConfigDirectory(), "git-hooks");
1227
+ } catch {
1228
+ return void 0;
1229
+ }
1230
+ }
1231
+ function otherWorktreeRoots(gitRoot) {
1232
+ try {
1233
+ const self = realpathLoose(gitRoot);
1234
+ return execFileSync("git", ["worktree", "list", "--porcelain"], {
1235
+ cwd: gitRoot,
1236
+ encoding: "utf8",
1237
+ stdio: ["ignore", "pipe", "ignore"],
1238
+ timeout: GIT_TIMEOUT_MS
1239
+ }).split("\n").flatMap((line) => line.startsWith("worktree ") ? [realpathLoose(line.slice(9))] : []).filter((root) => root !== self);
1240
+ } catch {
1241
+ return [];
1242
+ }
1243
+ }
1244
+ function hookLocation(hookPath, dirs) {
1245
+ const path = realpathLoose(hookPath);
1246
+ if (isWithin(path, realpathLoose(dirs.gitDir)) || isWithin(path, realpathLoose(dirs.commonDir))) {
1247
+ return "repository";
1248
+ }
1249
+ const primDir = primGitHooksDirectory();
1250
+ if (primDir !== void 0 && isWithin(path, realpathLoose(primDir))) return "prim";
1251
+ const root = realpathLoose(dirs.gitRoot);
1252
+ if (!isWithin(path, root)) return "external";
1253
+ const nested = otherWorktreeRoots(dirs.gitRoot).filter((other) => isWithin(other, root));
1254
+ return nested.some((other) => isWithin(path, other)) ? "external" : "worktree";
1255
+ }
1256
+ function hooksPathScope(cwd) {
1257
+ try {
1258
+ const scope = execFileSync("git", ["config", "--show-scope", "--get", "core.hooksPath"], {
1259
+ cwd,
1260
+ encoding: "utf8",
1261
+ stdio: ["ignore", "pipe", "ignore"],
1262
+ timeout: GIT_TIMEOUT_MS
1263
+ }).split(" ")[0];
1264
+ return scope === "local" || scope === "worktree" || scope === "global" || scope === "system" || scope === "command" ? scope : void 0;
1265
+ } catch {
1266
+ return void 0;
1267
+ }
1268
+ }
1269
+ function externalHookRemedy(hookName, cwd) {
1270
+ const snippet = `place \`prim hooks snippet ${hookName}\` there yourself`;
1271
+ switch (hooksPathScope(cwd)) {
1272
+ case "global":
1273
+ return `your global core.hooksPath runs every repository's hooks: ${snippet}, or have prim add it with \`prim hooks install --scope user --global-hooks-path\` (it changes every repository's hooks: an agent must ask the user first)`;
1274
+ case "system":
1275
+ return `the system core.hooksPath is shared by every user on this machine: ${snippet}, or ask its owner`;
1276
+ case "local":
1277
+ case "worktree":
1278
+ return `this repository's core.hooksPath points outside it: ${snippet}, or point core.hooksPath inside the repository`;
1279
+ default:
1280
+ return snippet;
1281
+ }
1282
+ }
1283
+ function safeGitPath(root, value) {
1284
+ if (value.length === 0 || value !== value.trim() || value.includes("\0") || value.includes("\n") || value.includes("\r")) {
1285
+ throw new Error("Git returned an unsafe hooks path");
1286
+ }
1287
+ return isAbsolute3(value) ? resolve3(value) : resolve3(root, value);
1288
+ }
1289
+ function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
1290
+ const gitRoot = gitToplevel(cwd);
1291
+ if (!gitRoot) throw new Error("not a git repository");
1292
+ const lines = execFileSync(
1293
+ "git",
1294
+ ["rev-parse", "--git-path", "hooks", "--absolute-git-dir", "--git-common-dir"],
1295
+ {
1296
+ cwd: gitRoot,
1297
+ encoding: "utf8",
1298
+ stdio: ["ignore", "pipe", "ignore"],
1299
+ timeout: GIT_TIMEOUT_MS
1300
+ }
1301
+ ).replace(/\r?\n$/u, "").split(/\r?\n/u);
1302
+ if (lines.length !== 3) throw new Error("Git returned unexpected repository paths");
1303
+ const [hooksValue, gitDirValue, commonDirValue] = lines;
1304
+ const hooksDir = safeGitPath(gitRoot, hooksValue);
1305
+ const dirs = {
1306
+ gitRoot,
1307
+ gitDir: safeGitPath(gitRoot, gitDirValue),
1308
+ commonDir: safeGitPath(gitRoot, commonDirValue)
1309
+ };
1310
+ if (basename(hooksDir) === "_" && basename(dirname4(hooksDir)) === ".husky") {
1311
+ const hookPath2 = resolve3(dirname4(hooksDir), hookName);
1312
+ return {
1313
+ gitRoot,
1314
+ hooksDir,
1315
+ hookPath: hookPath2,
1316
+ kind: "husky_v9",
1317
+ dispatcherPath: resolve3(hooksDir, hookName),
1318
+ location: hookLocation(hookPath2, dirs)
1319
+ };
1320
+ }
1321
+ const hookPath = resolve3(hooksDir, hookName);
1322
+ return {
1323
+ gitRoot,
1324
+ hooksDir,
1325
+ hookPath,
1326
+ kind: "direct",
1327
+ location: hookLocation(hookPath, dirs)
1328
+ };
1329
+ }
1330
+ function assertSafeFile(path, spec) {
1331
+ if (!existsSync4(path)) return void 0;
1332
+ const stat = lstatSync4(path);
1333
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_HOOK_BYTES) {
1334
+ throw new Error(`unsafe ${spec.hookName} hook target: ${path}`);
1335
+ }
1336
+ return stat;
1337
+ }
1338
+ function assertUsableHuskyDispatcher(target, spec) {
1339
+ if (!target.dispatcherPath) return;
1340
+ const stat = assertSafeFile(target.dispatcherPath, spec);
1341
+ if (!stat || (stat.mode & 64) === 0) {
1342
+ throw new Error(
1343
+ `Husky ${spec.hookName} dispatcher is missing or not executable: ${target.dispatcherPath}`
1344
+ );
1345
+ }
1346
+ const dispatcher = decodeHookText(readHookFile(target.dispatcherPath), spec);
1347
+ const directDispatcher = HUSKY_DIRECT_DISPATCHER.replaceAll("post-commit", spec.hookName);
1348
+ if (dispatcher === directDispatcher) return;
1349
+ const normalizedDispatcher = dispatcher.endsWith("\n") ? dispatcher.slice(0, -1) : dispatcher;
1350
+ if (!HUSKY_V9_DISPATCHERS.has(normalizedDispatcher)) {
1351
+ throw new Error(`unrecognized Husky ${spec.hookName} dispatcher: ${target.dispatcherPath}`);
1352
+ }
1353
+ const huskyRuntime = resolve3(dirname4(target.dispatcherPath), "h");
1354
+ const runtimeStat = assertSafeFile(huskyRuntime, spec);
1355
+ const runtime = runtimeStat ? readHookFile(huskyRuntime) : void 0;
1356
+ const runtimeHash = runtime ? createHash4("sha256").update(runtime).digest("hex") : void 0;
1357
+ if (!runtimeHash || !HUSKY_V9_RUNTIME_HASHES.has(runtimeHash)) {
1358
+ throw new Error(`unrecognized Husky v9 hook runtime: ${huskyRuntime}`);
1359
+ }
1360
+ }
1361
+ function readHookFile(path) {
1362
+ const value = readFileSync4(path);
1363
+ return Buffer.isBuffer(value) ? value : Buffer.from(value);
1364
+ }
1365
+ function decodeHookText(content, spec) {
1366
+ if (content.includes(0)) throw new Error(`binary ${spec.hookName} hook`);
1367
+ try {
1368
+ return new TextDecoder("utf-8", { fatal: true }).decode(content);
1369
+ } catch {
1370
+ throw new Error(`binary ${spec.hookName} hook`);
1371
+ }
1372
+ }
1373
+ function supportedShebangEnd(content, spec) {
1374
+ const text = decodeHookText(content, spec);
1375
+ const newline = text.indexOf("\n");
1376
+ const shebang = newline === -1 ? text : text.slice(0, newline);
1377
+ if (!SUPPORTED_SHEBANGS.has(shebang) || newline === -1) {
1378
+ throw new Error(`unsupported ${spec.hookName} hook interpreter`);
1379
+ }
1380
+ return Buffer.byteLength(text.slice(0, newline + 1), "utf8");
1381
+ }
1382
+ function shellInsertionPoint(content, spec) {
1383
+ const text = decodeHookText(content, spec);
1384
+ if (text.startsWith("#!")) return supportedShebangEnd(content, spec);
1385
+ return 0;
1386
+ }
1387
+ function allIndexes(haystack, needle) {
1388
+ const indexes = [];
1389
+ let offset = 0;
1390
+ while (offset <= haystack.length - needle.length) {
1391
+ const index = haystack.indexOf(needle, offset);
1392
+ if (index === -1) break;
1393
+ indexes.push(index);
1394
+ offset = index + needle.length;
1395
+ }
1396
+ return indexes;
1397
+ }
1398
+ function blockRange(content, spec) {
1399
+ decodeHookText(content, spec);
1400
+ const startMarker = Buffer.from(spec.blockStart);
1401
+ const endMarker = Buffer.from(spec.blockEnd);
1402
+ const starts = allIndexes(content, startMarker);
1403
+ const ends = allIndexes(content, endMarker);
1404
+ if (starts.length === 0 && ends.length === 0) return { kind: "absent" };
1405
+ if (starts.length !== 1 || ends.length !== 1 || ends[0] < starts[0]) {
1406
+ throw new Error(`malformed Prim ${spec.hookName} markers`);
1407
+ }
1408
+ const start = starts[0];
1409
+ const end = ends[0] + endMarker.length;
1410
+ const text = content.subarray(start, end).toString("utf8");
1411
+ if (canonicalHookBlock(text) === canonicalHookBlock(managedHookBlock(spec.hookName))) {
1412
+ return { kind: "current", start, end };
1413
+ }
1414
+ const version = hookBlockContractVersion(text);
1415
+ if (version !== void 0 && version > GIT_HOOK_CONTRACT_VERSION) {
1416
+ return { kind: "newer", start, end };
1417
+ }
1418
+ return { kind: "stale", start, end };
1419
+ }
1420
+ var HUSKY_V8_SOURCE_RE = /^\.[ \t]+"\$\(dirname(?:[ \t]+--)?[ \t]+"\$0"\)\/_\/husky\.sh"[ \t]*$/mu;
1421
+ function blockInsertionPoint(content, spec, huskyV8) {
1422
+ const shebangEnd = shellInsertionPoint(content, spec);
1423
+ if (!huskyV8) return shebangEnd;
1424
+ const rest = content.subarray(shebangEnd).toString("utf8");
1425
+ const match = HUSKY_V8_SOURCE_RE.exec(rest);
1426
+ if (!match) return shebangEnd;
1427
+ const lineEnd = match.index + match[0].length;
1428
+ const afterLine = rest[lineEnd] === "\n" ? lineEnd + 1 : lineEnd;
1429
+ return shebangEnd + Buffer.byteLength(rest.slice(0, afterLine), "utf8");
1430
+ }
1431
+ var HUSKY_SPEC_MAJOR_RE = /^\s*[~^]?=?\s*v?([0-9]+)(?:\.(?:[0-9]+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?\s*$/u;
1432
+ function declaredHuskyMajor(dir) {
1433
+ for (let current = resolve3(dir); ; ) {
1434
+ const manifest = join5(current, "package.json");
1435
+ if (existsSync4(manifest)) {
1436
+ try {
1437
+ if (lstatSync4(manifest).size > MAX_HOOK_BYTES) return void 0;
1438
+ const parsed = JSON.parse(readFileSync4(manifest, "utf8"));
1439
+ const range = parsed.devDependencies?.husky ?? parsed.dependencies?.husky;
1440
+ const major = typeof range === "string" ? HUSKY_SPEC_MAJOR_RE.exec(range)?.[1] : void 0;
1441
+ return major === void 0 ? void 0 : Number(major);
1442
+ } catch {
1443
+ return void 0;
1444
+ }
1445
+ }
1446
+ const parent = dirname4(current);
1447
+ if (parent === current || existsSync4(join5(current, ".git"))) return void 0;
1448
+ current = parent;
1449
+ }
1450
+ }
1451
+ function isHuskyV8Hook(hookPath) {
1452
+ const runtime = join5(dirname4(hookPath), "_", "husky.sh");
1453
+ try {
1454
+ const stat = lstatSync4(runtime);
1455
+ return stat.isFile() && stat.size <= MAX_HOOK_BYTES && readFileSync4(runtime, "utf8").includes("husky_skip_init");
1456
+ } catch (error) {
1457
+ if (errorCode(error) !== "ENOENT") return false;
1458
+ }
1459
+ const major = declaredHuskyMajor(dirname4(dirname4(hookPath)));
1460
+ return major !== void 0 && major <= 8;
1461
+ }
1462
+ var TERMINAL_LINE_RE = /^(?:exit|return)(?:\s|;|$)/u;
1463
+ var REDIRECT_OPERATOR_RE = /^[0-9]*(?:<<?|>>?|<&|>&|<>|>\|)$/u;
1464
+ var REDIRECT_WORD_RE = /^[0-9]*(?:<|>)/u;
1465
+ function isReplacingExec(line) {
1466
+ if (!/^exec(?:\s|$)/u.test(line)) return false;
1467
+ const words = line.slice(4).trim().split(/\s+/u).filter(Boolean);
1468
+ for (let index = 0; index < words.length; index += 1) {
1469
+ const word = words[index];
1470
+ if (word.startsWith("#")) break;
1471
+ if (REDIRECT_OPERATOR_RE.test(word)) {
1472
+ index += 1;
1473
+ continue;
1474
+ }
1475
+ if (!REDIRECT_WORD_RE.test(word)) return true;
1476
+ }
1477
+ return false;
1478
+ }
1479
+ function terminatesBefore(content, from, offset) {
1480
+ const lines = content.subarray(from, offset).toString("utf8").split("\n");
1481
+ return lines.some((line) => TERMINAL_LINE_RE.test(line) || isReplacingExec(line));
1482
+ }
1483
+ function mayTerminateBefore(content, from, offset) {
1484
+ return content.subarray(from, offset).toString("utf8").split(/\n|;|&&|\|\||\||[{()]|\b(?:then|do|else)\b/u).some((part) => {
1485
+ const command = part.trim();
1486
+ return TERMINAL_LINE_RE.test(command) || isReplacingExec(command);
1487
+ });
1488
+ }
1489
+ function withoutRange(content, start, end) {
1490
+ const suffix = content.subarray(end);
1491
+ return Buffer.concat([
1492
+ content.subarray(0, start),
1493
+ suffix.at(0) === 10 ? suffix.subarray(1) : suffix
1494
+ ]);
1495
+ }
1496
+ function insertBlock(content, at, spec) {
1497
+ return Buffer.concat([
1498
+ content.subarray(0, at),
1499
+ Buffer.from(managedHookBlock(spec.hookName)),
1500
+ Buffer.from("\n"),
1501
+ content.subarray(at)
1502
+ ]);
1503
+ }
1504
+ function migratedLegacyContent(existing, spec, huskyV8) {
1505
+ const text = existing.toString("utf8");
1506
+ if (spec.hookName === "pre-commit" && isOwnedStandalonePreCommit(text)) {
1507
+ return createdScaffold(spec);
1508
+ }
1509
+ if (spec.hookName !== "post-commit") return void 0;
1510
+ if (text.startsWith(`#!/bin/sh
1511
+ ${LEGACY_GLOBAL_OWNED_HEADER}
1512
+ `)) {
1513
+ const gateAt = existing.indexOf(Buffer.from('if [ "$(git config --get prim.active'));
1514
+ const chainAt = existing.indexOf(Buffer.from("common_dir=$(git rev-parse --git-common-dir"));
1515
+ if (gateAt === -1 || chainAt <= gateAt) {
1516
+ throw new Error("malformed legacy Prim global post-commit hook");
1517
+ }
1518
+ if (!isKnownLegacyGlobalGate(existing.subarray(gateAt, chainAt))) {
1519
+ throw new Error("unrecognized legacy Prim global post-commit invocation");
1520
+ }
1521
+ const withoutLegacyGate = Buffer.concat([
1522
+ existing.subarray(0, gateAt),
1523
+ existing.subarray(chainAt)
1524
+ ]);
1525
+ return insertBlock(
1526
+ withoutLegacyGate,
1527
+ blockInsertionPoint(withoutLegacyGate, spec, huskyV8),
1528
+ spec
1529
+ );
1530
+ }
1531
+ if (text.startsWith(`#!/bin/sh
1532
+ ${LEGACY_PRIM_OWNED_HEADER}
1533
+ `)) {
1534
+ const prefixLength = legacyProjectPrefixLength(existing);
1535
+ if (prefixLength === void 0) {
1536
+ throw new Error("unrecognized legacy Prim post-commit invocation");
1537
+ }
1538
+ return Buffer.concat([createdScaffold(spec), existing.subarray(prefixLength)]);
1539
+ }
1540
+ return void 0;
1541
+ }
1542
+ function mergedContent(existing, spec, relocate, huskyV8) {
1543
+ if (!existing) return { content: createdScaffold(spec), migrates: false };
1544
+ const range = blockRange(existing, spec);
1545
+ if (range.kind === "absent") {
1546
+ const migrated = migratedLegacyContent(existing, spec, huskyV8);
1547
+ if (migrated) return { content: migrated, migrates: true };
1548
+ } else if (range.kind !== "newer") {
1549
+ const oldCreated = oldCreatedPrefixes(spec).some(
1550
+ (prefix) => range.start === prefix.length && existing.subarray(0, prefix.length).equals(prefix)
1551
+ );
1552
+ if (oldCreated) {
1553
+ const suffix = existing.subarray(range.end);
1554
+ const tail = suffix.at(0) === 10 ? suffix.subarray(1) : suffix;
1555
+ return {
1556
+ content: Buffer.concat([createdScaffold(spec), tail]),
1557
+ migrates: range.kind === "stale"
1558
+ };
1559
+ }
1560
+ }
1561
+ const shebangEnd = shellInsertionPoint(existing, spec);
1562
+ const insertion = blockInsertionPoint(existing, spec, huskyV8);
1563
+ switch (range.kind) {
1564
+ case "newer":
1565
+ return { content: existing, migrates: false };
1566
+ case "absent":
1567
+ return { content: insertBlock(existing, insertion, spec), migrates: false };
1568
+ case "current":
1569
+ case "stale": {
1570
+ const misplaced = terminatesBefore(existing, shebangEnd, range.start) || range.start < insertion;
1571
+ if (relocate && misplaced) {
1572
+ const without = withoutRange(existing, range.start, range.end);
1573
+ return {
1574
+ content: insertBlock(without, blockInsertionPoint(without, spec, huskyV8), spec),
1575
+ migrates: range.kind === "stale"
1576
+ };
1577
+ }
1578
+ if (range.kind === "current") return { content: existing, migrates: false };
1579
+ return {
1580
+ content: Buffer.concat([
1581
+ existing.subarray(0, range.start),
1582
+ Buffer.from(managedHookBlock(spec.hookName)),
1583
+ existing.subarray(range.end)
1584
+ ]),
1585
+ migrates: true
1586
+ };
1587
+ }
1588
+ }
1589
+ }
1590
+ function errorCode(error) {
1591
+ return typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1592
+ }
1593
+ function assertTargetUnchanged(path, expected, spec, stat) {
1594
+ let current;
1595
+ try {
1596
+ current = lstatSync4(path);
1597
+ } catch (error) {
1598
+ if (expected === void 0 && errorCode(error) === "ENOENT") return;
1599
+ throw new Error(`${spec.hookName} hook changed concurrently: ${path}`);
1600
+ }
1601
+ if (expected === void 0) {
1602
+ throw new Error(`${spec.hookName} hook appeared concurrently: ${path}`);
1603
+ }
1604
+ if (!current.isFile() || current.isSymbolicLink() || current.size > MAX_HOOK_BYTES || current.dev !== stat?.dev || current.ino !== stat?.ino || (current.mode & 4095) !== ((stat?.mode ?? 0) & 4095) || !readHookFile(path).equals(expected)) {
1605
+ throw new Error(`${spec.hookName} hook changed concurrently: ${path}`);
1606
+ }
1607
+ }
1608
+ function rewriteHookAtomically(path, next, expected, spec, stat) {
1609
+ const parent = dirname4(path);
1610
+ mkdirSync3(parent, { recursive: true });
1611
+ const temporary = resolve3(
1612
+ parent,
1613
+ `.${basename(path)}.prim-${String(process.pid)}-${randomUUID()}.tmp`
1614
+ );
1615
+ let fd;
1616
+ try {
1617
+ fd = openSync3(
1618
+ temporary,
1619
+ constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW,
1620
+ stat?.mode ?? 493
1621
+ );
1622
+ writeFileSync(fd, next);
1623
+ fchmodSync(fd, (stat?.mode ?? 493) & 4095);
1624
+ fsyncSync(fd);
1625
+ closeSync3(fd);
1626
+ fd = void 0;
1627
+ assertTargetUnchanged(path, expected, spec, stat);
1628
+ renameSync(temporary, path);
1629
+ } finally {
1630
+ if (fd !== void 0) {
1631
+ try {
1632
+ closeSync3(fd);
1633
+ } catch {
1634
+ }
1635
+ }
1636
+ try {
1637
+ unlinkSync3(temporary);
1638
+ } catch (error) {
1639
+ if (errorCode(error) !== "ENOENT") {
1640
+ }
1641
+ }
1642
+ }
1643
+ }
1644
+ function unlinkHookUnchanged(path, expected, stat, spec) {
1645
+ assertTargetUnchanged(path, expected, spec, stat);
1646
+ unlinkSync3(path);
1647
+ }
1648
+ function workingLegacyBlock(content, spec) {
1649
+ try {
1650
+ const range = blockRange(content, spec);
1651
+ if (range.kind !== "stale") return false;
1652
+ const block = content.subarray(range.start, range.end).toString("utf8");
1653
+ const from = shellInsertionPoint(content, spec);
1654
+ return isRecognizedLegacyBlock(spec.hookName, block) && !mayTerminateBefore(content, from, range.start);
1655
+ } catch {
1656
+ return false;
1657
+ }
1658
+ }
1659
+ var AMBIENT_LOCATIONS = ["repository", "prim"];
1660
+ var EXPLICIT_LOCATIONS = ["repository", "prim", "worktree"];
1661
+ function ensureTarget(target, spec, policy) {
1662
+ const result = { hookName: spec.hookName, path: target.hookPath, kind: target.kind };
1663
+ const skip = (outcome) => ({
1664
+ ...result,
1665
+ changed: false,
1666
+ outcome
1667
+ });
1668
+ assertUsableHuskyDispatcher(target, spec);
1669
+ const stat = assertSafeFile(target.hookPath, spec);
1670
+ if (stat && target.kind === "direct" && (stat.mode & 64) === 0) {
1671
+ throw new Error(`existing ${spec.hookName} hook is not executable: ${target.hookPath}`);
1672
+ }
1673
+ const existing = stat ? readHookFile(target.hookPath) : void 0;
1674
+ if (policy.repairOnly && (!existing || blockRange(existing, spec).kind === "absent")) {
1675
+ return skip("skipped");
1676
+ }
1677
+ const huskyV8 = isHuskyV8Hook(target.hookPath);
1678
+ const next = mergedContent(existing, spec, policy.relocate, huskyV8);
1679
+ if (existing && next.content.equals(existing)) return skip("unchanged");
1680
+ if (!policy.writable(target.location)) {
1681
+ if (target.location === "worktree") return skip("deferred");
1682
+ return skip(existing && workingLegacyBlock(existing, spec) ? "kept" : "external");
1683
+ }
1684
+ if (next.migrates && inspectGitHookEntrypoint() !== "ready") return skip("runtime_missing");
1685
+ rewriteHookAtomically(target.hookPath, next.content, existing, spec, stat);
1686
+ return { ...result, changed: true, outcome: existing ? "updated" : "created" };
1687
+ }
1688
+ function ensureEffectiveGitHook(hookName, cwd = process.cwd(), options = {}) {
1689
+ const target = resolveEffectiveGitHook(hookName, cwd);
1690
+ if (gitHooksMode({ cwd: target.gitRoot }) === "manual") {
1691
+ return {
1692
+ hookName,
1693
+ path: target.hookPath,
1694
+ kind: target.kind,
1695
+ changed: false,
1696
+ outcome: "manual"
1697
+ };
1698
+ }
1699
+ const explicit = (options.context ?? "explicit") === "explicit";
1700
+ const allowed = explicit ? EXPLICIT_LOCATIONS : AMBIENT_LOCATIONS;
1701
+ return ensureTarget(target, managedHookSpec(hookName), {
1702
+ writable: (location) => allowed.includes(location),
1703
+ relocate: explicit,
1704
+ repairOnly: options.repairOnly === true
1705
+ });
1706
+ }
1707
+ function explicitTarget(hookPath, options) {
1708
+ const absolute = resolve3(hookPath);
1709
+ return {
1710
+ gitRoot: dirname4(dirname4(absolute)),
1711
+ hooksDir: dirname4(absolute),
1712
+ hookPath: absolute,
1713
+ // A `.husky/<hook>` file is run by Husky's dispatcher via `sh`, so it needs
1714
+ // neither a shebang nor the executable bit.
1715
+ kind: options.husky ? "husky_v9" : "direct",
1716
+ // The caller chose this exact file (a --target, or a consented global dir).
1717
+ location: "external"
1718
+ };
1719
+ }
1720
+ function hasCurrentHookBlock(hookName, hookPath) {
1721
+ try {
1722
+ const kind = blockRange(readHookFile(hookPath), managedHookSpec(hookName)).kind;
1723
+ return kind === "current" || kind === "newer";
1724
+ } catch {
1725
+ return false;
1726
+ }
1727
+ }
1728
+ function ensureGitHookAtPath(hookName, hookPath, options = {}) {
1729
+ return ensureTarget(explicitTarget(hookPath, options), managedHookSpec(hookName), {
1730
+ writable: () => true,
1731
+ relocate: true,
1732
+ repairOnly: false
1733
+ });
1734
+ }
1735
+ function inspectEffectiveGitHook(hookName, cwd = process.cwd()) {
1736
+ const spec = managedHookSpec(hookName);
1737
+ const target = resolveEffectiveGitHook(hookName, cwd);
1738
+ const base = {
1739
+ ...target,
1740
+ hookName,
1741
+ mode: gitHooksMode({ cwd: target.gitRoot }),
1742
+ entrypoint: inspectGitHookEntrypoint()
1743
+ };
1744
+ const uncovered = (reason2, executable2 = false) => ({ ...base, covered: false, executable: executable2, current: false, reason: reason2 });
1745
+ try {
1746
+ assertUsableHuskyDispatcher(target, spec);
1747
+ } catch (error) {
1748
+ const missing = error instanceof Error && (error.message.includes("missing or not executable") || error.message.includes("unsafe"));
1749
+ return uncovered(missing ? "husky_dispatcher_missing" : "husky_dispatcher_invalid");
1750
+ }
1751
+ let stat;
1752
+ try {
1753
+ stat = assertSafeFile(target.hookPath, spec);
1754
+ } catch {
1755
+ return uncovered("unsafe_target");
1756
+ }
1757
+ if (!stat) return uncovered("missing");
1758
+ const executable = target.kind === "husky_v9" || (stat.mode & 64) !== 0;
1759
+ let range;
1760
+ let content;
1761
+ let insertion;
1762
+ try {
1763
+ content = readHookFile(target.hookPath);
1764
+ insertion = shellInsertionPoint(content, spec);
1765
+ range = blockRange(content, spec);
1766
+ } catch (error) {
1767
+ const message = error instanceof Error ? error.message : "";
1768
+ return uncovered(
1769
+ message.includes("binary") ? "binary" : message.includes("unsupported") ? "unsupported_interpreter" : "malformed_markers",
1770
+ executable
1771
+ );
1772
+ }
1773
+ const huskyV8 = isHuskyV8Hook(target.hookPath);
1774
+ const preferred = blockInsertionPoint(content, spec, huskyV8);
1775
+ const current = range.kind === "current" || range.kind === "newer";
1776
+ const legacy = range.kind === "stale" && workingLegacyBlock(content, spec);
1777
+ const reason = range.kind === "absent" ? "missing_block" : range.kind === "stale" && !legacy ? "stale_block" : terminatesBefore(content, insertion, range.start) ? "unreachable_block" : !executable ? "not_executable" : legacy ? "legacy_block" : base.entrypoint !== "ready" ? "entrypoint_missing" : range.start < preferred ? "misplaced_block" : void 0;
1778
+ return {
1779
+ ...base,
1780
+ covered: reason === void 0,
1781
+ executable,
1782
+ current,
1783
+ ...reason ? { reason } : {}
1784
+ };
1785
+ }
1786
+ function projectHooksPathIsConfigured(gitRoot) {
1787
+ for (const scope of ["--worktree", "--local"]) {
1788
+ try {
1789
+ const value = execFileSync("git", ["config", scope, "--get", "core.hooksPath"], {
1790
+ cwd: gitRoot,
1791
+ encoding: "utf8",
1792
+ stdio: ["ignore", "pipe", "ignore"],
1793
+ timeout: GIT_TIMEOUT_MS
1794
+ }).trim();
1795
+ if (value.length > 0) return true;
1796
+ } catch {
1797
+ }
1798
+ }
1799
+ return false;
1800
+ }
1801
+ function uninstallProjectGitHook(hookName, cwd = process.cwd()) {
1802
+ const target = projectGitHookTarget(hookName, cwd);
1803
+ if (target.location === "external") {
1804
+ return { path: target.hookPath, changed: false, removedFile: false, skipped: "external" };
1805
+ }
1806
+ return uninstallTarget(target, managedHookSpec(hookName));
1807
+ }
1808
+ function projectGitHookTarget(hookName, cwd = process.cwd()) {
1809
+ const gitRoot = gitToplevel(cwd);
1810
+ if (!gitRoot) throw new Error("not a git repository");
1811
+ if (projectHooksPathIsConfigured(gitRoot)) return resolveEffectiveGitHook(hookName, gitRoot);
1812
+ return {
1813
+ ...explicitTarget(resolve3(projectHooksDir(gitRoot), hookName), {}),
1814
+ gitRoot,
1815
+ location: "repository"
1816
+ };
1817
+ }
1818
+ function projectHooksDir(gitRoot) {
1819
+ const commonDir = execFileSync("git", ["rev-parse", "--git-common-dir"], {
1820
+ cwd: gitRoot,
1821
+ encoding: "utf8",
1822
+ stdio: ["ignore", "pipe", "ignore"],
1823
+ timeout: GIT_TIMEOUT_MS
1824
+ }).replace(/\r?\n$/u, "");
1825
+ return resolve3(safeGitPath(gitRoot, commonDir), "hooks");
1826
+ }
1827
+ function uninstallGitHookAtPath(hookName, hookPath, options = {}) {
1828
+ return uninstallTarget(explicitTarget(hookPath, options), managedHookSpec(hookName));
1829
+ }
1830
+ function uninstallTarget(target, spec) {
1831
+ const unchanged = { path: target.hookPath, changed: false, removedFile: false };
1832
+ const stat = assertSafeFile(target.hookPath, spec);
1833
+ if (!stat) return unchanged;
1834
+ const existing = readHookFile(target.hookPath);
1835
+ const remove = () => {
1836
+ unlinkHookUnchanged(target.hookPath, existing, stat, spec);
1837
+ return { path: target.hookPath, changed: true, removedFile: true };
1838
+ };
1839
+ const rewrite = (next) => {
1840
+ rewriteHookAtomically(target.hookPath, next, existing, spec, stat);
1841
+ return { path: target.hookPath, changed: true, removedFile: false };
1842
+ };
1843
+ const range = blockRange(existing, spec);
1844
+ if (range.kind === "absent") {
1845
+ const text = existing.toString("utf8");
1846
+ if (spec.hookName === "pre-commit" && isOwnedStandalonePreCommit(text)) return remove();
1847
+ if (spec.hookName === "post-commit" && text.startsWith(`#!/bin/sh
1848
+ ${LEGACY_PRIM_OWNED_HEADER}
1849
+ `)) {
1850
+ const prefixLength = legacyProjectPrefixLength(existing);
1851
+ if (prefixLength === void 0) {
1852
+ throw new Error("unrecognized legacy Prim post-commit invocation");
1853
+ }
1854
+ const tail = existing.subarray(prefixLength);
1855
+ return tail.length === 0 ? remove() : rewrite(Buffer.concat([Buffer.from("#!/bin/sh\n"), tail]));
1856
+ }
1857
+ return unchanged;
1858
+ }
1859
+ const shebangEnd = shellInsertionPoint(existing, spec);
1860
+ const suffix = existing.subarray(range.end);
1861
+ const createdSuffix = Buffer.from(`
1862
+ # ${spec.createdMark}
1863
+ `);
1864
+ if (range.start === shebangEnd && suffix.subarray(0, createdSuffix.length).equals(createdSuffix)) {
1865
+ const tail = suffix.subarray(createdSuffix.length);
1866
+ return tail.length === 0 ? remove() : rewrite(Buffer.concat([existing.subarray(0, shebangEnd), tail]));
1867
+ }
1868
+ const createdPrefix = oldCreatedPrefixes(spec).find(
1869
+ (prefix) => range.start === prefix.length && existing.subarray(0, prefix.length).equals(prefix)
1870
+ );
1871
+ if (createdPrefix) {
1872
+ const tail = suffix.at(0) === 10 ? suffix.subarray(1) : suffix;
1873
+ return tail.length === 0 ? remove() : rewrite(Buffer.concat([Buffer.from("#!/bin/sh\n"), tail]));
1874
+ }
1875
+ return rewrite(withoutRange(existing, range.start, range.end));
1876
+ }
1877
+
1878
+ // src/lib/repository-binding.ts
1879
+ var InvalidRepositoryBindingResponseError = class extends Error {
1880
+ };
1881
+ async function resolveRepositoryBindingWithClient(root, client, options) {
1882
+ const repositoryFullName = githubRepositoryFullName(root);
1883
+ if (!repositoryFullName) {
1884
+ throw new Error("origin must be a GitHub HTTPS/SSH remote in owner/name form");
1885
+ }
1886
+ let response;
1887
+ try {
1888
+ response = await client.post(
1889
+ "/api/cli/repositories/bind",
1890
+ { repositoryFullName },
1891
+ options
1892
+ );
1893
+ } catch (error) {
1894
+ if (error instanceof HttpError && error.status === 404) {
1895
+ return { status: "unbound", repositoryFullName };
1896
+ }
1897
+ throw error;
1898
+ }
1899
+ if (!isValidRepoSyncId(response.repoSyncId)) {
1900
+ throw new InvalidRepositoryBindingResponseError(
1901
+ "server returned an invalid repository binding"
1902
+ );
1903
+ }
1904
+ return { status: "connected", repoSyncId: response.repoSyncId, repositoryFullName };
1905
+ }
1906
+ async function resolveRepositoryBinding(root, options) {
1907
+ return resolveRepositoryBindingWithClient(root, getClient(), options);
1908
+ }
1909
+ function persistRepositoryBinding(root, binding) {
1910
+ if (binding.status === "connected") {
1911
+ setRepoSyncId(root, binding.repoSyncId, binding.repositoryFullName);
1912
+ setRepositoryBindingState(root, "connected");
1913
+ return;
1914
+ }
1915
+ setRepositoryBindingState(root, "unbound");
1916
+ }
1917
+ async function bindRepositoryWithClient(root, client, options) {
1918
+ let binding;
1919
+ try {
1920
+ binding = await resolveRepositoryBindingWithClient(root, client, options);
1921
+ } catch (error) {
1922
+ if (error instanceof InvalidRepositoryBindingResponseError) {
1923
+ try {
1924
+ setRepositoryBindingState(root, "invalid");
1925
+ } catch {
1926
+ }
1927
+ }
1928
+ throw error;
1929
+ }
1930
+ persistRepositoryBinding(root, binding);
1931
+ return binding;
1932
+ }
1933
+ async function bindRepository(root, options) {
1934
+ return bindRepositoryWithClient(root, getClient(), options);
1935
+ }
1936
+
1937
+ // src/daemon/self-heal.ts
1938
+ import { spawn } from "child_process";
1939
+ function kickDaemonEnsure(options = {}) {
1940
+ const primEntry = options.primEntry === void 0 ? binFile("prim") : options.primEntry;
1941
+ if (!primEntry) {
1942
+ return false;
1943
+ }
1944
+ try {
1945
+ const args = [primEntry, "daemon", "ensure"];
1946
+ if (options.latestBootstrap ?? (options.platform ?? process.platform) === "darwin") {
1947
+ args.push("--latest-bootstrap");
1948
+ }
1949
+ const child = (options.spawnProcess ?? spawn)(
1950
+ options.nodeEntry ?? process.execPath,
1951
+ args,
1952
+ // Unattended: neither SessionStart's repair nor a drift heal is a person
1953
+ // running prim, so the child (and its descendants) never heal in turn.
1954
+ { detached: true, stdio: "ignore", env: unattendedEnv() }
1955
+ );
1956
+ child.once("error", () => {
1957
+ });
1958
+ child.unref();
1959
+ return true;
1960
+ } catch {
1961
+ return false;
1962
+ }
1963
+ }
1964
+
1965
+ export {
1966
+ warmBinCache,
1967
+ isLegacyOwnedGlobalHook,
1968
+ gitHooksMode,
1969
+ isOwnedStandalonePreCommit,
1970
+ externalHookRemedy,
1971
+ resolveEffectiveGitHook,
1972
+ ensureEffectiveGitHook,
1973
+ hasCurrentHookBlock,
1974
+ ensureGitHookAtPath,
1975
+ inspectEffectiveGitHook,
1976
+ uninstallProjectGitHook,
1977
+ projectGitHookTarget,
1978
+ projectHooksDir,
1979
+ uninstallGitHookAtPath,
1980
+ resolveRepositoryBinding,
1981
+ bindRepositoryWithClient,
1982
+ bindRepository,
1983
+ printJson,
1984
+ codexWelcomeSkillPath,
1985
+ hasUsableCodexGuidance,
1986
+ hasUsableCursorSkill,
1987
+ userTargetFor,
1988
+ registerSkillCommands,
1989
+ welcomeSkillPathFor,
1990
+ refreshClaudePlugins,
1991
+ kickDaemonEnsure
1992
+ };