@primitive.ai/prim 0.1.0-alpha.61 → 0.1.0-alpha.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,620 +0,0 @@
1
- import {
2
- gitToplevel,
3
- githubRepositoryFullName,
4
- setRepoSyncId
5
- } from "./chunk-LDQZASIF.js";
6
- import {
7
- getClient,
8
- withFileLock
9
- } from "./chunk-I3HIPAIR.js";
10
-
11
- // src/commands/skill.ts
12
- import { randomUUID } from "crypto";
13
- import {
14
- constants as constants2,
15
- closeSync as closeSync2,
16
- existsSync as existsSync2,
17
- fstatSync as fstatSync2,
18
- fsyncSync,
19
- lstatSync as lstatSync2,
20
- openSync as openSync2,
21
- readFileSync as readFileSync2,
22
- readSync as readSync2,
23
- renameSync,
24
- rmSync as rmSync2,
25
- writeFileSync
26
- } from "fs";
27
- import { homedir as homedir2 } from "os";
28
- import { dirname as dirname2, join as join2, resolve as resolve2 } from "path";
29
- import { fileURLToPath as fileURLToPath2 } from "url";
30
- import { createPatch } from "diff";
31
- import { parse as parseYaml2 } from "yaml";
32
-
33
- // src/output.ts
34
- function printJson(data) {
35
- console.log(JSON.stringify(data, null, 2));
36
- }
37
-
38
- // src/commands/claude-plugin.ts
39
- import { createHash } from "crypto";
40
- import {
41
- constants,
42
- closeSync,
43
- existsSync,
44
- fstatSync,
45
- lstatSync,
46
- mkdirSync,
47
- openSync,
48
- readFileSync,
49
- readSync,
50
- readdirSync,
51
- realpathSync,
52
- rmSync,
53
- rmdirSync
54
- } from "fs";
55
- import { homedir } from "os";
56
- import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
57
- import { fileURLToPath } from "url";
58
- import { parse as parseYaml } from "yaml";
59
-
60
- // src/lib/semver.ts
61
- function parseSemver(value) {
62
- if (typeof value !== "string" || value.length > 256) return;
63
- const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
64
- value
65
- );
66
- if (!match) return;
67
- const prerelease = match[4]?.split(".") ?? [];
68
- if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
69
- return;
70
- }
71
- return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
72
- }
73
- function compareSemver(left, right) {
74
- const a = parseSemver(left);
75
- const b = parseSemver(right);
76
- if (!a || !b) return;
77
- for (let i = 0; i < a.core.length; i += 1) {
78
- if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
79
- }
80
- if (a.prerelease.length === 0 || b.prerelease.length === 0) {
81
- return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
82
- }
83
- for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
84
- const x = a.prerelease[i];
85
- const y = b.prerelease[i];
86
- if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
87
- if (x === y) continue;
88
- const xNumeric = /^\d+$/u.test(x);
89
- const yNumeric = /^\d+$/u.test(y);
90
- if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
91
- if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
92
- return x < y ? -1 : 1;
93
- }
94
- return 0;
95
- }
96
-
97
- // src/commands/claude-plugin.ts
98
- var __dirname = dirname(fileURLToPath(import.meta.url));
99
- var PLUGIN_DESCRIPTION = "Primitive decision-graph guidance for the prim CLI \u2014 a model-invoked skill installed by prim skill install.";
100
- var MAX_MANIFEST_BYTES = 64 * 1024;
101
- var MAX_SKILL_BYTES = 1024 * 1024;
102
- var REFRESH_LOCK_TIMEOUT_MS = 150;
103
- var REFRESH_LOCK_POLL_MS = 10;
104
- function pluginDirFor(cwd, scope) {
105
- const base = scope === "user" ? join(homedir(), ".claude") : join(gitToplevel(cwd) ?? cwd, ".claude");
106
- return join(base, "skills", "prim");
107
- }
108
- function resolvePluginDir(cwd, scope) {
109
- if (scope && scope !== "user" && scope !== "project") {
110
- console.error(`Unknown --scope "${scope}" (expected user or project)`);
111
- return null;
112
- }
113
- return pluginDirFor(cwd, scope === "user" ? "user" : "project");
114
- }
115
- function packageVersion() {
116
- let dir = __dirname;
117
- while (dir !== dirname(dir)) {
118
- const p = resolve(dir, "package.json");
119
- if (existsSync(p)) return JSON.parse(readFileSync(p, "utf-8")).version;
120
- dir = dirname(dir);
121
- }
122
- return "0.0.0";
123
- }
124
- function pluginManifest(version) {
125
- const manifest = { name: "prim", description: PLUGIN_DESCRIPTION, version };
126
- return `${JSON.stringify(manifest, null, 2)}
127
- `;
128
- }
129
- function renderClaudePlugin() {
130
- const version = packageVersion();
131
- return { manifest: pluginManifest(version), skill: loadSkill(), version };
132
- }
133
- function removeDirIfEmpty(dir) {
134
- if (existsSync(dir) && readdirSync(dir).length === 0) rmdirSync(dir);
135
- }
136
- function pluginPaths(dir) {
137
- return {
138
- manifestPath: join(dir, ".claude-plugin", "plugin.json"),
139
- skillPath: join(dir, "SKILL.md")
140
- };
141
- }
142
- function pathIsInside(root, path) {
143
- const rel = relative(root, path);
144
- return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
145
- }
146
- function managedPathsAreSafe(paths, projectRoot) {
147
- try {
148
- const managed = [paths.manifestPath, paths.skillPath];
149
- if (managed.some((path) => !lstatSync(path).isFile())) return false;
150
- if (projectRoot === void 0) return true;
151
- const realRoot = realpathSync(projectRoot);
152
- return managed.every((path) => pathIsInside(realRoot, realpathSync(path)));
153
- } catch {
154
- return false;
155
- }
156
- }
157
- function readBoundedRegularFile(path, maxBytes) {
158
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
159
- try {
160
- const stat = fstatSync(fd);
161
- if (!stat.isFile() || stat.size > maxBytes) throw new Error("unsafe managed file");
162
- const chunks = [];
163
- let total = 0;
164
- while (total <= maxBytes) {
165
- const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1 - total));
166
- const bytesRead = readSync(fd, chunk, 0, chunk.length, null);
167
- if (bytesRead === 0) break;
168
- chunks.push(chunk.subarray(0, bytesRead));
169
- total += bytesRead;
170
- }
171
- if (total > maxBytes) throw new Error("unsafe managed file");
172
- return Buffer.concat(chunks, total).toString("utf8");
173
- } finally {
174
- closeSync(fd);
175
- }
176
- }
177
- function hasUsablePrimFrontmatter(skill) {
178
- const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/u.exec(skill);
179
- if (!match) return false;
180
- try {
181
- const parsed = parseYaml(match[1]);
182
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
183
- const frontmatter = parsed;
184
- return frontmatter.name === "prim" && typeof frontmatter.description === "string" && frontmatter.description.trim().length > 0 && match[2].trim().length > 0;
185
- } catch {
186
- return false;
187
- }
188
- }
189
- function inspectRecognizedInstallation(paths, projectRoot) {
190
- if (!existsSync(paths.manifestPath) || !existsSync(paths.skillPath)) return;
191
- if (!managedPathsAreSafe(paths, projectRoot)) return;
192
- const manifest = readBoundedRegularFile(paths.manifestPath, MAX_MANIFEST_BYTES);
193
- const parsed = JSON.parse(manifest);
194
- if (parsed.name !== "prim") return;
195
- const skill = readBoundedRegularFile(paths.skillPath, MAX_SKILL_BYTES);
196
- return {
197
- manifest,
198
- manifestVersion: parsed.version,
199
- skill,
200
- usable: hasUsablePrimFrontmatter(skill)
201
- };
202
- }
203
- function refreshLockDir(physicalPluginDir) {
204
- const cacheRoot = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
205
- const identity = createHash("sha256").update(physicalPluginDir).digest("hex");
206
- return join(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
207
- }
208
- async function refreshClaudePlugins(cwd, options = {}) {
209
- const result = { installed: 0, refreshed: 0 };
210
- const candidates = [];
211
- if (options.includeProject !== false) {
212
- const projectRoot = options.projectRoot ?? gitToplevel(cwd);
213
- if (projectRoot !== null && isAbsolute(projectRoot)) {
214
- candidates.push({ dir: join(projectRoot, ".claude", "skills", "prim"), projectRoot });
215
- }
216
- }
217
- candidates.push({ dir: pluginDirFor(cwd, "user") });
218
- const seen = /* @__PURE__ */ new Set();
219
- let desired;
220
- for (const { dir, projectRoot } of candidates) {
221
- let counted = false;
222
- const markInstalled = () => {
223
- if (!counted) {
224
- result.installed += 1;
225
- counted = true;
226
- }
227
- };
228
- const refreshCandidate = () => {
229
- const { manifestPath, skillPath } = pluginPaths(dir);
230
- const paths = { manifestPath, skillPath };
231
- try {
232
- let changed = false;
233
- const current = inspectRecognizedInstallation(paths, projectRoot);
234
- if (!current) return;
235
- desired ??= renderClaudePlugin();
236
- if (projectRoot !== void 0 && current.usable && compareSemver(current.manifestVersion, desired.version) === 1) {
237
- markInstalled();
238
- return;
239
- }
240
- if (current.manifest !== desired.manifest) {
241
- if (!managedPathsAreSafe(paths, projectRoot)) throw new Error("unsafe managed path");
242
- atomicWrite(manifestPath, desired.manifest);
243
- if (!changed) result.refreshed += 1;
244
- changed = true;
245
- }
246
- if (current.skill !== desired.skill) {
247
- if (!managedPathsAreSafe(paths, projectRoot)) throw new Error("unsafe managed path");
248
- atomicWrite(skillPath, desired.skill);
249
- if (!changed) result.refreshed += 1;
250
- changed = true;
251
- }
252
- markInstalled();
253
- } catch {
254
- try {
255
- if (inspectRecognizedInstallation(paths, projectRoot)?.usable) markInstalled();
256
- } catch {
257
- }
258
- }
259
- };
260
- try {
261
- const paths = pluginPaths(dir);
262
- if (!existsSync(paths.manifestPath) || !existsSync(paths.skillPath)) continue;
263
- const physicalPluginDir = realpathSync(dir);
264
- if (seen.has(physicalPluginDir)) continue;
265
- seen.add(physicalPluginDir);
266
- await withFileLock(refreshLockDir(physicalPluginDir), refreshCandidate, {
267
- timeoutMs: REFRESH_LOCK_TIMEOUT_MS,
268
- pollMs: REFRESH_LOCK_POLL_MS
269
- });
270
- } catch {
271
- }
272
- }
273
- return result;
274
- }
275
- function installClaudePlugin(cwd, opts) {
276
- const dir = resolvePluginDir(cwd, opts.scope);
277
- if (dir === null) return 1;
278
- const { manifestPath, skillPath } = pluginPaths(dir);
279
- const { manifest, skill } = renderClaudePlugin();
280
- const manifestCurrent = existsSync(manifestPath) ? readFileSync(manifestPath, "utf-8") : null;
281
- const skillCurrent = existsSync(skillPath) ? readFileSync(skillPath, "utf-8") : null;
282
- if (manifestCurrent === manifest && skillCurrent === skill) {
283
- console.log("No changes \u2014 prim skill plugin already up to date.");
284
- return 0;
285
- }
286
- if (opts.dryRun) {
287
- console.log(`Would write plugin to ${dir} (.claude-plugin/plugin.json + SKILL.md)`);
288
- return 0;
289
- }
290
- mkdirSync(join(dir, ".claude-plugin"), { recursive: true });
291
- atomicWrite(manifestPath, manifest);
292
- atomicWrite(skillPath, skill);
293
- console.log(`Installed prim skill plugin at ${dir}`);
294
- console.log("Restart Claude Code or run /reload-plugins to load it.");
295
- if (opts.scope !== "user") {
296
- console.log("Project-scope plugins load only when Claude Code launches from this directory.");
297
- }
298
- return 0;
299
- }
300
- function uninstallClaudePlugin(cwd, opts) {
301
- const dir = resolvePluginDir(cwd, opts.scope);
302
- if (dir === null) return 1;
303
- const { manifestPath, skillPath } = pluginPaths(dir);
304
- if (!existsSync(manifestPath) && !existsSync(skillPath)) {
305
- console.log(`prim skill plugin not present at ${dir}`);
306
- return 0;
307
- }
308
- rmSync(manifestPath, { force: true });
309
- rmSync(skillPath, { force: true });
310
- removeDirIfEmpty(join(dir, ".claude-plugin"));
311
- removeDirIfEmpty(dir);
312
- console.log(`Removed prim skill plugin from ${dir}`);
313
- return 0;
314
- }
315
- function statusClaudePlugin(cwd, opts) {
316
- const dir = resolvePluginDir(cwd, opts.scope);
317
- if (dir === null) return 1;
318
- const { skillPath } = pluginPaths(dir);
319
- const installed = existsSync(skillPath);
320
- if (opts.json) {
321
- printJson({ installed, target: dir });
322
- return installed ? 0 : 1;
323
- }
324
- if (installed) {
325
- console.log(`prim skill plugin installed at ${dir}`);
326
- return 0;
327
- }
328
- console.log(`No prim skill plugin at ${dir}`);
329
- return 1;
330
- }
331
-
332
- // src/commands/skill.ts
333
- var __dirname2 = dirname2(fileURLToPath2(import.meta.url));
334
- var SKILL_BEGIN = "<!-- BEGIN PRIM SKILL v1 -->";
335
- var SKILL_END = "<!-- END PRIM SKILL v1 -->";
336
- var CODEX_GUIDANCE_LIMIT_BYTES = 1024 * 1024;
337
- var CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES = 32 * 1024;
338
- var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
339
- var SKILL_END_BUFFER = Buffer.from(SKILL_END);
340
- function readCodexGuidance(path) {
341
- try {
342
- const entry = lstatSync2(path);
343
- if (entry.isSymbolicLink() || !entry.isFile()) return null;
344
- const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
345
- try {
346
- const opened = fstatSync2(fd);
347
- if (!opened.isFile() || opened.size > CODEX_GUIDANCE_LIMIT_BYTES) return null;
348
- const bytes = Buffer.allocUnsafe(CODEX_GUIDANCE_LIMIT_BYTES + 1);
349
- let length = 0;
350
- while (length < bytes.length) {
351
- const read = readSync2(fd, bytes, length, bytes.length - length, length);
352
- if (read === 0) break;
353
- length += read;
354
- }
355
- return length > CODEX_GUIDANCE_LIMIT_BYTES ? null : bytes.subarray(0, length);
356
- } finally {
357
- closeSync2(fd);
358
- }
359
- } catch (error) {
360
- const code = error.code;
361
- return code === "ENOENT" || code === "ENOTDIR" ? void 0 : null;
362
- }
363
- }
364
- function effectiveCodexGuidance(scope) {
365
- const override = readCodexGuidance(join2(scope, "AGENTS.override.md"));
366
- if (override === null) return null;
367
- if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
368
- const base = readCodexGuidance(join2(scope, "AGENTS.md"));
369
- return base ?? null;
370
- }
371
- function hasUsablePrimBlock(content, visibleBytes) {
372
- const begin = content.indexOf(SKILL_BEGIN_BUFFER);
373
- const end = content.indexOf(SKILL_END_BUFFER);
374
- 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) {
375
- return false;
376
- }
377
- const block = content.subarray(begin + SKILL_BEGIN_BUFFER.length, end).toString("utf8").trim();
378
- const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/u.exec(block);
379
- if (!match || match[2].trim().length === 0) return false;
380
- try {
381
- const metadata = parseYaml2(match[1]);
382
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return false;
383
- const fields = metadata;
384
- return fields.name === "prim" && typeof fields.description === "string" && fields.description.trim().length > 0;
385
- } catch {
386
- return false;
387
- }
388
- }
389
- function hasUsableCodexGuidance(projectRoot) {
390
- try {
391
- const codexHome = process.env.CODEX_HOME?.trim() ? resolve2(process.env.CODEX_HOME) : join2(homedir2(), ".codex");
392
- const scopes = [
393
- { path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
394
- { path: projectRoot, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
395
- ];
396
- return scopes.some(({ path, visibleBytes }) => {
397
- const guidance = effectiveCodexGuidance(path);
398
- return guidance !== null && hasUsablePrimBlock(guidance, visibleBytes);
399
- });
400
- } catch {
401
- return false;
402
- }
403
- }
404
- var TARGET_CANDIDATES = [
405
- "CLAUDE.md",
406
- "AGENTS.md",
407
- ".hermes.md",
408
- ".cursor/rules",
409
- ".windsurfrules",
410
- ".github/instructions/primitive.md"
411
- ];
412
- var DEFAULT_TARGET = "CLAUDE.md";
413
- var AGENT_TARGET = {
414
- claude: "CLAUDE.md",
415
- codex: "AGENTS.md",
416
- hermes: ".hermes.md"
417
- };
418
- function userTargetFor(agent) {
419
- if (agent === "claude") return join2(homedir2(), ".claude", "CLAUDE.md");
420
- if (agent === "codex") return join2(homedir2(), ".codex", "AGENTS.md");
421
- if (agent === "hermes") {
422
- return join2(process.env.HERMES_HOME ?? join2(homedir2(), ".hermes"), ".hermes.md");
423
- }
424
- return null;
425
- }
426
- function loadSkill() {
427
- let dir = __dirname2;
428
- while (dir !== dirname2(dir)) {
429
- const p = resolve2(dir, "SKILL.md");
430
- if (existsSync2(p)) return readFileSync2(p, "utf-8");
431
- dir = dirname2(dir);
432
- }
433
- throw new Error("SKILL.md not found in package");
434
- }
435
- function detectTargets(cwd) {
436
- return TARGET_CANDIDATES.filter((p) => existsSync2(resolve2(cwd, p)));
437
- }
438
- function detectNewline(content) {
439
- return content.includes("\r\n") ? "\r\n" : "\n";
440
- }
441
- function composeBlock(skill, eol) {
442
- const body = skill.replace(/\r?\n/g, eol);
443
- return `${SKILL_BEGIN}${eol}${body}${eol}${SKILL_END}`;
444
- }
445
- function applyBlock(existing, block, eol) {
446
- const b = existing.indexOf(SKILL_BEGIN);
447
- const e = existing.indexOf(SKILL_END);
448
- if (b !== -1 && e !== -1) {
449
- return existing.slice(0, b) + block + existing.slice(e + SKILL_END.length);
450
- }
451
- if (existing.length === 0) return `${block}${eol}`;
452
- const sep2 = existing.endsWith(eol) ? "" : eol;
453
- return `${existing}${sep2}${block}${eol}`;
454
- }
455
- function removeBlock(existing) {
456
- const b = existing.indexOf(SKILL_BEGIN);
457
- const e = existing.indexOf(SKILL_END);
458
- if (b === -1 || e === -1) return null;
459
- const out = existing.slice(0, b) + existing.slice(e + SKILL_END.length);
460
- return out.replace(/(\r?\n){2,}$/, "$1");
461
- }
462
- function atomicWrite(target, content) {
463
- const tmp = `${target}.${randomUUID()}.tmp`;
464
- let temporaryCreated = false;
465
- try {
466
- const fd = openSync2(tmp, "wx");
467
- temporaryCreated = true;
468
- try {
469
- writeFileSync(fd, content);
470
- fsyncSync(fd);
471
- } finally {
472
- closeSync2(fd);
473
- }
474
- renameSync(tmp, target);
475
- } catch (error) {
476
- if (temporaryCreated) {
477
- try {
478
- rmSync2(tmp, { force: true });
479
- } catch {
480
- }
481
- }
482
- throw error;
483
- }
484
- }
485
- function resolveTarget(cwd, opts) {
486
- if (opts.scope && opts.scope !== "user" && opts.scope !== "project") {
487
- console.error(`Unknown --scope "${opts.scope}" (expected user or project)`);
488
- return null;
489
- }
490
- if (opts.target) return resolve2(cwd, opts.target);
491
- if (opts.scope === "user") {
492
- if (!opts.agent) {
493
- console.error("--scope user requires --agent (claude, codex, or hermes)");
494
- return null;
495
- }
496
- const userTarget = userTargetFor(opts.agent);
497
- if (userTarget) return userTarget;
498
- console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, or hermes)`);
499
- return null;
500
- }
501
- if (opts.agent) {
502
- const mapped = AGENT_TARGET[opts.agent];
503
- if (typeof mapped === "string") return resolve2(cwd, mapped);
504
- console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, or hermes)`);
505
- return null;
506
- }
507
- const matches = detectTargets(cwd);
508
- if (matches.length === 0) return resolve2(cwd, DEFAULT_TARGET);
509
- if (matches.length === 1) return resolve2(cwd, matches[0]);
510
- console.error("Multiple rules files detected. Use --target to disambiguate:");
511
- for (const m of matches) console.error(` ${m}`);
512
- return null;
513
- }
514
- function runInstall(cwd, opts) {
515
- if (opts.agent === "claude" && !opts.target) return installClaudePlugin(cwd, opts);
516
- const target = resolveTarget(cwd, opts);
517
- if (target === null) return 1;
518
- const existing = existsSync2(target) ? readFileSync2(target, "utf-8") : "";
519
- const eol = existing ? detectNewline(existing) : "\n";
520
- const block = composeBlock(loadSkill(), eol);
521
- const next = applyBlock(existing, block, eol);
522
- if (next === existing) {
523
- console.log("No changes \u2014 skill block already up to date.");
524
- return 0;
525
- }
526
- if (opts.dryRun) {
527
- process.stdout.write(createPatch(target, existing, next, "current", "proposed"));
528
- return 0;
529
- }
530
- atomicWrite(target, next);
531
- console.log(`Wrote ${Buffer.byteLength(next)} bytes to ${target}`);
532
- return 0;
533
- }
534
- function runUninstall(cwd, opts) {
535
- if (opts.agent === "claude" && !opts.target) return uninstallClaudePlugin(cwd, opts);
536
- const target = resolveTarget(cwd, opts);
537
- if (target === null) return 1;
538
- if (!existsSync2(target)) {
539
- console.log(`Skill block not present at ${target}`);
540
- return 0;
541
- }
542
- const existing = readFileSync2(target, "utf-8");
543
- const next = removeBlock(existing);
544
- if (next === null) {
545
- console.log(`Skill block not present at ${target}`);
546
- return 0;
547
- }
548
- atomicWrite(target, next);
549
- console.log(`Removed skill block from ${target}`);
550
- return 0;
551
- }
552
- function runStatus(cwd, opts) {
553
- if (opts.agent === "claude" && !opts.target) return statusClaudePlugin(cwd, opts);
554
- const target = resolveTarget(cwd, opts);
555
- if (target === null) return 1;
556
- const fileExists = existsSync2(target);
557
- let installed = false;
558
- if (fileExists) {
559
- const content = readFileSync2(target, "utf-8");
560
- installed = content.includes(SKILL_BEGIN) && content.includes(SKILL_END);
561
- }
562
- if (opts.json) {
563
- printJson({ installed, target });
564
- return installed ? 0 : 1;
565
- }
566
- if (!fileExists) {
567
- console.log(`No rules file at ${target}`);
568
- return 1;
569
- }
570
- if (installed) {
571
- console.log(`PRIM SKILL v1 installed at ${target}`);
572
- return 0;
573
- }
574
- console.log(`No PRIM SKILL block at ${target}`);
575
- return 1;
576
- }
577
- function registerSkillCommands(program) {
578
- const skill = program.command("skill").description("Manage the prim skill in your project rules file");
579
- skill.command("install").description("Install the prim skill block into your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, or hermes (selects the default rules file)").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--dry-run", "Print a unified diff without writing").action((opts) => {
580
- try {
581
- process.exit(runInstall(process.cwd(), opts));
582
- } catch (err) {
583
- console.error(err instanceof Error ? err.message : String(err));
584
- process.exit(2);
585
- }
586
- });
587
- skill.command("uninstall").description("Remove the prim skill block from your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, or hermes (selects the default rules file)").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").action((opts) => {
588
- process.exit(runUninstall(process.cwd(), opts));
589
- });
590
- skill.command("status").description("Report whether the prim skill block is installed").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, or hermes (selects the default rules file)").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--json", "Output as JSON").action((opts) => {
591
- process.exit(runStatus(process.cwd(), opts));
592
- });
593
- }
594
-
595
- // src/lib/repository-binding.ts
596
- async function bindRepository(root, options) {
597
- const repositoryFullName = githubRepositoryFullName(root);
598
- if (!repositoryFullName) {
599
- throw new Error("origin must be a GitHub HTTPS/SSH remote in owner/name form");
600
- }
601
- const response = await getClient().post(
602
- "/api/cli/repositories/bind",
603
- { repositoryFullName },
604
- options
605
- );
606
- if (typeof response.repoSyncId !== "string" || response.repoSyncId.length === 0) {
607
- throw new Error("server returned no repository binding");
608
- }
609
- setRepoSyncId(root, response.repoSyncId);
610
- return { repoSyncId: response.repoSyncId, repositoryFullName };
611
- }
612
-
613
- export {
614
- bindRepository,
615
- printJson,
616
- compareSemver,
617
- refreshClaudePlugins,
618
- hasUsableCodexGuidance,
619
- registerSkillCommands
620
- };
@@ -1,67 +0,0 @@
1
- // src/hooks/prim-hook-core.ts
2
- import { createHash, randomUUID } from "crypto";
3
- import { platform } from "os";
4
-
5
- // src/protocol/move.ts
6
- var LEGACY_ENVELOPE_VERSION = 1;
7
- var AGENT_ENVELOPE_VERSION = 3;
8
- var ENVELOPE_VERSION = LEGACY_ENVELOPE_VERSION;
9
-
10
- // src/hooks/prim-hook-core.ts
11
- function postToolInvocationId(parsed, agent) {
12
- if (parsed.hook_event_name !== "PostToolUse") return void 0;
13
- const raw = agent === "hermes" ? parsed.extra?.tool_call_id : parsed.tool_use_id;
14
- return typeof raw === "string" && raw.length > 0 ? raw : void 0;
15
- }
16
- function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, invocationId) {
17
- const sessionId = parsed.session_id ?? "";
18
- const eventType = parsed.hook_event_name ?? "unknown";
19
- const moveId = eventType === "PostToolUse" && sessionId && invocationId ? `posttool:v1:${createHash("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}` : randomUUID();
20
- return {
21
- moveId,
22
- capturedAt: Date.now(),
23
- sessionId,
24
- eventType,
25
- payload: parsed,
26
- env: {
27
- cwd: parsed.cwd ?? process.cwd(),
28
- cliVersion,
29
- osPlatform: platform(),
30
- ...workspaceId ? { workspaceId } : {}
31
- },
32
- envelopeVersion: AGENT_ENVELOPE_VERSION,
33
- producer: agent,
34
- ...invocationId ? { invocationId } : {}
35
- };
36
- }
37
- function toCommitMove(commit, cliVersion, cwd) {
38
- return {
39
- moveId: `commit:${commit.sha}`,
40
- capturedAt: Date.now(),
41
- sessionId: "",
42
- eventType: "git.commit",
43
- payload: {
44
- kind: "git.commit",
45
- sha: commit.sha,
46
- parentSha: commit.parentSha,
47
- branch: commit.branch,
48
- files: commit.files
49
- },
50
- env: {
51
- cwd,
52
- cliVersion,
53
- osPlatform: platform()
54
- },
55
- envelopeVersion: ENVELOPE_VERSION
56
- };
57
- }
58
- function shouldFlushAfter(eventType) {
59
- return eventType === "SessionEnd";
60
- }
61
-
62
- export {
63
- postToolInvocationId,
64
- toMove,
65
- toCommitMove,
66
- shouldFlushAfter
67
- };