@primitive.ai/prim 0.1.0-alpha.60 → 0.1.0-alpha.62
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.
- package/dist/chunk-DA4BMHEB.js +77 -0
- package/dist/{chunk-B4SHJYIN.js → chunk-GF5QII7T.js} +83 -110
- package/dist/{chunk-QY75BQMF.js → chunk-JQFN6LBO.js} +8 -0
- package/dist/{chunk-YIMUIPMD.js → chunk-KBFFVYBC.js} +7 -1
- package/dist/chunk-LOGW54W5.js +1244 -0
- package/dist/chunk-QGVHLP5J.js +117 -0
- package/dist/{chunk-IMAIBPUC.js → chunk-UVIWZWM6.js} +1 -0
- package/dist/chunk-XTNMSS4C.js +283 -0
- package/dist/daemon/server.js +1 -0
- package/dist/hooks/post-commit.js +82 -16
- package/dist/hooks/post-tool-use.js +41 -25
- package/dist/hooks/pre-tool-use.js +103 -11
- package/dist/hooks/prim-hook.js +30 -9
- package/dist/hooks/session-start.js +22 -5
- package/dist/index.js +730 -179
- package/dist/statusline-main.js +7 -2
- package/package.json +1 -1
- package/dist/chunk-GUXBUBQ7.js +0 -84
- package/dist/chunk-LDQZASIF.js +0 -166
- package/dist/chunk-MZQO7K2P.js +0 -616
- package/dist/chunk-YDBZTFW5.js +0 -67
|
@@ -0,0 +1,1244 @@
|
|
|
1
|
+
import {
|
|
2
|
+
gitToplevel,
|
|
3
|
+
githubRepositoryFullName,
|
|
4
|
+
isValidRepoSyncId,
|
|
5
|
+
setRepoSyncId
|
|
6
|
+
} from "./chunk-XTNMSS4C.js";
|
|
7
|
+
import {
|
|
8
|
+
getClient,
|
|
9
|
+
withFileLock
|
|
10
|
+
} from "./chunk-I3HIPAIR.js";
|
|
11
|
+
|
|
12
|
+
// src/commands/skill.ts
|
|
13
|
+
import { randomUUID } from "crypto";
|
|
14
|
+
import {
|
|
15
|
+
constants as constants2,
|
|
16
|
+
closeSync as closeSync2,
|
|
17
|
+
existsSync as existsSync2,
|
|
18
|
+
fstatSync as fstatSync2,
|
|
19
|
+
fsyncSync,
|
|
20
|
+
lstatSync as lstatSync2,
|
|
21
|
+
openSync as openSync2,
|
|
22
|
+
readFileSync as readFileSync2,
|
|
23
|
+
readSync as readSync2,
|
|
24
|
+
renameSync,
|
|
25
|
+
rmSync as rmSync2,
|
|
26
|
+
writeFileSync
|
|
27
|
+
} from "fs";
|
|
28
|
+
import { homedir as homedir2 } from "os";
|
|
29
|
+
import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
|
|
30
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
31
|
+
import { createPatch } from "diff";
|
|
32
|
+
import { parse as parseYaml2 } from "yaml";
|
|
33
|
+
|
|
34
|
+
// src/output.ts
|
|
35
|
+
function printJson(data) {
|
|
36
|
+
console.log(JSON.stringify(data, null, 2));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/commands/claude-plugin.ts
|
|
40
|
+
import { createHash } from "crypto";
|
|
41
|
+
import {
|
|
42
|
+
constants,
|
|
43
|
+
closeSync,
|
|
44
|
+
existsSync,
|
|
45
|
+
fstatSync,
|
|
46
|
+
lstatSync,
|
|
47
|
+
mkdirSync,
|
|
48
|
+
openSync,
|
|
49
|
+
readFileSync,
|
|
50
|
+
readSync,
|
|
51
|
+
readdirSync,
|
|
52
|
+
realpathSync,
|
|
53
|
+
rmSync,
|
|
54
|
+
rmdirSync
|
|
55
|
+
} from "fs";
|
|
56
|
+
import { homedir } from "os";
|
|
57
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
|
|
58
|
+
import { fileURLToPath } from "url";
|
|
59
|
+
import { parse as parseYaml } from "yaml";
|
|
60
|
+
|
|
61
|
+
// src/lib/semver.ts
|
|
62
|
+
function parseSemver(value) {
|
|
63
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
64
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
|
|
65
|
+
value
|
|
66
|
+
);
|
|
67
|
+
if (!match) return;
|
|
68
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
69
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
73
|
+
}
|
|
74
|
+
function compareSemver(left, right) {
|
|
75
|
+
const a = parseSemver(left);
|
|
76
|
+
const b = parseSemver(right);
|
|
77
|
+
if (!a || !b) return;
|
|
78
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
79
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
80
|
+
}
|
|
81
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
82
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
83
|
+
}
|
|
84
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
85
|
+
const x = a.prerelease[i];
|
|
86
|
+
const y = b.prerelease[i];
|
|
87
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
88
|
+
if (x === y) continue;
|
|
89
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
90
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
91
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
92
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
93
|
+
return x < y ? -1 : 1;
|
|
94
|
+
}
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// src/commands/claude-plugin.ts
|
|
99
|
+
var __dirname = dirname(fileURLToPath(import.meta.url));
|
|
100
|
+
var PLUGIN_DESCRIPTION = "Primitive decision-graph guidance for the prim CLI \u2014 a model-invoked skill installed by prim skill install.";
|
|
101
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
102
|
+
var MAX_SKILL_BYTES = 1024 * 1024;
|
|
103
|
+
var REFRESH_LOCK_TIMEOUT_MS = 150;
|
|
104
|
+
var REFRESH_LOCK_POLL_MS = 10;
|
|
105
|
+
function pluginDirFor(cwd, scope) {
|
|
106
|
+
const base = scope === "user" ? join(homedir(), ".claude") : join(gitToplevel(cwd) ?? cwd, ".claude");
|
|
107
|
+
return join(base, "skills", "prim");
|
|
108
|
+
}
|
|
109
|
+
function resolvePluginDir(cwd, scope) {
|
|
110
|
+
if (scope && scope !== "user" && scope !== "project") {
|
|
111
|
+
console.error(`Unknown --scope "${scope}" (expected user or project)`);
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
return pluginDirFor(cwd, scope === "user" ? "user" : "project");
|
|
115
|
+
}
|
|
116
|
+
function packageVersion() {
|
|
117
|
+
let dir = __dirname;
|
|
118
|
+
while (dir !== dirname(dir)) {
|
|
119
|
+
const p = resolve(dir, "package.json");
|
|
120
|
+
if (existsSync(p)) return JSON.parse(readFileSync(p, "utf-8")).version;
|
|
121
|
+
dir = dirname(dir);
|
|
122
|
+
}
|
|
123
|
+
return "0.0.0";
|
|
124
|
+
}
|
|
125
|
+
function pluginManifest(version) {
|
|
126
|
+
const manifest = { name: "prim", description: PLUGIN_DESCRIPTION, version };
|
|
127
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
128
|
+
`;
|
|
129
|
+
}
|
|
130
|
+
function renderClaudePlugin() {
|
|
131
|
+
const version = packageVersion();
|
|
132
|
+
return { manifest: pluginManifest(version), skill: loadSkill(), version };
|
|
133
|
+
}
|
|
134
|
+
function removeDirIfEmpty(dir) {
|
|
135
|
+
if (existsSync(dir) && readdirSync(dir).length === 0) rmdirSync(dir);
|
|
136
|
+
}
|
|
137
|
+
function pluginPaths(dir) {
|
|
138
|
+
return {
|
|
139
|
+
manifestPath: join(dir, ".claude-plugin", "plugin.json"),
|
|
140
|
+
skillPath: join(dir, "SKILL.md")
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function pathIsInside(root, path) {
|
|
144
|
+
const rel = relative(root, path);
|
|
145
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
146
|
+
}
|
|
147
|
+
function managedPathsAreSafe(paths, projectRoot) {
|
|
148
|
+
try {
|
|
149
|
+
const managed = [paths.manifestPath, paths.skillPath];
|
|
150
|
+
if (managed.some((path) => !lstatSync(path).isFile())) return false;
|
|
151
|
+
if (projectRoot === void 0) return true;
|
|
152
|
+
const realRoot = realpathSync(projectRoot);
|
|
153
|
+
return managed.every((path) => pathIsInside(realRoot, realpathSync(path)));
|
|
154
|
+
} catch {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function readBoundedRegularFile(path, maxBytes) {
|
|
159
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
160
|
+
try {
|
|
161
|
+
const stat = fstatSync(fd);
|
|
162
|
+
if (!stat.isFile() || stat.size > maxBytes) throw new Error("unsafe managed file");
|
|
163
|
+
const chunks = [];
|
|
164
|
+
let total = 0;
|
|
165
|
+
while (total <= maxBytes) {
|
|
166
|
+
const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1 - total));
|
|
167
|
+
const bytesRead = readSync(fd, chunk, 0, chunk.length, null);
|
|
168
|
+
if (bytesRead === 0) break;
|
|
169
|
+
chunks.push(chunk.subarray(0, bytesRead));
|
|
170
|
+
total += bytesRead;
|
|
171
|
+
}
|
|
172
|
+
if (total > maxBytes) throw new Error("unsafe managed file");
|
|
173
|
+
return Buffer.concat(chunks, total).toString("utf8");
|
|
174
|
+
} finally {
|
|
175
|
+
closeSync(fd);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function hasUsablePrimFrontmatter(skill) {
|
|
179
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/u.exec(skill);
|
|
180
|
+
if (!match) return false;
|
|
181
|
+
try {
|
|
182
|
+
const parsed = parseYaml(match[1]);
|
|
183
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
|
|
184
|
+
const frontmatter = parsed;
|
|
185
|
+
return frontmatter.name === "prim" && typeof frontmatter.description === "string" && frontmatter.description.trim().length > 0 && match[2].trim().length > 0;
|
|
186
|
+
} catch {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function inspectRecognizedInstallation(paths, projectRoot) {
|
|
191
|
+
if (!existsSync(paths.manifestPath) || !existsSync(paths.skillPath)) return;
|
|
192
|
+
if (!managedPathsAreSafe(paths, projectRoot)) return;
|
|
193
|
+
const manifest = readBoundedRegularFile(paths.manifestPath, MAX_MANIFEST_BYTES);
|
|
194
|
+
const parsed = JSON.parse(manifest);
|
|
195
|
+
if (parsed.name !== "prim") return;
|
|
196
|
+
const skill = readBoundedRegularFile(paths.skillPath, MAX_SKILL_BYTES);
|
|
197
|
+
return {
|
|
198
|
+
manifest,
|
|
199
|
+
manifestVersion: parsed.version,
|
|
200
|
+
skill,
|
|
201
|
+
usable: hasUsablePrimFrontmatter(skill)
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function refreshLockDir(physicalPluginDir) {
|
|
205
|
+
const cacheRoot = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
|
|
206
|
+
const identity = createHash("sha256").update(physicalPluginDir).digest("hex");
|
|
207
|
+
return join(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
|
|
208
|
+
}
|
|
209
|
+
async function refreshClaudePlugins(cwd, options = {}) {
|
|
210
|
+
const result = { installed: 0, refreshed: 0 };
|
|
211
|
+
const candidates = [];
|
|
212
|
+
if (options.includeProject !== false) {
|
|
213
|
+
const projectRoot = options.projectRoot ?? gitToplevel(cwd);
|
|
214
|
+
if (projectRoot !== null && isAbsolute(projectRoot)) {
|
|
215
|
+
candidates.push({ dir: join(projectRoot, ".claude", "skills", "prim"), projectRoot });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
candidates.push({ dir: pluginDirFor(cwd, "user") });
|
|
219
|
+
const seen = /* @__PURE__ */ new Set();
|
|
220
|
+
let desired;
|
|
221
|
+
for (const { dir, projectRoot } of candidates) {
|
|
222
|
+
let counted = false;
|
|
223
|
+
const markInstalled = () => {
|
|
224
|
+
if (!counted) {
|
|
225
|
+
result.installed += 1;
|
|
226
|
+
counted = true;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
const refreshCandidate = () => {
|
|
230
|
+
const { manifestPath, skillPath } = pluginPaths(dir);
|
|
231
|
+
const paths = { manifestPath, skillPath };
|
|
232
|
+
try {
|
|
233
|
+
let changed = false;
|
|
234
|
+
const current = inspectRecognizedInstallation(paths, projectRoot);
|
|
235
|
+
if (!current) return;
|
|
236
|
+
desired ??= renderClaudePlugin();
|
|
237
|
+
if (projectRoot !== void 0 && current.usable && compareSemver(current.manifestVersion, desired.version) === 1) {
|
|
238
|
+
markInstalled();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (current.manifest !== desired.manifest) {
|
|
242
|
+
if (!managedPathsAreSafe(paths, projectRoot)) throw new Error("unsafe managed path");
|
|
243
|
+
atomicWrite(manifestPath, desired.manifest);
|
|
244
|
+
if (!changed) result.refreshed += 1;
|
|
245
|
+
changed = true;
|
|
246
|
+
}
|
|
247
|
+
if (current.skill !== desired.skill) {
|
|
248
|
+
if (!managedPathsAreSafe(paths, projectRoot)) throw new Error("unsafe managed path");
|
|
249
|
+
atomicWrite(skillPath, desired.skill);
|
|
250
|
+
if (!changed) result.refreshed += 1;
|
|
251
|
+
changed = true;
|
|
252
|
+
}
|
|
253
|
+
markInstalled();
|
|
254
|
+
} catch {
|
|
255
|
+
try {
|
|
256
|
+
if (inspectRecognizedInstallation(paths, projectRoot)?.usable) markInstalled();
|
|
257
|
+
} catch {
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
try {
|
|
262
|
+
const paths = pluginPaths(dir);
|
|
263
|
+
if (!existsSync(paths.manifestPath) || !existsSync(paths.skillPath)) continue;
|
|
264
|
+
const physicalPluginDir = realpathSync(dir);
|
|
265
|
+
if (seen.has(physicalPluginDir)) continue;
|
|
266
|
+
seen.add(physicalPluginDir);
|
|
267
|
+
await withFileLock(refreshLockDir(physicalPluginDir), refreshCandidate, {
|
|
268
|
+
timeoutMs: REFRESH_LOCK_TIMEOUT_MS,
|
|
269
|
+
pollMs: REFRESH_LOCK_POLL_MS
|
|
270
|
+
});
|
|
271
|
+
} catch {
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return result;
|
|
275
|
+
}
|
|
276
|
+
function installClaudePlugin(cwd, opts) {
|
|
277
|
+
const dir = resolvePluginDir(cwd, opts.scope);
|
|
278
|
+
if (dir === null) return 1;
|
|
279
|
+
const { manifestPath, skillPath } = pluginPaths(dir);
|
|
280
|
+
const { manifest, skill } = renderClaudePlugin();
|
|
281
|
+
const manifestCurrent = existsSync(manifestPath) ? readFileSync(manifestPath, "utf-8") : null;
|
|
282
|
+
const skillCurrent = existsSync(skillPath) ? readFileSync(skillPath, "utf-8") : null;
|
|
283
|
+
if (manifestCurrent === manifest && skillCurrent === skill) {
|
|
284
|
+
console.log("No changes \u2014 prim skill plugin already up to date.");
|
|
285
|
+
return 0;
|
|
286
|
+
}
|
|
287
|
+
if (opts.dryRun) {
|
|
288
|
+
console.log(`Would write plugin to ${dir} (.claude-plugin/plugin.json + SKILL.md)`);
|
|
289
|
+
return 0;
|
|
290
|
+
}
|
|
291
|
+
mkdirSync(join(dir, ".claude-plugin"), { recursive: true });
|
|
292
|
+
atomicWrite(manifestPath, manifest);
|
|
293
|
+
atomicWrite(skillPath, skill);
|
|
294
|
+
console.log(`Installed prim skill plugin at ${dir}`);
|
|
295
|
+
console.log("Restart Claude Code or run /reload-plugins to load it.");
|
|
296
|
+
if (opts.scope !== "user") {
|
|
297
|
+
console.log("Project-scope plugins load only when Claude Code launches from this directory.");
|
|
298
|
+
}
|
|
299
|
+
return 0;
|
|
300
|
+
}
|
|
301
|
+
function uninstallClaudePlugin(cwd, opts) {
|
|
302
|
+
const dir = resolvePluginDir(cwd, opts.scope);
|
|
303
|
+
if (dir === null) return 1;
|
|
304
|
+
const { manifestPath, skillPath } = pluginPaths(dir);
|
|
305
|
+
if (!existsSync(manifestPath) && !existsSync(skillPath)) {
|
|
306
|
+
console.log(`prim skill plugin not present at ${dir}`);
|
|
307
|
+
return 0;
|
|
308
|
+
}
|
|
309
|
+
rmSync(manifestPath, { force: true });
|
|
310
|
+
rmSync(skillPath, { force: true });
|
|
311
|
+
removeDirIfEmpty(join(dir, ".claude-plugin"));
|
|
312
|
+
removeDirIfEmpty(dir);
|
|
313
|
+
console.log(`Removed prim skill plugin from ${dir}`);
|
|
314
|
+
return 0;
|
|
315
|
+
}
|
|
316
|
+
function statusClaudePlugin(cwd, opts) {
|
|
317
|
+
const dir = resolvePluginDir(cwd, opts.scope);
|
|
318
|
+
if (dir === null) return 1;
|
|
319
|
+
const { skillPath } = pluginPaths(dir);
|
|
320
|
+
const installed = existsSync(skillPath);
|
|
321
|
+
if (opts.json) {
|
|
322
|
+
printJson({ installed, target: dir });
|
|
323
|
+
return installed ? 0 : 1;
|
|
324
|
+
}
|
|
325
|
+
if (installed) {
|
|
326
|
+
console.log(`prim skill plugin installed at ${dir}`);
|
|
327
|
+
return 0;
|
|
328
|
+
}
|
|
329
|
+
console.log(`No prim skill plugin at ${dir}`);
|
|
330
|
+
return 1;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/commands/skill.ts
|
|
334
|
+
var __dirname2 = dirname2(fileURLToPath2(import.meta.url));
|
|
335
|
+
var SKILL_BEGIN = "<!-- BEGIN PRIM SKILL v1 -->";
|
|
336
|
+
var SKILL_END = "<!-- END PRIM SKILL v1 -->";
|
|
337
|
+
var CODEX_GUIDANCE_LIMIT_BYTES = 1024 * 1024;
|
|
338
|
+
var CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES = 32 * 1024;
|
|
339
|
+
var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
|
|
340
|
+
var SKILL_END_BUFFER = Buffer.from(SKILL_END);
|
|
341
|
+
function readCodexGuidance(path) {
|
|
342
|
+
try {
|
|
343
|
+
const entry = lstatSync2(path);
|
|
344
|
+
if (entry.isSymbolicLink() || !entry.isFile()) return null;
|
|
345
|
+
const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
346
|
+
try {
|
|
347
|
+
const opened = fstatSync2(fd);
|
|
348
|
+
if (!opened.isFile() || opened.size > CODEX_GUIDANCE_LIMIT_BYTES) return null;
|
|
349
|
+
const bytes = Buffer.allocUnsafe(CODEX_GUIDANCE_LIMIT_BYTES + 1);
|
|
350
|
+
let length = 0;
|
|
351
|
+
while (length < bytes.length) {
|
|
352
|
+
const read = readSync2(fd, bytes, length, bytes.length - length, length);
|
|
353
|
+
if (read === 0) break;
|
|
354
|
+
length += read;
|
|
355
|
+
}
|
|
356
|
+
return length > CODEX_GUIDANCE_LIMIT_BYTES ? null : bytes.subarray(0, length);
|
|
357
|
+
} finally {
|
|
358
|
+
closeSync2(fd);
|
|
359
|
+
}
|
|
360
|
+
} catch (error) {
|
|
361
|
+
const code = error.code;
|
|
362
|
+
return code === "ENOENT" || code === "ENOTDIR" ? void 0 : null;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function effectiveCodexGuidance(scope) {
|
|
366
|
+
const override = readCodexGuidance(join2(scope, "AGENTS.override.md"));
|
|
367
|
+
if (override === null) return null;
|
|
368
|
+
if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
|
|
369
|
+
const base = readCodexGuidance(join2(scope, "AGENTS.md"));
|
|
370
|
+
return base ?? null;
|
|
371
|
+
}
|
|
372
|
+
function hasUsablePrimBlock(content, visibleBytes) {
|
|
373
|
+
const begin = content.indexOf(SKILL_BEGIN_BUFFER);
|
|
374
|
+
const end = content.indexOf(SKILL_END_BUFFER);
|
|
375
|
+
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) {
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
const block = content.subarray(begin + SKILL_BEGIN_BUFFER.length, end).toString("utf8").trim();
|
|
379
|
+
const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/u.exec(block);
|
|
380
|
+
if (!match || match[2].trim().length === 0) return false;
|
|
381
|
+
try {
|
|
382
|
+
const metadata = parseYaml2(match[1]);
|
|
383
|
+
if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return false;
|
|
384
|
+
const fields = metadata;
|
|
385
|
+
return fields.name === "prim" && typeof fields.description === "string" && fields.description.trim().length > 0;
|
|
386
|
+
} catch {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function hasUsableCodexGuidance(projectRoot) {
|
|
391
|
+
try {
|
|
392
|
+
const codexHome = process.env.CODEX_HOME?.trim() ? resolve2(process.env.CODEX_HOME) : join2(homedir2(), ".codex");
|
|
393
|
+
const scopes = [
|
|
394
|
+
{ path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
|
|
395
|
+
{ path: projectRoot, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
|
|
396
|
+
];
|
|
397
|
+
return scopes.some(({ path, visibleBytes }) => {
|
|
398
|
+
const guidance = effectiveCodexGuidance(path);
|
|
399
|
+
return guidance !== null && hasUsablePrimBlock(guidance, visibleBytes);
|
|
400
|
+
});
|
|
401
|
+
} catch {
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
var TARGET_CANDIDATES = [
|
|
406
|
+
"CLAUDE.md",
|
|
407
|
+
"AGENTS.md",
|
|
408
|
+
".hermes.md",
|
|
409
|
+
".cursor/rules",
|
|
410
|
+
".windsurfrules",
|
|
411
|
+
".github/instructions/primitive.md"
|
|
412
|
+
];
|
|
413
|
+
var DEFAULT_TARGET = "CLAUDE.md";
|
|
414
|
+
var AGENT_TARGET = {
|
|
415
|
+
claude: "CLAUDE.md",
|
|
416
|
+
codex: "AGENTS.md",
|
|
417
|
+
hermes: ".hermes.md"
|
|
418
|
+
};
|
|
419
|
+
function userTargetFor(agent) {
|
|
420
|
+
if (agent === "claude") return join2(homedir2(), ".claude", "CLAUDE.md");
|
|
421
|
+
if (agent === "codex") return join2(homedir2(), ".codex", "AGENTS.md");
|
|
422
|
+
if (agent === "hermes") {
|
|
423
|
+
return join2(process.env.HERMES_HOME ?? join2(homedir2(), ".hermes"), ".hermes.md");
|
|
424
|
+
}
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
function loadSkill() {
|
|
428
|
+
let dir = __dirname2;
|
|
429
|
+
while (dir !== dirname2(dir)) {
|
|
430
|
+
const p = resolve2(dir, "SKILL.md");
|
|
431
|
+
if (existsSync2(p)) return readFileSync2(p, "utf-8");
|
|
432
|
+
dir = dirname2(dir);
|
|
433
|
+
}
|
|
434
|
+
throw new Error("SKILL.md not found in package");
|
|
435
|
+
}
|
|
436
|
+
function detectTargets(cwd) {
|
|
437
|
+
return TARGET_CANDIDATES.filter((p) => existsSync2(resolve2(cwd, p)));
|
|
438
|
+
}
|
|
439
|
+
function detectNewline(content) {
|
|
440
|
+
return content.includes("\r\n") ? "\r\n" : "\n";
|
|
441
|
+
}
|
|
442
|
+
function composeBlock(skill, eol) {
|
|
443
|
+
const body = skill.replace(/\r?\n/g, eol);
|
|
444
|
+
return `${SKILL_BEGIN}${eol}${body}${eol}${SKILL_END}`;
|
|
445
|
+
}
|
|
446
|
+
function applyBlock(existing, block, eol) {
|
|
447
|
+
const b = existing.indexOf(SKILL_BEGIN);
|
|
448
|
+
const e = existing.indexOf(SKILL_END);
|
|
449
|
+
if (b !== -1 && e !== -1) {
|
|
450
|
+
return existing.slice(0, b) + block + existing.slice(e + SKILL_END.length);
|
|
451
|
+
}
|
|
452
|
+
if (existing.length === 0) return `${block}${eol}`;
|
|
453
|
+
const sep2 = existing.endsWith(eol) ? "" : eol;
|
|
454
|
+
return `${existing}${sep2}${block}${eol}`;
|
|
455
|
+
}
|
|
456
|
+
function removeBlock(existing) {
|
|
457
|
+
const b = existing.indexOf(SKILL_BEGIN);
|
|
458
|
+
const e = existing.indexOf(SKILL_END);
|
|
459
|
+
if (b === -1 || e === -1) return null;
|
|
460
|
+
const out = existing.slice(0, b) + existing.slice(e + SKILL_END.length);
|
|
461
|
+
return out.replace(/(\r?\n){2,}$/, "$1");
|
|
462
|
+
}
|
|
463
|
+
function atomicWrite(target, content) {
|
|
464
|
+
const tmp = `${target}.${randomUUID()}.tmp`;
|
|
465
|
+
let temporaryCreated = false;
|
|
466
|
+
try {
|
|
467
|
+
const fd = openSync2(tmp, "wx");
|
|
468
|
+
temporaryCreated = true;
|
|
469
|
+
try {
|
|
470
|
+
writeFileSync(fd, content);
|
|
471
|
+
fsyncSync(fd);
|
|
472
|
+
} finally {
|
|
473
|
+
closeSync2(fd);
|
|
474
|
+
}
|
|
475
|
+
renameSync(tmp, target);
|
|
476
|
+
} catch (error) {
|
|
477
|
+
if (temporaryCreated) {
|
|
478
|
+
try {
|
|
479
|
+
rmSync2(tmp, { force: true });
|
|
480
|
+
} catch {
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
throw error;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
function resolveTarget(cwd, opts) {
|
|
487
|
+
if (opts.scope && opts.scope !== "user" && opts.scope !== "project") {
|
|
488
|
+
console.error(`Unknown --scope "${opts.scope}" (expected user or project)`);
|
|
489
|
+
return null;
|
|
490
|
+
}
|
|
491
|
+
if (opts.target) return resolve2(cwd, opts.target);
|
|
492
|
+
if (opts.scope === "user") {
|
|
493
|
+
if (!opts.agent) {
|
|
494
|
+
console.error("--scope user requires --agent (claude, codex, or hermes)");
|
|
495
|
+
return null;
|
|
496
|
+
}
|
|
497
|
+
const userTarget = userTargetFor(opts.agent);
|
|
498
|
+
if (userTarget) return userTarget;
|
|
499
|
+
console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, or hermes)`);
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
if (opts.agent) {
|
|
503
|
+
const mapped = AGENT_TARGET[opts.agent];
|
|
504
|
+
if (typeof mapped === "string") return resolve2(cwd, mapped);
|
|
505
|
+
console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, or hermes)`);
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
const matches = detectTargets(cwd);
|
|
509
|
+
if (matches.length === 0) return resolve2(cwd, DEFAULT_TARGET);
|
|
510
|
+
if (matches.length === 1) return resolve2(cwd, matches[0]);
|
|
511
|
+
console.error("Multiple rules files detected. Use --target to disambiguate:");
|
|
512
|
+
for (const m of matches) console.error(` ${m}`);
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
function runInstall(cwd, opts) {
|
|
516
|
+
if (opts.agent === "claude" && !opts.target) return installClaudePlugin(cwd, opts);
|
|
517
|
+
const target = resolveTarget(cwd, opts);
|
|
518
|
+
if (target === null) return 1;
|
|
519
|
+
const existing = existsSync2(target) ? readFileSync2(target, "utf-8") : "";
|
|
520
|
+
const eol = existing ? detectNewline(existing) : "\n";
|
|
521
|
+
const block = composeBlock(loadSkill(), eol);
|
|
522
|
+
const next = applyBlock(existing, block, eol);
|
|
523
|
+
if (next === existing) {
|
|
524
|
+
console.log("No changes \u2014 skill block already up to date.");
|
|
525
|
+
return 0;
|
|
526
|
+
}
|
|
527
|
+
if (opts.dryRun) {
|
|
528
|
+
process.stdout.write(createPatch(target, existing, next, "current", "proposed"));
|
|
529
|
+
return 0;
|
|
530
|
+
}
|
|
531
|
+
atomicWrite(target, next);
|
|
532
|
+
console.log(`Wrote ${Buffer.byteLength(next)} bytes to ${target}`);
|
|
533
|
+
return 0;
|
|
534
|
+
}
|
|
535
|
+
function runUninstall(cwd, opts) {
|
|
536
|
+
if (opts.agent === "claude" && !opts.target) return uninstallClaudePlugin(cwd, opts);
|
|
537
|
+
const target = resolveTarget(cwd, opts);
|
|
538
|
+
if (target === null) return 1;
|
|
539
|
+
if (!existsSync2(target)) {
|
|
540
|
+
console.log(`Skill block not present at ${target}`);
|
|
541
|
+
return 0;
|
|
542
|
+
}
|
|
543
|
+
const existing = readFileSync2(target, "utf-8");
|
|
544
|
+
const next = removeBlock(existing);
|
|
545
|
+
if (next === null) {
|
|
546
|
+
console.log(`Skill block not present at ${target}`);
|
|
547
|
+
return 0;
|
|
548
|
+
}
|
|
549
|
+
atomicWrite(target, next);
|
|
550
|
+
console.log(`Removed skill block from ${target}`);
|
|
551
|
+
return 0;
|
|
552
|
+
}
|
|
553
|
+
function runStatus(cwd, opts) {
|
|
554
|
+
if (opts.agent === "claude" && !opts.target) return statusClaudePlugin(cwd, opts);
|
|
555
|
+
const target = resolveTarget(cwd, opts);
|
|
556
|
+
if (target === null) return 1;
|
|
557
|
+
const fileExists = existsSync2(target);
|
|
558
|
+
let installed = false;
|
|
559
|
+
if (fileExists) {
|
|
560
|
+
const content = readFileSync2(target, "utf-8");
|
|
561
|
+
installed = content.includes(SKILL_BEGIN) && content.includes(SKILL_END);
|
|
562
|
+
}
|
|
563
|
+
if (opts.json) {
|
|
564
|
+
printJson({ installed, target });
|
|
565
|
+
return installed ? 0 : 1;
|
|
566
|
+
}
|
|
567
|
+
if (!fileExists) {
|
|
568
|
+
console.log(`No rules file at ${target}`);
|
|
569
|
+
return 1;
|
|
570
|
+
}
|
|
571
|
+
if (installed) {
|
|
572
|
+
console.log(`PRIM SKILL v1 installed at ${target}`);
|
|
573
|
+
return 0;
|
|
574
|
+
}
|
|
575
|
+
console.log(`No PRIM SKILL block at ${target}`);
|
|
576
|
+
return 1;
|
|
577
|
+
}
|
|
578
|
+
function registerSkillCommands(program) {
|
|
579
|
+
const skill = program.command("skill").description("Manage the prim skill in your project rules file");
|
|
580
|
+
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, or hermes (selects the default rules file)").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) => {
|
|
581
|
+
try {
|
|
582
|
+
process.exit(runInstall(process.cwd(), opts));
|
|
583
|
+
} catch (err) {
|
|
584
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
585
|
+
process.exit(2);
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
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, or hermes (selects the default rules file)").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").action((opts) => {
|
|
589
|
+
process.exit(runUninstall(process.cwd(), opts));
|
|
590
|
+
});
|
|
591
|
+
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, or hermes (selects the default rules file)").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--json", "Output as JSON").action((opts) => {
|
|
592
|
+
process.exit(runStatus(process.cwd(), opts));
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// src/lib/post-commit-hook.ts
|
|
597
|
+
import { execFileSync } from "child_process";
|
|
598
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
|
|
599
|
+
import {
|
|
600
|
+
constants as constants3,
|
|
601
|
+
closeSync as closeSync3,
|
|
602
|
+
existsSync as existsSync3,
|
|
603
|
+
fchmodSync,
|
|
604
|
+
fsyncSync as fsyncSync2,
|
|
605
|
+
lstatSync as lstatSync3,
|
|
606
|
+
mkdirSync as mkdirSync2,
|
|
607
|
+
openSync as openSync3,
|
|
608
|
+
readFileSync as readFileSync3,
|
|
609
|
+
renameSync as renameSync2,
|
|
610
|
+
unlinkSync,
|
|
611
|
+
writeFileSync as writeFileSync2
|
|
612
|
+
} from "fs";
|
|
613
|
+
import { basename, dirname as dirname3, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
|
|
614
|
+
var PRIM_POST_COMMIT_BLOCK_START = "# >>> prim post-commit hook >>>";
|
|
615
|
+
var PRIM_POST_COMMIT_BLOCK_END = "# <<< prim post-commit hook <<<";
|
|
616
|
+
var PRIM_CREATED_MARK = "prim-created-post-commit-hook";
|
|
617
|
+
var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
|
|
618
|
+
var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
|
|
619
|
+
var LEGACY_GLOBAL_OWNED_HEADER = "# prim global post-commit hook (core.hooksPath) \u2014 managed by prim; do not edit.";
|
|
620
|
+
var MAX_HOOK_BYTES = 1048576;
|
|
621
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
622
|
+
var SUPPORTED_SHEBANGS = /* @__PURE__ */ new Set([
|
|
623
|
+
"#!/bin/sh",
|
|
624
|
+
"#!/usr/bin/env sh",
|
|
625
|
+
"#!/bin/bash",
|
|
626
|
+
"#!/usr/bin/env bash",
|
|
627
|
+
"#!/bin/zsh",
|
|
628
|
+
"#!/usr/bin/env zsh"
|
|
629
|
+
]);
|
|
630
|
+
var HUSKY_V9_DISPATCHERS = /* @__PURE__ */ new Set([
|
|
631
|
+
'#!/usr/bin/env sh\n. "${0%/*}/h"',
|
|
632
|
+
'#!/usr/bin/env sh\n. "$(dirname "$0")/h"'
|
|
633
|
+
]);
|
|
634
|
+
var HUSKY_DIRECT_DISPATCHER = '#!/bin/sh\nexec sh "$(dirname "$0")/../post-commit"\n';
|
|
635
|
+
var HUSKY_V9_RUNTIME_HASHES = /* @__PURE__ */ new Set([
|
|
636
|
+
"d6aaa6f3f7c11008c525e649161df4a93152f1e55d0887fa1d7b8d622735d380",
|
|
637
|
+
"b02cb91cab7125a9e906be723a1b85297fc435a8307d429ae845546b4ee0ecde",
|
|
638
|
+
"9db5d129c4eb822a773157d98cd8fb8f1b156b85e3193117fefe527ca6d45e91",
|
|
639
|
+
"3b2cb21335e544b4ebce658ca47af4a69d2c77026cc4d3f8b2227c34d062b207",
|
|
640
|
+
"548990e1c11285694096184993d907b258d41235461a7ca2551e3b53ff9d3a38",
|
|
641
|
+
"c029a943acea5d6e2ddbaa271a1fb22c2da55d56b5c6fb59ca804ac9a4018708",
|
|
642
|
+
"ae3413a8fe2b39372de48bdc9691f42055f089c0c7529834b2fb07a131585b6a",
|
|
643
|
+
"70200b200ca709b0622784f93839a5b2872333a917a09afddefd7dc2d8cdc680"
|
|
644
|
+
]);
|
|
645
|
+
function currentPostCommitBlock() {
|
|
646
|
+
return `${PRIM_POST_COMMIT_BLOCK_START}
|
|
647
|
+
if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then
|
|
648
|
+
prim_commit_sha=$(git rev-parse --verify HEAD 2>/dev/null) || prim_commit_sha=
|
|
649
|
+
case "$prim_commit_sha" in *[!0-9a-f]*|"") prim_commit_sha= ;; esac
|
|
650
|
+
case "\${#prim_commit_sha}" in 40|64) ;; *) prim_commit_sha= ;; esac
|
|
651
|
+
if [ -n "$prim_commit_sha" ]; then
|
|
652
|
+
prim_commit_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_commit_branch=
|
|
653
|
+
prim_cache_dir="\${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin"
|
|
654
|
+
prim_post_commit_ran=0
|
|
655
|
+
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:-1440}" 2>/dev/null)" ]; then
|
|
656
|
+
prim_node=$(cat "$prim_cache_dir/node")
|
|
657
|
+
prim_entry=$(cat "$prim_cache_dir/prim-post-commit")
|
|
658
|
+
if [ -x "$prim_node" ] && [ -f "$prim_entry" ]; then
|
|
659
|
+
( trap '' HUP; export PRIM_COMMIT_SHA="$prim_commit_sha" PRIM_COMMIT_BRANCH="$prim_commit_branch"; "$prim_node" "$prim_entry" ) </dev/null >/dev/null 2>&1 &
|
|
660
|
+
prim_post_commit_ran=1
|
|
661
|
+
fi
|
|
662
|
+
fi
|
|
663
|
+
if [ "$prim_post_commit_ran" -eq 0 ]; then
|
|
664
|
+
if [ -x "./node_modules/.bin/prim-post-commit" ]; then
|
|
665
|
+
( trap '' HUP; export PRIM_COMMIT_SHA="$prim_commit_sha" PRIM_COMMIT_BRANCH="$prim_commit_branch"; ./node_modules/.bin/prim-post-commit ) </dev/null >/dev/null 2>&1 &
|
|
666
|
+
elif command -v npx >/dev/null 2>&1; then
|
|
667
|
+
( trap '' HUP; export PRIM_COMMIT_SHA="$prim_commit_sha" PRIM_COMMIT_BRANCH="$prim_commit_branch"; npx --yes -p @primitive.ai/prim@latest prim-post-commit ) </dev/null >/dev/null 2>&1 &
|
|
668
|
+
fi
|
|
669
|
+
fi
|
|
670
|
+
unset prim_cache_dir prim_post_commit_ran prim_node prim_entry prim_commit_branch
|
|
671
|
+
fi
|
|
672
|
+
unset prim_commit_sha
|
|
673
|
+
fi
|
|
674
|
+
${PRIM_POST_COMMIT_BLOCK_END}`;
|
|
675
|
+
}
|
|
676
|
+
function postCommitHookBlock() {
|
|
677
|
+
return currentPostCommitBlock();
|
|
678
|
+
}
|
|
679
|
+
function legacyFloatingInvocation() {
|
|
680
|
+
return `if command -v prim-post-commit >/dev/null 2>&1; then
|
|
681
|
+
prim-post-commit || true
|
|
682
|
+
elif [ -f "./node_modules/.bin/prim-post-commit" ]; then
|
|
683
|
+
./node_modules/.bin/prim-post-commit || true
|
|
684
|
+
else
|
|
685
|
+
npx --yes -p @primitive.ai/prim prim-post-commit 2>/dev/null || true
|
|
686
|
+
fi`;
|
|
687
|
+
}
|
|
688
|
+
function legacyGlobalGate() {
|
|
689
|
+
return Buffer.from(`if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then
|
|
690
|
+
${legacyFloatingInvocation()}
|
|
691
|
+
fi
|
|
692
|
+
`);
|
|
693
|
+
}
|
|
694
|
+
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;
|
|
695
|
+
var SHELL_QUOTED_RE = /^'(?:[^']|'"'"')*'$/u;
|
|
696
|
+
function decodePinnedPath(token) {
|
|
697
|
+
if (!token || !SHELL_QUOTED_RE.test(token)) return void 0;
|
|
698
|
+
const value = token.slice(1, -1).replaceAll(`'"'"'`, "'");
|
|
699
|
+
if (!isAbsolute2(value) || value.includes("\0") || value.includes("\n") || value.includes("\r")) {
|
|
700
|
+
return void 0;
|
|
701
|
+
}
|
|
702
|
+
return value;
|
|
703
|
+
}
|
|
704
|
+
function isPinnedInvocation(value) {
|
|
705
|
+
const match = PINNED_INVOCATION_RE.exec(value);
|
|
706
|
+
const node = decodePinnedPath(match?.groups?.node);
|
|
707
|
+
const entry = decodePinnedPath(match?.groups?.entry);
|
|
708
|
+
return Boolean(node && entry?.endsWith("/dist/hooks/post-commit.js"));
|
|
709
|
+
}
|
|
710
|
+
function legacyProjectPrefixLength(existing) {
|
|
711
|
+
const prefix = Buffer.from(`#!/bin/sh
|
|
712
|
+
${LEGACY_PRIM_OWNED_HEADER}
|
|
713
|
+
|
|
714
|
+
`);
|
|
715
|
+
if (!existing.subarray(0, prefix.length).equals(prefix)) return void 0;
|
|
716
|
+
const floating = Buffer.from(`${legacyFloatingInvocation()}
|
|
717
|
+
`);
|
|
718
|
+
if (existing.subarray(prefix.length, prefix.length + floating.length).equals(floating)) {
|
|
719
|
+
return prefix.length + floating.length;
|
|
720
|
+
}
|
|
721
|
+
const invocationEnd = existing.indexOf(10, prefix.length);
|
|
722
|
+
if (invocationEnd === -1) return void 0;
|
|
723
|
+
const invocation = existing.subarray(prefix.length, invocationEnd).toString("utf8");
|
|
724
|
+
return isPinnedInvocation(invocation) ? invocationEnd + 1 : void 0;
|
|
725
|
+
}
|
|
726
|
+
function isKnownLegacyGlobalGate(value) {
|
|
727
|
+
if (value.equals(legacyGlobalGate())) return true;
|
|
728
|
+
const prefix = Buffer.from(
|
|
729
|
+
'if [ "$(git config --get prim.active 2>/dev/null)" = "true" ]; then\n'
|
|
730
|
+
);
|
|
731
|
+
const suffix = Buffer.from("\nfi\n");
|
|
732
|
+
return value.subarray(0, prefix.length).equals(prefix) && value.subarray(-suffix.length).equals(suffix) && isPinnedInvocation(value.subarray(prefix.length, -suffix.length).toString("utf8"));
|
|
733
|
+
}
|
|
734
|
+
function createdScaffold() {
|
|
735
|
+
return Buffer.from(`#!/bin/sh
|
|
736
|
+
${currentPostCommitBlock()}
|
|
737
|
+
# ${PRIM_CREATED_MARK}
|
|
738
|
+
`);
|
|
739
|
+
}
|
|
740
|
+
function safeGitPath(root, value) {
|
|
741
|
+
if (value.length === 0 || value !== value.trim() || value.includes("\0") || value.includes("\n") || value.includes("\r")) {
|
|
742
|
+
throw new Error("Git returned an unsafe hooks path");
|
|
743
|
+
}
|
|
744
|
+
return isAbsolute2(value) ? resolve3(value) : resolve3(root, value);
|
|
745
|
+
}
|
|
746
|
+
function resolveEffectivePostCommitHook(cwd = process.cwd()) {
|
|
747
|
+
const gitRoot = gitToplevel(cwd);
|
|
748
|
+
if (!gitRoot) throw new Error("not a git repository");
|
|
749
|
+
const value = execFileSync("git", ["rev-parse", "--git-path", "hooks"], {
|
|
750
|
+
cwd: gitRoot,
|
|
751
|
+
encoding: "utf8",
|
|
752
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
753
|
+
timeout: GIT_TIMEOUT_MS
|
|
754
|
+
}).replace(/\r?\n$/u, "");
|
|
755
|
+
const hooksDir = safeGitPath(gitRoot, value);
|
|
756
|
+
if (basename(hooksDir) === "_" && basename(dirname3(hooksDir)) === ".husky") {
|
|
757
|
+
return {
|
|
758
|
+
gitRoot,
|
|
759
|
+
hooksDir,
|
|
760
|
+
hookPath: resolve3(dirname3(hooksDir), "post-commit"),
|
|
761
|
+
kind: "husky_v9",
|
|
762
|
+
dispatcherPath: resolve3(hooksDir, "post-commit")
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
return {
|
|
766
|
+
gitRoot,
|
|
767
|
+
hooksDir,
|
|
768
|
+
hookPath: resolve3(hooksDir, "post-commit"),
|
|
769
|
+
kind: "direct"
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
function assertSafeFile(path) {
|
|
773
|
+
if (!existsSync3(path)) return void 0;
|
|
774
|
+
const stat = lstatSync3(path);
|
|
775
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_HOOK_BYTES) {
|
|
776
|
+
throw new Error(`unsafe post-commit hook target: ${path}`);
|
|
777
|
+
}
|
|
778
|
+
return stat;
|
|
779
|
+
}
|
|
780
|
+
function assertUsableHuskyDispatcher(target) {
|
|
781
|
+
if (!target.dispatcherPath) return;
|
|
782
|
+
const stat = assertSafeFile(target.dispatcherPath);
|
|
783
|
+
if (!stat || (stat.mode & 64) === 0) {
|
|
784
|
+
throw new Error(
|
|
785
|
+
`Husky post-commit dispatcher is missing or not executable: ${target.dispatcherPath}`
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
const dispatcher = decodeHookText(readHookFile(target.dispatcherPath));
|
|
789
|
+
if (dispatcher === HUSKY_DIRECT_DISPATCHER) return;
|
|
790
|
+
const normalizedDispatcher = dispatcher.endsWith("\n") ? dispatcher.slice(0, -1) : dispatcher;
|
|
791
|
+
if (!HUSKY_V9_DISPATCHERS.has(normalizedDispatcher)) {
|
|
792
|
+
throw new Error(`unrecognized Husky post-commit dispatcher: ${target.dispatcherPath}`);
|
|
793
|
+
}
|
|
794
|
+
const huskyRuntime = resolve3(dirname3(target.dispatcherPath), "h");
|
|
795
|
+
const runtimeStat = assertSafeFile(huskyRuntime);
|
|
796
|
+
const runtime = runtimeStat ? readHookFile(huskyRuntime) : void 0;
|
|
797
|
+
const runtimeHash = runtime ? createHash2("sha256").update(runtime).digest("hex") : void 0;
|
|
798
|
+
if (!runtimeHash || !HUSKY_V9_RUNTIME_HASHES.has(runtimeHash)) {
|
|
799
|
+
throw new Error(`unrecognized Husky v9 hook runtime: ${huskyRuntime}`);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
function readHookFile(path) {
|
|
803
|
+
const value = readFileSync3(path);
|
|
804
|
+
return Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
805
|
+
}
|
|
806
|
+
function decodeHookText(content) {
|
|
807
|
+
if (content.includes(0)) throw new Error("binary post-commit hook");
|
|
808
|
+
try {
|
|
809
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(content);
|
|
810
|
+
} catch {
|
|
811
|
+
throw new Error("binary post-commit hook");
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
function supportedShebangEnd(content) {
|
|
815
|
+
const text = decodeHookText(content);
|
|
816
|
+
const newline = text.indexOf("\n");
|
|
817
|
+
const shebang = newline === -1 ? text : text.slice(0, newline);
|
|
818
|
+
if (!SUPPORTED_SHEBANGS.has(shebang) || newline === -1) {
|
|
819
|
+
throw new Error("unsupported post-commit hook interpreter");
|
|
820
|
+
}
|
|
821
|
+
return Buffer.byteLength(text.slice(0, newline + 1), "utf8");
|
|
822
|
+
}
|
|
823
|
+
function shellInsertionPoint(content, allowShebangless) {
|
|
824
|
+
const text = decodeHookText(content);
|
|
825
|
+
if (text.startsWith("#!")) return supportedShebangEnd(content);
|
|
826
|
+
if (allowShebangless) return 0;
|
|
827
|
+
throw new Error("unsupported post-commit hook interpreter");
|
|
828
|
+
}
|
|
829
|
+
function allIndexes(haystack, needle) {
|
|
830
|
+
const indexes = [];
|
|
831
|
+
let offset = 0;
|
|
832
|
+
while (offset <= haystack.length - needle.length) {
|
|
833
|
+
const index = haystack.indexOf(needle, offset);
|
|
834
|
+
if (index === -1) break;
|
|
835
|
+
indexes.push(index);
|
|
836
|
+
offset = index + needle.length;
|
|
837
|
+
}
|
|
838
|
+
return indexes;
|
|
839
|
+
}
|
|
840
|
+
function blockRange(content) {
|
|
841
|
+
decodeHookText(content);
|
|
842
|
+
const startMarker = Buffer.from(PRIM_POST_COMMIT_BLOCK_START);
|
|
843
|
+
const endMarker = Buffer.from(PRIM_POST_COMMIT_BLOCK_END);
|
|
844
|
+
const starts = allIndexes(content, startMarker);
|
|
845
|
+
const ends = allIndexes(content, endMarker);
|
|
846
|
+
if (starts.length === 0 && ends.length === 0) return { kind: "absent" };
|
|
847
|
+
if (starts.length !== 1 || ends.length !== 1 || ends[0] < starts[0]) {
|
|
848
|
+
throw new Error("malformed Prim post-commit markers");
|
|
849
|
+
}
|
|
850
|
+
const start = starts[0];
|
|
851
|
+
const end = ends[0] + endMarker.length;
|
|
852
|
+
const current = Buffer.from(currentPostCommitBlock());
|
|
853
|
+
return content.subarray(start, end).equals(current) ? { kind: "current", start, end } : { kind: "stale", start, end };
|
|
854
|
+
}
|
|
855
|
+
function mergedContent(existing, allowShebangless) {
|
|
856
|
+
const block = Buffer.from(currentPostCommitBlock());
|
|
857
|
+
if (!existing) {
|
|
858
|
+
return createdScaffold();
|
|
859
|
+
}
|
|
860
|
+
const range = blockRange(existing);
|
|
861
|
+
if (range.kind === "absent" && existing.toString("utf8").startsWith(`#!/bin/sh
|
|
862
|
+
${LEGACY_GLOBAL_OWNED_HEADER}
|
|
863
|
+
`)) {
|
|
864
|
+
const gateAt = existing.indexOf(Buffer.from('if [ "$(git config --get prim.active'));
|
|
865
|
+
const chainAt = existing.indexOf(Buffer.from("common_dir=$(git rev-parse --git-common-dir"));
|
|
866
|
+
if (gateAt === -1 || chainAt <= gateAt) {
|
|
867
|
+
throw new Error("malformed legacy Prim global post-commit hook");
|
|
868
|
+
}
|
|
869
|
+
if (!isKnownLegacyGlobalGate(existing.subarray(gateAt, chainAt))) {
|
|
870
|
+
throw new Error("unrecognized legacy Prim global post-commit invocation");
|
|
871
|
+
}
|
|
872
|
+
const withoutLegacyGate = Buffer.concat([
|
|
873
|
+
existing.subarray(0, gateAt),
|
|
874
|
+
existing.subarray(chainAt)
|
|
875
|
+
]);
|
|
876
|
+
const shebangEnd2 = shellInsertionPoint(withoutLegacyGate, allowShebangless);
|
|
877
|
+
return Buffer.concat([
|
|
878
|
+
withoutLegacyGate.subarray(0, shebangEnd2),
|
|
879
|
+
block,
|
|
880
|
+
Buffer.from("\n"),
|
|
881
|
+
withoutLegacyGate.subarray(shebangEnd2)
|
|
882
|
+
]);
|
|
883
|
+
}
|
|
884
|
+
if (range.kind === "absent" && existing.toString("utf8").startsWith(`#!/bin/sh
|
|
885
|
+
${LEGACY_PRIM_OWNED_HEADER}
|
|
886
|
+
`)) {
|
|
887
|
+
const prefixLength = legacyProjectPrefixLength(existing);
|
|
888
|
+
if (prefixLength === void 0) {
|
|
889
|
+
throw new Error("unrecognized legacy Prim post-commit invocation");
|
|
890
|
+
}
|
|
891
|
+
return Buffer.concat([createdScaffold(), existing.subarray(prefixLength)]);
|
|
892
|
+
}
|
|
893
|
+
if (range.kind !== "absent") {
|
|
894
|
+
const oldCreatedPrefixes = [
|
|
895
|
+
Buffer.from(`#!/bin/sh
|
|
896
|
+
# ${PRIM_CREATED_MARK}
|
|
897
|
+
|
|
898
|
+
`),
|
|
899
|
+
Buffer.from(`#!/bin/sh
|
|
900
|
+
# ${LEGACY_PRIM_CREATED_MARK}
|
|
901
|
+
|
|
902
|
+
`)
|
|
903
|
+
];
|
|
904
|
+
const oldCreated = oldCreatedPrefixes.some(
|
|
905
|
+
(prefix) => range.start === prefix.length && existing.subarray(0, prefix.length).equals(prefix)
|
|
906
|
+
);
|
|
907
|
+
if (oldCreated) {
|
|
908
|
+
const suffix = existing.subarray(range.end);
|
|
909
|
+
const tail = suffix.at(0) === 10 ? suffix.subarray(1) : suffix;
|
|
910
|
+
return Buffer.concat([createdScaffold(), tail]);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
const shebangEnd = shellInsertionPoint(existing, allowShebangless);
|
|
914
|
+
if (range.kind === "current" && range.start === shebangEnd) return existing;
|
|
915
|
+
let withoutBlock = existing;
|
|
916
|
+
if (range.kind !== "absent") {
|
|
917
|
+
const suffix = existing.subarray(range.end);
|
|
918
|
+
withoutBlock = Buffer.concat([
|
|
919
|
+
existing.subarray(0, range.start),
|
|
920
|
+
range.start === shebangEnd && suffix.at(0) === 10 ? suffix.subarray(1) : suffix
|
|
921
|
+
]);
|
|
922
|
+
}
|
|
923
|
+
return Buffer.concat([
|
|
924
|
+
withoutBlock.subarray(0, shebangEnd),
|
|
925
|
+
block,
|
|
926
|
+
Buffer.from("\n"),
|
|
927
|
+
withoutBlock.subarray(shebangEnd)
|
|
928
|
+
]);
|
|
929
|
+
}
|
|
930
|
+
function errorCode(error) {
|
|
931
|
+
return typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
932
|
+
}
|
|
933
|
+
function assertTargetUnchanged(path, expected, stat) {
|
|
934
|
+
let current;
|
|
935
|
+
try {
|
|
936
|
+
current = lstatSync3(path);
|
|
937
|
+
} catch (error) {
|
|
938
|
+
if (expected === void 0 && errorCode(error) === "ENOENT") return;
|
|
939
|
+
throw new Error(`post-commit hook changed concurrently: ${path}`);
|
|
940
|
+
}
|
|
941
|
+
if (expected === void 0) {
|
|
942
|
+
throw new Error(`post-commit hook appeared concurrently: ${path}`);
|
|
943
|
+
}
|
|
944
|
+
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)) {
|
|
945
|
+
throw new Error(`post-commit hook changed concurrently: ${path}`);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
function rewriteHookAtomically(path, next, expected, stat) {
|
|
949
|
+
const parent = dirname3(path);
|
|
950
|
+
mkdirSync2(parent, { recursive: true });
|
|
951
|
+
const temporary = resolve3(
|
|
952
|
+
parent,
|
|
953
|
+
`.${basename(path)}.prim-${String(process.pid)}-${randomUUID2()}.tmp`
|
|
954
|
+
);
|
|
955
|
+
let fd;
|
|
956
|
+
try {
|
|
957
|
+
fd = openSync3(
|
|
958
|
+
temporary,
|
|
959
|
+
constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW,
|
|
960
|
+
stat?.mode ?? 493
|
|
961
|
+
);
|
|
962
|
+
writeFileSync2(fd, next);
|
|
963
|
+
fchmodSync(fd, (stat?.mode ?? 493) & 4095);
|
|
964
|
+
fsyncSync2(fd);
|
|
965
|
+
closeSync3(fd);
|
|
966
|
+
fd = void 0;
|
|
967
|
+
assertTargetUnchanged(path, expected, stat);
|
|
968
|
+
renameSync2(temporary, path);
|
|
969
|
+
} finally {
|
|
970
|
+
if (fd !== void 0) {
|
|
971
|
+
try {
|
|
972
|
+
closeSync3(fd);
|
|
973
|
+
} catch {
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
try {
|
|
977
|
+
unlinkSync(temporary);
|
|
978
|
+
} catch (error) {
|
|
979
|
+
if (errorCode(error) !== "ENOENT") {
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
function unlinkHookUnchanged(path, expected, stat) {
|
|
985
|
+
assertTargetUnchanged(path, expected, stat);
|
|
986
|
+
unlinkSync(path);
|
|
987
|
+
}
|
|
988
|
+
function ensureEffectivePostCommitHook(cwd = process.cwd()) {
|
|
989
|
+
const target = resolveEffectivePostCommitHook(cwd);
|
|
990
|
+
return ensureTarget(target);
|
|
991
|
+
}
|
|
992
|
+
function ensureTarget(target, initialContent) {
|
|
993
|
+
assertUsableHuskyDispatcher(target);
|
|
994
|
+
const stat = assertSafeFile(target.hookPath);
|
|
995
|
+
if (stat && target.kind === "direct" && (stat.mode & 64) === 0) {
|
|
996
|
+
throw new Error(`existing post-commit hook is not executable: ${target.hookPath}`);
|
|
997
|
+
}
|
|
998
|
+
const existing = stat ? readHookFile(target.hookPath) : void 0;
|
|
999
|
+
const next = !existing && initialContent !== void 0 ? Buffer.from(initialContent) : mergedContent(existing, target.kind === "husky_v9");
|
|
1000
|
+
if (!existing && initialContent !== void 0) {
|
|
1001
|
+
const shebangEnd = shellInsertionPoint(next, target.kind === "husky_v9");
|
|
1002
|
+
const range = blockRange(next);
|
|
1003
|
+
if (range.kind !== "current" || range.start !== shebangEnd) {
|
|
1004
|
+
throw new Error("invalid initial Prim post-commit scaffold");
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
const contentChanged = !existing || !next.equals(existing);
|
|
1008
|
+
if (contentChanged) {
|
|
1009
|
+
rewriteHookAtomically(target.hookPath, next, existing, stat);
|
|
1010
|
+
}
|
|
1011
|
+
return { path: target.hookPath, changed: contentChanged || !stat, kind: target.kind };
|
|
1012
|
+
}
|
|
1013
|
+
function ensurePostCommitHookAtPath(hookPath, initialContent) {
|
|
1014
|
+
const absolute = resolve3(hookPath);
|
|
1015
|
+
const result = ensureTarget(
|
|
1016
|
+
{
|
|
1017
|
+
gitRoot: dirname3(dirname3(absolute)),
|
|
1018
|
+
hooksDir: dirname3(absolute),
|
|
1019
|
+
hookPath: absolute,
|
|
1020
|
+
kind: "direct"
|
|
1021
|
+
},
|
|
1022
|
+
initialContent
|
|
1023
|
+
);
|
|
1024
|
+
return { ...result, kind: "direct" };
|
|
1025
|
+
}
|
|
1026
|
+
function inspectEffectivePostCommitHook(cwd = process.cwd()) {
|
|
1027
|
+
const target = resolveEffectivePostCommitHook(cwd);
|
|
1028
|
+
try {
|
|
1029
|
+
assertUsableHuskyDispatcher(target);
|
|
1030
|
+
} catch (error) {
|
|
1031
|
+
const missing = error instanceof Error && (error.message.includes("missing or not executable") || error.message.includes("unsafe"));
|
|
1032
|
+
return {
|
|
1033
|
+
...target,
|
|
1034
|
+
covered: false,
|
|
1035
|
+
executable: false,
|
|
1036
|
+
current: false,
|
|
1037
|
+
reason: missing ? "husky_dispatcher_missing" : "husky_dispatcher_invalid"
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
let stat;
|
|
1041
|
+
try {
|
|
1042
|
+
stat = assertSafeFile(target.hookPath);
|
|
1043
|
+
} catch {
|
|
1044
|
+
return {
|
|
1045
|
+
...target,
|
|
1046
|
+
covered: false,
|
|
1047
|
+
executable: false,
|
|
1048
|
+
current: false,
|
|
1049
|
+
reason: "unsafe_target"
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
if (!stat) {
|
|
1053
|
+
return {
|
|
1054
|
+
...target,
|
|
1055
|
+
covered: false,
|
|
1056
|
+
executable: false,
|
|
1057
|
+
current: false,
|
|
1058
|
+
reason: "missing"
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
const executable = target.kind === "husky_v9" || (stat.mode & 64) !== 0;
|
|
1062
|
+
try {
|
|
1063
|
+
const content = readHookFile(target.hookPath);
|
|
1064
|
+
const shebangEnd = shellInsertionPoint(content, target.kind === "husky_v9");
|
|
1065
|
+
const range = blockRange(content);
|
|
1066
|
+
const positioned = range.kind !== "absent" && range.start === shebangEnd;
|
|
1067
|
+
const current = range.kind === "current" && positioned;
|
|
1068
|
+
return {
|
|
1069
|
+
...target,
|
|
1070
|
+
covered: current && executable,
|
|
1071
|
+
executable,
|
|
1072
|
+
current,
|
|
1073
|
+
reason: range.kind === "current" && !positioned ? "unreachable_block" : !current ? "stale_block" : executable ? void 0 : "not_executable"
|
|
1074
|
+
};
|
|
1075
|
+
} catch (error) {
|
|
1076
|
+
const message = error instanceof Error ? error.message : "";
|
|
1077
|
+
const reason = message.includes("binary") ? "binary" : message.includes("unsupported") ? "unsupported_interpreter" : "malformed_markers";
|
|
1078
|
+
return {
|
|
1079
|
+
...target,
|
|
1080
|
+
covered: false,
|
|
1081
|
+
executable,
|
|
1082
|
+
current: false,
|
|
1083
|
+
reason
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
function uninstallEffectivePostCommitHook(cwd = process.cwd()) {
|
|
1088
|
+
const target = resolveEffectivePostCommitHook(cwd);
|
|
1089
|
+
return uninstallTarget(target);
|
|
1090
|
+
}
|
|
1091
|
+
function projectHooksPathIsConfigured(gitRoot) {
|
|
1092
|
+
for (const scope of ["--worktree", "--local"]) {
|
|
1093
|
+
try {
|
|
1094
|
+
const value = execFileSync("git", ["config", scope, "--get", "core.hooksPath"], {
|
|
1095
|
+
cwd: gitRoot,
|
|
1096
|
+
encoding: "utf8",
|
|
1097
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1098
|
+
timeout: GIT_TIMEOUT_MS
|
|
1099
|
+
}).trim();
|
|
1100
|
+
if (value.length > 0) return true;
|
|
1101
|
+
} catch {
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
return false;
|
|
1105
|
+
}
|
|
1106
|
+
function uninstallProjectPostCommitHook(cwd = process.cwd()) {
|
|
1107
|
+
const gitRoot = gitToplevel(cwd);
|
|
1108
|
+
if (!gitRoot) throw new Error("not a git repository");
|
|
1109
|
+
if (projectHooksPathIsConfigured(gitRoot)) {
|
|
1110
|
+
return uninstallEffectivePostCommitHook(gitRoot);
|
|
1111
|
+
}
|
|
1112
|
+
const commonDir = execFileSync("git", ["rev-parse", "--git-common-dir"], {
|
|
1113
|
+
cwd: gitRoot,
|
|
1114
|
+
encoding: "utf8",
|
|
1115
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1116
|
+
timeout: GIT_TIMEOUT_MS
|
|
1117
|
+
}).replace(/\r?\n$/u, "");
|
|
1118
|
+
return uninstallPostCommitHookAtPath(
|
|
1119
|
+
resolve3(safeGitPath(gitRoot, commonDir), "hooks", "post-commit")
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
function uninstallTarget(target) {
|
|
1123
|
+
const stat = assertSafeFile(target.hookPath);
|
|
1124
|
+
if (!stat) return { path: target.hookPath, changed: false, removedFile: false };
|
|
1125
|
+
const existing = readHookFile(target.hookPath);
|
|
1126
|
+
const range = blockRange(existing);
|
|
1127
|
+
if (range.kind === "absent") {
|
|
1128
|
+
if (existing.toString("utf8").startsWith(`#!/bin/sh
|
|
1129
|
+
${LEGACY_PRIM_OWNED_HEADER}
|
|
1130
|
+
`)) {
|
|
1131
|
+
const prefixLength = legacyProjectPrefixLength(existing);
|
|
1132
|
+
if (prefixLength === void 0) {
|
|
1133
|
+
throw new Error("unrecognized legacy Prim post-commit invocation");
|
|
1134
|
+
}
|
|
1135
|
+
const tail = existing.subarray(prefixLength);
|
|
1136
|
+
if (tail.length === 0) {
|
|
1137
|
+
unlinkHookUnchanged(target.hookPath, existing, stat);
|
|
1138
|
+
return { path: target.hookPath, changed: true, removedFile: true };
|
|
1139
|
+
}
|
|
1140
|
+
rewriteHookAtomically(
|
|
1141
|
+
target.hookPath,
|
|
1142
|
+
Buffer.concat([Buffer.from("#!/bin/sh\n"), tail]),
|
|
1143
|
+
existing,
|
|
1144
|
+
stat
|
|
1145
|
+
);
|
|
1146
|
+
return { path: target.hookPath, changed: true, removedFile: false };
|
|
1147
|
+
}
|
|
1148
|
+
return { path: target.hookPath, changed: false, removedFile: false };
|
|
1149
|
+
}
|
|
1150
|
+
const shebangEnd = shellInsertionPoint(existing, target.kind === "husky_v9");
|
|
1151
|
+
const suffix = existing.subarray(range.end);
|
|
1152
|
+
const createdSuffix = Buffer.from(`
|
|
1153
|
+
# ${PRIM_CREATED_MARK}
|
|
1154
|
+
`);
|
|
1155
|
+
if (range.start === shebangEnd && suffix.subarray(0, createdSuffix.length).equals(createdSuffix)) {
|
|
1156
|
+
const tail = suffix.subarray(createdSuffix.length);
|
|
1157
|
+
if (tail.length === 0) {
|
|
1158
|
+
unlinkHookUnchanged(target.hookPath, existing, stat);
|
|
1159
|
+
return { path: target.hookPath, changed: true, removedFile: true };
|
|
1160
|
+
}
|
|
1161
|
+
rewriteHookAtomically(
|
|
1162
|
+
target.hookPath,
|
|
1163
|
+
Buffer.concat([existing.subarray(0, shebangEnd), tail]),
|
|
1164
|
+
existing,
|
|
1165
|
+
stat
|
|
1166
|
+
);
|
|
1167
|
+
return { path: target.hookPath, changed: true, removedFile: false };
|
|
1168
|
+
}
|
|
1169
|
+
const createdPrefixes = [
|
|
1170
|
+
Buffer.from(`#!/bin/sh
|
|
1171
|
+
# ${PRIM_CREATED_MARK}
|
|
1172
|
+
|
|
1173
|
+
`),
|
|
1174
|
+
Buffer.from(`#!/bin/sh
|
|
1175
|
+
# ${LEGACY_PRIM_CREATED_MARK}
|
|
1176
|
+
|
|
1177
|
+
`)
|
|
1178
|
+
];
|
|
1179
|
+
const createdPrefix = createdPrefixes.find(
|
|
1180
|
+
(prefix) => range.start === prefix.length && existing.subarray(0, prefix.length).equals(prefix)
|
|
1181
|
+
);
|
|
1182
|
+
if (createdPrefix) {
|
|
1183
|
+
const tail = suffix.at(0) === 10 ? suffix.subarray(1) : suffix;
|
|
1184
|
+
if (tail.length === 0) {
|
|
1185
|
+
unlinkHookUnchanged(target.hookPath, existing, stat);
|
|
1186
|
+
return { path: target.hookPath, changed: true, removedFile: true };
|
|
1187
|
+
}
|
|
1188
|
+
rewriteHookAtomically(
|
|
1189
|
+
target.hookPath,
|
|
1190
|
+
Buffer.concat([Buffer.from("#!/bin/sh\n"), tail]),
|
|
1191
|
+
existing,
|
|
1192
|
+
stat
|
|
1193
|
+
);
|
|
1194
|
+
return { path: target.hookPath, changed: true, removedFile: false };
|
|
1195
|
+
}
|
|
1196
|
+
const next = Buffer.concat([
|
|
1197
|
+
existing.subarray(0, range.start),
|
|
1198
|
+
range.start === shebangEnd && suffix.at(0) === 10 ? suffix.subarray(1) : suffix
|
|
1199
|
+
]);
|
|
1200
|
+
rewriteHookAtomically(target.hookPath, next, existing, stat);
|
|
1201
|
+
return { path: target.hookPath, changed: true, removedFile: false };
|
|
1202
|
+
}
|
|
1203
|
+
function uninstallPostCommitHookAtPath(hookPath) {
|
|
1204
|
+
const absolute = resolve3(hookPath);
|
|
1205
|
+
return uninstallTarget({
|
|
1206
|
+
gitRoot: dirname3(dirname3(absolute)),
|
|
1207
|
+
hooksDir: dirname3(absolute),
|
|
1208
|
+
hookPath: absolute,
|
|
1209
|
+
kind: "direct"
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// src/lib/repository-binding.ts
|
|
1214
|
+
async function bindRepository(root, options) {
|
|
1215
|
+
const repositoryFullName = githubRepositoryFullName(root);
|
|
1216
|
+
if (!repositoryFullName) {
|
|
1217
|
+
throw new Error("origin must be a GitHub HTTPS/SSH remote in owner/name form");
|
|
1218
|
+
}
|
|
1219
|
+
const response = await getClient().post(
|
|
1220
|
+
"/api/cli/repositories/bind",
|
|
1221
|
+
{ repositoryFullName },
|
|
1222
|
+
options
|
|
1223
|
+
);
|
|
1224
|
+
if (!isValidRepoSyncId(response.repoSyncId)) {
|
|
1225
|
+
throw new Error("server returned no repository binding");
|
|
1226
|
+
}
|
|
1227
|
+
setRepoSyncId(root, response.repoSyncId);
|
|
1228
|
+
return { repoSyncId: response.repoSyncId, repositoryFullName };
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
export {
|
|
1232
|
+
postCommitHookBlock,
|
|
1233
|
+
ensureEffectivePostCommitHook,
|
|
1234
|
+
ensurePostCommitHookAtPath,
|
|
1235
|
+
inspectEffectivePostCommitHook,
|
|
1236
|
+
uninstallProjectPostCommitHook,
|
|
1237
|
+
uninstallPostCommitHookAtPath,
|
|
1238
|
+
bindRepository,
|
|
1239
|
+
printJson,
|
|
1240
|
+
compareSemver,
|
|
1241
|
+
refreshClaudePlugins,
|
|
1242
|
+
hasUsableCodexGuidance,
|
|
1243
|
+
registerSkillCommands
|
|
1244
|
+
};
|