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