@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
  3. package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
  4. package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
  5. package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
  6. package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
  7. package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
  8. package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
  9. package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
  10. package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
  11. package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
  12. package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
  13. package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
  14. package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
  15. package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
  16. package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
  17. package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
  19. package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
  20. package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
  21. package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
  22. package/dist/daemon/server.js +1769 -487
  23. package/dist/hook-runtime/daemon/server.js +1769 -487
  24. package/dist/hook-runtime/hooks/post-commit.js +611 -337
  25. package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
  27. package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
  29. package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
  30. package/dist/hook-runtime/hooks/session-end.js +538 -385
  31. package/dist/hook-runtime/hooks/session-start.js +1379 -233
  32. package/dist/hook-runtime/index.js +5438 -4052
  33. package/dist/hook-runtime/statusline-main.js +547 -273
  34. package/dist/hooks/post-commit.js +7 -7
  35. package/dist/hooks/post-rewrite.js +6 -6
  36. package/dist/hooks/post-tool-use.js +18 -18
  37. package/dist/hooks/pre-commit.js +4 -4
  38. package/dist/hooks/pre-tool-use-worker.js +9 -9
  39. package/dist/hooks/prim-hook.js +16 -16
  40. package/dist/hooks/session-end.js +4 -4
  41. package/dist/hooks/session-start.js +64 -22
  42. package/dist/index.js +396 -52
  43. package/dist/statusline-main.js +547 -273
  44. package/package.json +1 -1
@@ -54,35 +54,35 @@ var require_ucs2length = __commonJS({
54
54
 
55
55
  // src/hooks/post-commit.ts
56
56
  import { execFileSync as execFileSync7, spawn as spawn2 } from "child_process";
57
- import { lstatSync as lstatSync7, readFileSync as readFileSync18 } from "fs";
58
- import { basename as basename4, dirname as dirname12, isAbsolute as isAbsolute5, join as join19 } from "path";
59
- import { fileURLToPath as fileURLToPath4 } from "url";
57
+ import { lstatSync as lstatSync8, readFileSync as readFileSync19 } from "fs";
58
+ import { basename as basename4, dirname as dirname14, isAbsolute as isAbsolute6, join as join22 } from "path";
59
+ import { fileURLToPath as fileURLToPath5 } from "url";
60
60
 
61
61
  // src/binding.ts
62
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
63
- import { dirname as dirname5, join as join8 } from "path";
62
+ import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
63
+ import { dirname as dirname8, join as join12 } from "path";
64
64
 
65
65
  // src/lib/credentials.ts
66
- import { createHash as createHash4 } from "crypto";
67
- import { readFileSync as readFileSync6 } from "fs";
68
- import { join as join7 } from "path";
66
+ import { createHash as createHash7 } from "crypto";
67
+ import { readFileSync as readFileSync8 } from "fs";
68
+ import { join as join11 } from "path";
69
69
 
70
70
  // src/lib/machine-credentials.ts
71
- import { execFileSync } from "child_process";
72
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
71
+ import { execFileSync as execFileSync2 } from "child_process";
72
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
73
73
  import {
74
- chmodSync,
75
- existsSync as existsSync3,
74
+ chmodSync as chmodSync2,
75
+ existsSync as existsSync5,
76
76
  linkSync,
77
- lstatSync as lstatSync3,
78
- mkdirSync as mkdirSync3,
79
- readFileSync as readFileSync5,
80
- rmSync as rmSync5,
81
- writeFileSync as writeFileSync3
77
+ lstatSync as lstatSync5,
78
+ mkdirSync as mkdirSync4,
79
+ readFileSync as readFileSync7,
80
+ rmSync as rmSync7,
81
+ writeFileSync as writeFileSync4
82
82
  } from "fs";
83
- import { createRequire } from "module";
84
- import { dirname as dirname4, join as join6 } from "path";
85
- import { fileURLToPath as fileURLToPath3 } from "url";
83
+ import { createRequire as createRequire2 } from "module";
84
+ import { dirname as dirname7, join as join10 } from "path";
85
+ import { fileURLToPath as fileURLToPath4 } from "url";
86
86
 
87
87
  // src/lib/atomic-file.ts
88
88
  import { randomUUID } from "crypto";
@@ -169,13 +169,27 @@ import { existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, s
169
169
  import { dirname as dirname2, join } from "path";
170
170
  var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
171
171
 
172
- // src/lib/machine-broker.ts
173
- import { spawn } from "child_process";
174
- import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
175
- import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
176
- import { createServer } from "http";
177
- import { basename, join as join4 } from "path";
178
- import { fileURLToPath as fileURLToPath2 } from "url";
172
+ // src/lib/hook-runtime.ts
173
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
174
+ import {
175
+ constants as constants2,
176
+ accessSync,
177
+ chmodSync,
178
+ copyFileSync,
179
+ existsSync as existsSync4,
180
+ lstatSync,
181
+ mkdirSync as mkdirSync3,
182
+ mkdtempSync,
183
+ readFileSync as readFileSync3,
184
+ readdirSync,
185
+ realpathSync,
186
+ renameSync as renameSync2,
187
+ rmSync as rmSync3,
188
+ statSync as statSync2,
189
+ utimesSync,
190
+ writeFileSync as writeFileSync3
191
+ } from "fs";
192
+ import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
179
193
 
180
194
  // src/lib/bin-path.ts
181
195
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
@@ -183,6 +197,7 @@ import { dirname as dirname3, isAbsolute, join as join2 } from "path";
183
197
  import { fileURLToPath } from "url";
184
198
  var PKG_NAME = "@primitive.ai/prim";
185
199
  var ROOT_WALK_LIMIT = 6;
200
+ var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
186
201
  var resolvedRoot;
187
202
  function locateRoot() {
188
203
  if (resolvedRoot !== void 0) {
@@ -221,6 +236,140 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
221
236
  "fi; fi; "
222
237
  ].join("");
223
238
 
239
+ // src/lib/git-hook-contract.ts
240
+ var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
241
+ # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
242
+ # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
243
+ # where prim is active (git config prim.active true) and never fails the hook.
244
+ case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
245
+ prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
246
+ [ -x "$prim_launcher" ] || exit 0
247
+ [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
248
+ prim_hook=\${1-}
249
+ if [ "$#" -gt 0 ]; then shift; fi
250
+ case "$prim_hook" in
251
+ pre-commit)
252
+ "$prim_launcher" prim-pre-commit "$@" || :
253
+ ;;
254
+ post-commit)
255
+ prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
256
+ case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
257
+ case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
258
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
259
+ prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
260
+ (
261
+ trap '' HUP
262
+ trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
263
+ PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
264
+ ) </dev/null >/dev/null 2>&1 &
265
+ ;;
266
+ post-rewrite)
267
+ case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
268
+ prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
269
+ if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
270
+ rm -f "$prim_pairs"
271
+ exit 0
272
+ fi
273
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
274
+ (
275
+ trap '' HUP
276
+ trap 'rm -f "$prim_pairs"' 0
277
+ PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
278
+ ) </dev/null >/dev/null 2>&1 &
279
+ ;;
280
+ esac
281
+ exit 0
282
+ `;
283
+
284
+ // src/lib/native-keyring.ts
285
+ import { existsSync as existsSync3 } from "fs";
286
+ import { createRequire } from "module";
287
+ import { dirname as dirname4, join as join3 } from "path";
288
+ import { fileURLToPath as fileURLToPath2 } from "url";
289
+ var require2 = createRequire(import.meta.url);
290
+
291
+ // src/lib/paths.ts
292
+ import { homedir } from "os";
293
+ import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
294
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
295
+ function absolutePath(value, variable) {
296
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
297
+ throw new Error(`${variable} contains unsafe characters`);
298
+ }
299
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
300
+ const normalized = normalize(value);
301
+ return normalized === value ? value : void 0;
302
+ }
303
+ function resolvePrimConfigDirectory(options = {}) {
304
+ const env = options.env ?? process.env;
305
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
306
+ if (explicit) return { path: explicit, source: "explicit" };
307
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
308
+ if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
309
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
310
+ if (!home) {
311
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
312
+ }
313
+ return { path: join4(home, ".config", "prim"), source: "default" };
314
+ }
315
+ function primConfigDirectory(options = {}) {
316
+ return resolvePrimConfigDirectory(options).path;
317
+ }
318
+
319
+ // src/lib/hook-runtime.ts
320
+ var RELEASE_PREFIX = "release-";
321
+ var MAX_MANIFEST_BYTES = 64 * 1024;
322
+ var RELEASE_GRACE_MS = 10 * 60 * 1e3;
323
+ var HOOK_RUNTIME_ENTRIES = {
324
+ // SessionStart self-healing resolves this exact CLI entry to run
325
+ // `daemon ensure`; it must travel with the immutable hook release.
326
+ prim: "dist/index.js",
327
+ "prim-hook": "dist/hooks/prim-hook.js",
328
+ "prim-pre-commit": "dist/hooks/pre-commit.js",
329
+ "prim-post-commit": "dist/hooks/post-commit.js",
330
+ "prim-post-rewrite": "dist/hooks/post-rewrite.js",
331
+ "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
332
+ "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
333
+ "prim-post-tool-use": "dist/hooks/post-tool-use.js",
334
+ "prim-session-start": "dist/hooks/session-start.js",
335
+ "prim-session-end": "dist/hooks/session-end.js",
336
+ "prim-daemon-server": "dist/daemon/server.js",
337
+ "prim-statusline": "dist/statusline-main.js"
338
+ };
339
+ var SOURCE_ENTRIES = Object.fromEntries(
340
+ Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
341
+ bin,
342
+ target.replace(/^dist\//u, "")
343
+ ])
344
+ );
345
+ var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
346
+ set -eu
347
+ case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
348
+ IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
349
+ case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
350
+ prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
351
+ case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
352
+ [ "\${#prim_release_id}" -eq 64 ] || exit 69
353
+ prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
354
+ case "\${1-}" in
355
+ ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
356
+ *) exit 64 ;;
357
+ esac
358
+ shift
359
+ IFS= read -r prim_node < "$prim_release/node" || exit 69
360
+ case "$prim_node" in /*) ;; *) exit 69 ;; esac
361
+ [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
362
+ exec "$prim_node" "$prim_entry" "$@"
363
+ `;
364
+
365
+ // src/lib/machine-broker.ts
366
+ import { spawn } from "child_process";
367
+ import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
368
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
369
+ import { createServer } from "http";
370
+ import { basename, join as join6 } from "path";
371
+ import { fileURLToPath as fileURLToPath3 } from "url";
372
+
224
373
  // src/lib/loopback-fetch.ts
225
374
  import { request } from "http";
226
375
  import { Readable } from "stream";
@@ -229,6 +378,8 @@ import { Readable } from "stream";
229
378
  function isClaudeCloudSession(env = process.env) {
230
379
  return env.CLAUDE_CODE_REMOTE === "true";
231
380
  }
381
+ var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
382
+ var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
232
383
 
233
384
  // src/lib/workos-connect.ts
234
385
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -375,34 +526,6 @@ function parseMachineIdentity(value, clientId) {
375
526
  };
376
527
  }
377
528
 
378
- // src/lib/paths.ts
379
- import { homedir } from "os";
380
- import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
381
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
382
- function absolutePath(value, variable) {
383
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
384
- throw new Error(`${variable} contains unsafe characters`);
385
- }
386
- if (!value || value.trim() !== value || !isAbsolute2(value)) return;
387
- const normalized = normalize(value);
388
- return normalized === value ? value : void 0;
389
- }
390
- function resolvePrimConfigDirectory(options = {}) {
391
- const env = options.env ?? process.env;
392
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
393
- if (explicit) return { path: explicit, source: "explicit" };
394
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
395
- if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
396
- const home = absolutePath(options.homeDir ?? homedir(), "HOME");
397
- if (!home) {
398
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
399
- }
400
- return { path: join3(home, ".config", "prim"), source: "default" };
401
- }
402
- function primConfigDirectory(options = {}) {
403
- return resolvePrimConfigDirectory(options).path;
404
- }
405
-
406
529
  // src/lib/machine-broker.ts
407
530
  var MAX_RESPONSE_BYTES = 96 * 1024;
408
531
  var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
@@ -411,29 +534,325 @@ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
411
534
  var IDLE_MS = 5 * 6e4;
412
535
 
413
536
  // src/lib/machine-retry.ts
414
- import { createHash as createHash2 } from "crypto";
415
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
416
- import { join as join5 } from "path";
537
+ import { createHash as createHash3 } from "crypto";
538
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
539
+ import { join as join7 } from "path";
417
540
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
418
541
 
419
- // src/lib/machine-credentials.ts
420
- var require2 = createRequire(import.meta.url);
542
+ // src/lib/session-identity.ts
543
+ import { execFile } from "child_process";
544
+ import { createHash as createHash5 } from "crypto";
545
+ import { rmSync as rmSync6 } from "fs";
546
+ import { join as join9 } from "path";
547
+ import { promisify } from "util";
548
+
549
+ // src/lib/git.ts
550
+ import { execFileSync } from "child_process";
551
+ import { createHash as createHash4 } from "crypto";
552
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
553
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
554
+ var GIT_TIMEOUT_MS = 1e3;
555
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
556
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
557
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
558
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
559
+ function gitChildEnvironment(env = process.env) {
560
+ return Object.fromEntries(
561
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
562
+ );
563
+ }
564
+ function gitToplevel(cwd) {
565
+ try {
566
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
567
+ cwd,
568
+ encoding: "utf-8",
569
+ stdio: ["ignore", "pipe", "ignore"],
570
+ timeout: GIT_TIMEOUT_MS,
571
+ env: gitChildEnvironment()
572
+ }).trim();
573
+ } catch {
574
+ return null;
575
+ }
576
+ }
577
+ function gitValue(cwd, args) {
578
+ try {
579
+ const value = execFileSync("git", args, {
580
+ cwd,
581
+ encoding: "utf-8",
582
+ stdio: ["ignore", "pipe", "ignore"],
583
+ timeout: GIT_TIMEOUT_MS,
584
+ env: gitChildEnvironment()
585
+ }).trim();
586
+ return value || void 0;
587
+ } catch {
588
+ return void 0;
589
+ }
590
+ }
591
+ function parseGithubRepositoryName(path) {
592
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
593
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
594
+ return null;
595
+ }
596
+ return `${parts[0]}/${parts[1]}`;
597
+ }
598
+ function githubRepositoryFromRemote(remote) {
599
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
600
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
601
+ remote
602
+ );
603
+ const path = match?.[1] ?? match?.[2];
604
+ return path ? parseGithubRepositoryName(path) : null;
605
+ }
606
+ function checkoutSettingsText(repoRoot) {
607
+ const path = join8(repoRoot, ".claude", "settings.json");
608
+ try {
609
+ if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
610
+ const stat = lstatSync4(path);
611
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
612
+ return readFileSync6(path, "utf8");
613
+ } catch {
614
+ return null;
615
+ }
616
+ }
617
+ function checkoutDeclaration(repoRoot, name) {
618
+ const text = checkoutSettingsText(repoRoot);
619
+ if (text === null) return null;
620
+ let parsed;
621
+ try {
622
+ parsed = JSON.parse(text);
623
+ } catch {
624
+ return null;
625
+ }
626
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
627
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
628
+ return typeof value === "string" ? value : null;
629
+ }
630
+ function declaredGithubRepository(repoRoot) {
631
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
632
+ return value === null ? null : parseGithubRepositoryName(value.trim());
633
+ }
634
+ function githubRepositoryFullName(cwd) {
635
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
636
+ if (remote) {
637
+ const fromOrigin = githubRepositoryFromRemote(remote);
638
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
639
+ }
640
+ const root = gitToplevel(cwd);
641
+ return root ? declaredGithubRepository(root) : null;
642
+ }
643
+ function normalizeOriginRemote(remote) {
644
+ const value = remote.trim();
645
+ if (!value) return void 0;
646
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
647
+ if (scp?.host && scp.path) {
648
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
649
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
650
+ }
651
+ try {
652
+ const url = new URL(value);
653
+ url.username = "";
654
+ url.password = "";
655
+ url.search = "";
656
+ url.hash = "";
657
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
658
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
659
+ return void 0;
660
+ } catch {
661
+ return void 0;
662
+ }
663
+ }
664
+ function opaqueRepoKey(source, value) {
665
+ return `repo_v1_${createHash4("sha256").update(`${source}\0${value}`).digest("hex")}`;
666
+ }
667
+ function resolveRepositoryContext(cwd = process.cwd()) {
668
+ const top = gitToplevel(cwd);
669
+ if (!top) return null;
670
+ let repoRoot;
671
+ try {
672
+ repoRoot = realpathSync2.native(top);
673
+ } catch {
674
+ repoRoot = resolve2(top);
675
+ }
676
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
677
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
678
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
679
+ if (normalizedOrigin) {
680
+ return {
681
+ repoRoot,
682
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
683
+ identitySource: "origin",
684
+ repoFullName
685
+ };
686
+ }
687
+ if (repoFullName) {
688
+ return {
689
+ repoRoot,
690
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
691
+ identitySource: "declared",
692
+ repoFullName
693
+ };
694
+ }
695
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
696
+ if (roots && roots.length > 0) {
697
+ return {
698
+ repoRoot,
699
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
700
+ identitySource: "root_commit",
701
+ repoFullName
702
+ };
703
+ }
704
+ return { repoRoot, repoFullName };
705
+ }
706
+
707
+ // src/lib/session-identity.ts
708
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
709
+ var SESSION_IDENTITY_VALUE = "session";
710
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
711
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
712
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
421
713
  var DEFAULT_API_URL = "https://api.getprimitive.ai";
714
+ var RENEW_BEFORE_MS = 6e4;
715
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
716
+ var RESPONSE_MAX_BYTES = 64 * 1024;
717
+ function sessionIdentityRequested(env = process.env) {
718
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
719
+ }
720
+ function sessionIdentityMode(deps = {}) {
721
+ const env = deps.env ?? process.env;
722
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
723
+ }
724
+ function failure(code, cause, remedy) {
725
+ return { status: "failed", code, cause, remedy };
726
+ }
727
+ var NEW_SESSION_REMEDY = "start a new cloud session";
728
+ var SESSION_REVOKED = failure(
729
+ "session_revoked",
730
+ "Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
731
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
732
+ );
733
+ var CHALLENGE_WINDOW_PASSED = failure(
734
+ "challenge_expired",
735
+ "this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
736
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
737
+ );
738
+ var CHALLENGE_GONE = failure(
739
+ "challenge_not_found",
740
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
741
+ NEW_SESSION_REMEDY
742
+ );
743
+ function hash(value) {
744
+ return createHash5("sha256").update(value).digest("hex");
745
+ }
746
+ function sessionContext(deps) {
747
+ const env = deps.env ?? process.env;
748
+ const environment = environmentCredentials(deps);
749
+ if (!environment)
750
+ return failure(
751
+ "environment_credential_missing",
752
+ "the cloud environment has no environment credential",
753
+ 'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
754
+ );
755
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
756
+ if (!sessionId || !SESSION_ID.test(sessionId))
757
+ return failure(
758
+ "session_id_missing",
759
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
760
+ NEW_SESSION_REMEDY
761
+ );
762
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
763
+ const directory = deps.directory ?? primConfigDirectory({ env });
764
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
765
+ return {
766
+ directory,
767
+ apiUrl,
768
+ clientId: environment.clientId,
769
+ generation: environment.generation,
770
+ sessionId,
771
+ tokenPath: join9(directory, `session_identity_${key}.json`),
772
+ statePath: join9(directory, `session_identity_${key}.state.json`),
773
+ lockPath: join9(directory, "session-identity.lock")
774
+ };
775
+ }
776
+ function readRecord(path) {
777
+ try {
778
+ const value = readMachineMetadata(path);
779
+ return value === void 0 ? void 0 : machineRecord(value);
780
+ } catch {
781
+ return void 0;
782
+ }
783
+ }
784
+ function finiteNumber(value) {
785
+ return typeof value === "number" && Number.isFinite(value);
786
+ }
787
+ function readToken(context) {
788
+ const data = readRecord(context.tokenPath);
789
+ if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
790
+ return void 0;
791
+ const identity = data.identity;
792
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
793
+ return void 0;
794
+ return data;
795
+ }
796
+ function tokenValid(record, now = Date.now()) {
797
+ return now < record.expiresAt - RENEW_BEFORE_MS;
798
+ }
799
+ function toCredential(record) {
800
+ return {
801
+ issuer: record.issuer,
802
+ audience: record.audience,
803
+ ...record.identity,
804
+ accessToken: record.accessToken,
805
+ expiresAt: record.expiresAt,
806
+ apiUrl: record.apiUrl,
807
+ generation: record.generation,
808
+ storage: "environment",
809
+ session: {
810
+ userId: record.userId,
811
+ displayName: record.displayName,
812
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
813
+ refreshAfter: record.refreshAfter
814
+ }
815
+ };
816
+ }
817
+ function cachedSessionCredential(deps = {}) {
818
+ if (!sessionIdentityMode(deps)) return void 0;
819
+ let context;
820
+ try {
821
+ context = sessionContext(deps);
822
+ } catch {
823
+ return void 0;
824
+ }
825
+ if ("status" in context) return void 0;
826
+ const record = readToken(context);
827
+ return record && tokenValid(record) ? toCredential(record) : void 0;
828
+ }
829
+ var SERVER_CONTRACT_FAILURE = failure(
830
+ "server_contract",
831
+ "Primitive's answer did not identify the linked member",
832
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
833
+ );
834
+
835
+ // src/lib/machine-credentials.ts
836
+ function sessionScoped(deps) {
837
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
838
+ }
839
+ var require3 = createRequire2(import.meta.url);
840
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
422
841
  var PROFILE_FILE = "machine_profile.json";
423
842
  var cached;
424
843
  function configurationDirectory(deps) {
425
844
  return deps.directory ?? primConfigDirectory({ env: deps.env });
426
845
  }
427
846
  function apiUrlFor(deps) {
428
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
847
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
429
848
  }
430
- function hash(value) {
431
- return createHash3("sha256").update(value).digest("hex");
849
+ function hash2(value) {
850
+ return createHash6("sha256").update(value).digest("hex");
432
851
  }
433
852
  function environmentContextPath(deps, clientId) {
434
- return join6(
853
+ return join10(
435
854
  configurationDirectory(deps),
436
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
855
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
437
856
  );
438
857
  }
439
858
  function readEnvironmentContext(environment, deps) {
@@ -459,12 +878,12 @@ function readEnvironmentContext(environment, deps) {
459
878
  }
460
879
  function protectPath(path, directory) {
461
880
  if (process.platform !== "win32") {
462
- chmodSync(path, directory ? 448 : 384);
881
+ chmodSync2(path, directory ? 448 : 384);
463
882
  return;
464
883
  }
465
884
  const encodedPath = Buffer.from(path).toString("base64");
466
885
  const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
467
- execFileSync(
886
+ execFileSync2(
468
887
  "powershell.exe",
469
888
  [
470
889
  "-NoProfile",
@@ -476,25 +895,28 @@ function protectPath(path, directory) {
476
895
  );
477
896
  }
478
897
  function ensureDirectory(directory) {
479
- mkdirSync3(directory, { recursive: true, mode: 448 });
480
- if (lstatSync3(directory).isSymbolicLink())
898
+ mkdirSync4(directory, { recursive: true, mode: 448 });
899
+ if (lstatSync5(directory).isSymbolicLink())
481
900
  throw new MachineAuthError(
482
901
  "unsafe_storage",
483
902
  "Credential directory must not be a symbolic link."
484
903
  );
485
904
  protectPath(directory, true);
486
905
  }
906
+ function readMachineMetadata(path) {
907
+ return readPrivate(path);
908
+ }
487
909
  function readPrivate(path) {
488
910
  let raw;
489
911
  try {
490
- const stat = lstatSync3(path);
912
+ const stat = lstatSync5(path);
491
913
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
492
914
  throw new MachineAuthError(
493
915
  "unsafe_storage",
494
916
  "Machine credential files must be owner-only regular files."
495
917
  );
496
918
  }
497
- raw = readFileSync5(path, "utf8");
919
+ raw = readFileSync7(path, "utf8");
498
920
  } catch (error) {
499
921
  if (error.code === "ENOENT") return void 0;
500
922
  throw error;
@@ -539,7 +961,7 @@ function parseProfile(value) {
539
961
  };
540
962
  }
541
963
  function readMachineProfile(deps = {}) {
542
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
964
+ const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
543
965
  return value === void 0 ? void 0 : parseProfile(value);
544
966
  }
545
967
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -548,20 +970,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
548
970
  var brokerKeys = /* @__PURE__ */ new Map();
549
971
  function networkSecretBrokerKey(deps, clientId) {
550
972
  const directory = configurationDirectory(deps);
551
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
973
+ const path = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
552
974
  const known = brokerKeys.get(path);
553
975
  if (known) return known;
554
976
  ensureDirectory(directory);
555
977
  const read = () => {
556
978
  try {
557
- const stat = lstatSync3(path);
979
+ const stat = lstatSync5(path);
558
980
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
559
981
  throw new MachineAuthError(
560
982
  "unsafe_storage",
561
983
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
562
984
  true
563
985
  );
564
- const value = readFileSync5(path, "utf8").trim();
986
+ const value = readFileSync7(path, "utf8").trim();
565
987
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
566
988
  } catch (error) {
567
989
  if (error.code === "ENOENT") return void 0;
@@ -580,16 +1002,16 @@ function networkSecretBrokerKey(deps, clientId) {
580
1002
  `The machine broker key at ${path} is damaged. Delete it and retry.`,
581
1003
  true
582
1004
  );
583
- const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
1005
+ const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
584
1006
  try {
585
- writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
1007
+ writeFileSync4(staged, `${randomBytes4(32).toString("hex")}
586
1008
  `, { mode: 384, flag: "wx" });
587
1009
  protectPath(staged, false);
588
1010
  linkSync(staged, path);
589
1011
  } catch (error) {
590
1012
  if (error.code !== "EEXIST") throw error;
591
1013
  } finally {
592
- rmSync5(staged, { force: true });
1014
+ rmSync7(staged, { force: true });
593
1015
  }
594
1016
  }
595
1017
  const key = read()?.key;
@@ -622,7 +1044,7 @@ function environmentCredentials(deps) {
622
1044
  "conflicting_credentials",
623
1045
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
624
1046
  );
625
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
1047
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
626
1048
  const credentials = {
627
1049
  clientId,
628
1050
  generation,
@@ -643,12 +1065,12 @@ function environmentCredentials(deps) {
643
1065
  return {
644
1066
  clientId,
645
1067
  clientSecret,
646
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1068
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
647
1069
  };
648
1070
  }
649
1071
  function hasMachineConfiguration(deps = {}) {
650
1072
  const env = deps.env ?? process.env;
651
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
1073
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join10(configurationDirectory(deps), PROFILE_FILE));
652
1074
  if (configured && env.PRIM_TOKEN?.trim()) {
653
1075
  throw new MachineAuthError(
654
1076
  "conflicting_credentials",
@@ -660,6 +1082,7 @@ function hasMachineConfiguration(deps = {}) {
660
1082
  }
661
1083
  function machineContext(deps = {}) {
662
1084
  if (!hasMachineConfiguration(deps)) return void 0;
1085
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
663
1086
  const environment = environmentCredentials(deps);
664
1087
  if (environment) {
665
1088
  if (environmentTerminal === environment.generation) return void 0;
@@ -674,6 +1097,7 @@ function machineContext(deps = {}) {
674
1097
  return profile;
675
1098
  }
676
1099
  function cachedMachineCredential(deps = {}) {
1100
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
677
1101
  const context = machineContext(deps);
678
1102
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
679
1103
  }
@@ -695,31 +1119,31 @@ function machineCaptureActor(deps = {}) {
695
1119
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
696
1120
  }
697
1121
  function machineJournalBucket(identity) {
698
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1122
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
699
1123
  }
700
1124
  function identityPending(actor) {
701
1125
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
702
1126
  }
703
1127
  function machinePendingBucket(identity) {
704
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
1128
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
705
1129
  }
706
1130
 
707
1131
  // src/lib/credentials.ts
708
1132
  var CONFIG_DIRECTORY = primConfigDirectory();
709
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
710
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
711
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
712
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
713
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
714
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
715
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
716
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
1133
+ var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
1134
+ var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
1135
+ var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
1136
+ var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
1137
+ var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
1138
+ var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
1139
+ var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
1140
+ var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
717
1141
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
718
1142
  var CREDENTIAL_MIGRATION_VERSION = 1;
719
1143
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
720
1144
  function readTrimmed(path) {
721
1145
  try {
722
- const value = readFileSync6(path, "utf8").trim();
1146
+ const value = readFileSync8(path, "utf8").trim();
723
1147
  return value || void 0;
724
1148
  } catch {
725
1149
  return void 0;
@@ -756,7 +1180,7 @@ function resolveAuthCredential(options = {}) {
756
1180
  return { token: stored, source: "token_file" };
757
1181
  }
758
1182
  function credentialFingerprint(value) {
759
- return createHash4("sha256").update(value).digest("hex");
1183
+ return createHash7("sha256").update(value).digest("hex");
760
1184
  }
761
1185
  function parseLegacyBrokerCredentialMetadata(value) {
762
1186
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -776,7 +1200,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
776
1200
  function readBoundedCredentialJson(path) {
777
1201
  let raw;
778
1202
  try {
779
- raw = readFileSync6(path, "utf8");
1203
+ raw = readFileSync8(path, "utf8");
780
1204
  } catch (error) {
781
1205
  return error.code === "ENOENT" ? void 0 : null;
782
1206
  }
@@ -849,14 +1273,14 @@ function jwtOrganizationId(token) {
849
1273
 
850
1274
  // src/binding.ts
851
1275
  var PRIM_CONFIG_DIR = primConfigDirectory();
852
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
1276
+ var SESSIONS_DIR = join12(PRIM_CONFIG_DIR, "sessions");
853
1277
  var WORKSPACE_FILE = ".prim/workspace.json";
854
1278
  function readJsonSafe(path) {
855
- if (!existsSync4(path)) {
1279
+ if (!existsSync6(path)) {
856
1280
  return;
857
1281
  }
858
1282
  try {
859
- return JSON.parse(readFileSync7(path, "utf-8"));
1283
+ return JSON.parse(readFileSync9(path, "utf-8"));
860
1284
  } catch {
861
1285
  return;
862
1286
  }
@@ -865,17 +1289,17 @@ function fromSessionMarker(sessionId) {
865
1289
  if (!sessionId) {
866
1290
  return;
867
1291
  }
868
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
1292
+ const marker = readJsonSafe(join12(SESSIONS_DIR, `${sessionId}.json`));
869
1293
  return marker?.orgId;
870
1294
  }
871
1295
  function fromWorkspaceFile(startDir) {
872
1296
  let dir = startDir;
873
1297
  while (true) {
874
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
1298
+ const config = readJsonSafe(join12(dir, WORKSPACE_FILE));
875
1299
  if (config?.orgId) {
876
1300
  return config.orgId;
877
1301
  }
878
- const parent = dirname5(dir);
1302
+ const parent = dirname8(dir);
879
1303
  if (parent === dir) {
880
1304
  return;
881
1305
  }
@@ -911,26 +1335,26 @@ function resolveOrg(args) {
911
1335
  import {
912
1336
  appendFileSync,
913
1337
  closeSync as closeSync2,
914
- existsSync as existsSync7,
1338
+ existsSync as existsSync9,
915
1339
  fstatSync,
916
- mkdirSync as mkdirSync5,
1340
+ mkdirSync as mkdirSync6,
917
1341
  openSync as openSync2,
918
1342
  opendirSync,
919
- readFileSync as readFileSync11,
1343
+ readFileSync as readFileSync13,
920
1344
  readSync,
921
- readdirSync as readdirSync3
1345
+ readdirSync as readdirSync4
922
1346
  } from "fs";
923
- import { dirname as dirname8, join as join12 } from "path";
1347
+ import { dirname as dirname11, join as join16 } from "path";
924
1348
 
925
1349
  // src/client.ts
926
- import { createHash as createHash5 } from "crypto";
927
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
928
- import { dirname as dirname6 } from "path";
1350
+ import { createHash as createHash8 } from "crypto";
1351
+ import { chmodSync as chmodSync4, existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync11, rmSync as rmSync8 } from "fs";
1352
+ import { dirname as dirname9 } from "path";
929
1353
 
930
1354
  // src/daemon/client-instance-id.ts
931
- import { randomBytes as randomBytes4 } from "crypto";
932
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
933
- import { join as join9 } from "path";
1355
+ import { randomBytes as randomBytes5 } from "crypto";
1356
+ import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync10 } from "fs";
1357
+ import { join as join13 } from "path";
934
1358
  var INSTANCE_BODY_CHARS = 43;
935
1359
  var INSTANCE_PREFIX = "pci_";
936
1360
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -939,28 +1363,28 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
939
1363
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
940
1364
 
941
1365
  // src/client.ts
942
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1366
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
943
1367
  function getSiteUrl() {
944
1368
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
945
1369
  }
946
1370
  function getSiteUrlForEnvironment(primApiUrl) {
947
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1371
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
948
1372
  }
949
1373
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
950
1374
 
951
1375
  // src/drain-progress.ts
952
1376
  import {
953
- chmodSync as chmodSync4,
954
- existsSync as existsSync6,
955
- readFileSync as readFileSync10,
956
- readdirSync as readdirSync2,
957
- rmSync as rmSync7,
1377
+ chmodSync as chmodSync5,
1378
+ existsSync as existsSync8,
1379
+ readFileSync as readFileSync12,
1380
+ readdirSync as readdirSync3,
1381
+ rmSync as rmSync9,
958
1382
  rmdirSync
959
1383
  } from "fs";
960
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
1384
+ import { basename as basename3, dirname as dirname10, join as join15 } from "path";
961
1385
 
962
1386
  // src/journal.ts
963
- var JOURNAL_DIR = join12(primConfigDirectory(), "moves");
1387
+ var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
964
1388
  var UNBOUND_BUCKET = "_unbound";
965
1389
  var JOURNAL_BASENAME = "journal.ndjson";
966
1390
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -972,26 +1396,26 @@ function envSlug(apiUrl) {
972
1396
  return slug;
973
1397
  }
974
1398
  function currentEnvDir() {
975
- return join12(JOURNAL_DIR, envSlug(getSiteUrl()));
1399
+ return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
976
1400
  }
977
1401
  var DIR_MODE = 448;
978
1402
  var FILE_MODE = 384;
979
1403
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
980
1404
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
981
1405
  function appendMoveToPath(path, move) {
982
- const dir = dirname8(path);
983
- if (!existsSync7(dir)) {
984
- mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
1406
+ const dir = dirname11(path);
1407
+ if (!existsSync9(dir)) {
1408
+ mkdirSync6(dir, { recursive: true, mode: DIR_MODE });
985
1409
  }
986
1410
  appendFileSync(path, `${JSON.stringify(move)}
987
1411
  `, { mode: FILE_MODE });
988
1412
  }
989
1413
  function bucketDir(orgId) {
990
1414
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
991
- return join12(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
1415
+ return join16(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
992
1416
  }
993
1417
  function journalPath(orgId) {
994
- return join12(bucketDir(orgId), JOURNAL_BASENAME);
1418
+ return join16(bucketDir(orgId), JOURNAL_BASENAME);
995
1419
  }
996
1420
  function appendMove(move, orgId) {
997
1421
  const actor = machineCaptureActor();
@@ -1004,38 +1428,38 @@ var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
1004
1428
 
1005
1429
  // src/lib/activation.ts
1006
1430
  import { execFileSync as execFileSync4 } from "child_process";
1007
- import { existsSync as existsSync9, readFileSync as readFileSync14 } from "fs";
1431
+ import { existsSync as existsSync11, readFileSync as readFileSync15 } from "fs";
1008
1432
  import { homedir as homedir2 } from "os";
1009
- import { join as join15 } from "path";
1433
+ import { join as join18 } from "path";
1010
1434
 
1011
1435
  // src/lib/cloud-prepared.ts
1012
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, rmSync as rmSync8, writeFileSync as writeFileSync4 } from "fs";
1013
- import { join as join13 } from "path";
1436
+ import { existsSync as existsSync10, mkdirSync as mkdirSync7, readFileSync as readFileSync14, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
1437
+ import { join as join17 } from "path";
1014
1438
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
1015
1439
  function cloudPreparedPath(env = process.env) {
1016
- return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1440
+ return join17(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1017
1441
  }
1018
1442
  function isPreparedCloudSession(env = process.env) {
1019
1443
  if (!isClaudeCloudSession(env)) return false;
1020
1444
  try {
1021
- return existsSync8(cloudPreparedPath(env));
1445
+ return existsSync10(cloudPreparedPath(env));
1022
1446
  } catch {
1023
1447
  return false;
1024
1448
  }
1025
1449
  }
1026
1450
 
1027
1451
  // src/lib/demo-pause.ts
1028
- import { execFileSync as execFileSync2 } from "child_process";
1452
+ import { execFileSync as execFileSync3 } from "child_process";
1029
1453
  var DEMO_PAUSE_MS = 30 * 6e4;
1030
1454
  var PAUSE_KEY = "prim.demoPause";
1031
- var GIT_TIMEOUT_MS = 1e3;
1455
+ var GIT_TIMEOUT_MS2 = 1e3;
1032
1456
  function git(cwd, args) {
1033
1457
  try {
1034
- return execFileSync2("git", args, {
1458
+ return execFileSync3("git", args, {
1035
1459
  cwd,
1036
1460
  encoding: "utf-8",
1037
1461
  stdio: ["ignore", "pipe", "ignore"],
1038
- timeout: GIT_TIMEOUT_MS
1462
+ timeout: GIT_TIMEOUT_MS2
1039
1463
  });
1040
1464
  } catch {
1041
1465
  return void 0;
@@ -1043,10 +1467,10 @@ function git(cwd, args) {
1043
1467
  }
1044
1468
  function setLocal(cwd, key, value) {
1045
1469
  try {
1046
- execFileSync2(
1470
+ execFileSync3(
1047
1471
  "git",
1048
1472
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
1049
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1473
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
1050
1474
  );
1051
1475
  } catch (error) {
1052
1476
  if (value !== null || error.status !== 5) throw error;
@@ -1085,156 +1509,6 @@ function healDemoPause(cwd, pause, options = {}) {
1085
1509
  }
1086
1510
  }
1087
1511
 
1088
- // src/lib/git.ts
1089
- import { execFileSync as execFileSync3 } from "child_process";
1090
- import { createHash as createHash6 } from "crypto";
1091
- import { lstatSync as lstatSync5, readFileSync as readFileSync13, realpathSync } from "fs";
1092
- import { basename as basename3, dirname as dirname9, isAbsolute as isAbsolute3, join as join14, relative, resolve as resolve2, sep } from "path";
1093
- var GIT_TIMEOUT_MS2 = 1e3;
1094
- var MAX_SETTINGS_BYTES = 1024 * 1024;
1095
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1096
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1097
- function gitToplevel(cwd) {
1098
- try {
1099
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
1100
- cwd,
1101
- encoding: "utf-8",
1102
- stdio: ["ignore", "pipe", "ignore"],
1103
- timeout: GIT_TIMEOUT_MS2
1104
- }).trim();
1105
- } catch {
1106
- return null;
1107
- }
1108
- }
1109
- function gitValue(cwd, args) {
1110
- try {
1111
- const value = execFileSync3("git", args, {
1112
- cwd,
1113
- encoding: "utf-8",
1114
- stdio: ["ignore", "pipe", "ignore"],
1115
- timeout: GIT_TIMEOUT_MS2
1116
- }).trim();
1117
- return value || void 0;
1118
- } catch {
1119
- return void 0;
1120
- }
1121
- }
1122
- function parseGithubRepositoryName(path) {
1123
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1124
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1125
- return null;
1126
- }
1127
- return `${parts[0]}/${parts[1]}`;
1128
- }
1129
- function githubRepositoryFromRemote(remote) {
1130
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1131
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1132
- remote
1133
- );
1134
- const path = match?.[1] ?? match?.[2];
1135
- return path ? parseGithubRepositoryName(path) : null;
1136
- }
1137
- function checkoutSettingsText(repoRoot) {
1138
- const path = join14(repoRoot, ".claude", "settings.json");
1139
- try {
1140
- if (!lstatSync5(join14(repoRoot, ".claude")).isDirectory()) return null;
1141
- const stat = lstatSync5(path);
1142
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1143
- return readFileSync13(path, "utf8");
1144
- } catch {
1145
- return null;
1146
- }
1147
- }
1148
- function checkoutDeclaration(repoRoot, name) {
1149
- const text = checkoutSettingsText(repoRoot);
1150
- if (text === null) return null;
1151
- let parsed;
1152
- try {
1153
- parsed = JSON.parse(text);
1154
- } catch {
1155
- return null;
1156
- }
1157
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1158
- const value = typeof env === "object" && env !== null ? env[name] : void 0;
1159
- return typeof value === "string" ? value : null;
1160
- }
1161
- function declaredGithubRepository(repoRoot) {
1162
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1163
- return value === null ? null : parseGithubRepositoryName(value.trim());
1164
- }
1165
- function githubRepositoryFullName(cwd) {
1166
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1167
- if (remote) {
1168
- const fromOrigin = githubRepositoryFromRemote(remote);
1169
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1170
- }
1171
- const root = gitToplevel(cwd);
1172
- return root ? declaredGithubRepository(root) : null;
1173
- }
1174
- function normalizeOriginRemote(remote) {
1175
- const value = remote.trim();
1176
- if (!value) return void 0;
1177
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1178
- if (scp?.host && scp.path) {
1179
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1180
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1181
- }
1182
- try {
1183
- const url = new URL(value);
1184
- url.username = "";
1185
- url.password = "";
1186
- url.search = "";
1187
- url.hash = "";
1188
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1189
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1190
- return void 0;
1191
- } catch {
1192
- return void 0;
1193
- }
1194
- }
1195
- function opaqueRepoKey(source, value) {
1196
- return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
1197
- }
1198
- function resolveRepositoryContext(cwd = process.cwd()) {
1199
- const top = gitToplevel(cwd);
1200
- if (!top) return null;
1201
- let repoRoot;
1202
- try {
1203
- repoRoot = realpathSync.native(top);
1204
- } catch {
1205
- repoRoot = resolve2(top);
1206
- }
1207
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1208
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1209
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1210
- if (normalizedOrigin) {
1211
- return {
1212
- repoRoot,
1213
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
1214
- identitySource: "origin",
1215
- repoFullName
1216
- };
1217
- }
1218
- if (repoFullName) {
1219
- return {
1220
- repoRoot,
1221
- repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1222
- identitySource: "declared",
1223
- repoFullName
1224
- };
1225
- }
1226
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1227
- if (roots && roots.length > 0) {
1228
- return {
1229
- repoRoot,
1230
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1231
- identitySource: "root_commit",
1232
- repoFullName
1233
- };
1234
- }
1235
- return { repoRoot, repoFullName };
1236
- }
1237
-
1238
1512
  // src/lib/activation.ts
1239
1513
  var PRIM_ACTIVE_KEY = "prim.active";
1240
1514
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
@@ -1287,10 +1561,10 @@ function repoSyncId(cwd) {
1287
1561
  function projectPrimInstallAt(root) {
1288
1562
  if (root === null || root === homedir2()) return false;
1289
1563
  for (const rel of PROJECT_INSTALL_FILES) {
1290
- const path = join15(root, rel);
1291
- if (existsSync9(path)) {
1564
+ const path = join18(root, rel);
1565
+ if (existsSync11(path)) {
1292
1566
  try {
1293
- const content = readFileSync14(path, "utf-8");
1567
+ const content = readFileSync15(path, "utf-8");
1294
1568
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
1295
1569
  } catch {
1296
1570
  }
@@ -28291,8 +28565,8 @@ function cachedCollectScopeAdmits(cwd, facts) {
28291
28565
 
28292
28566
  // src/lib/commit-heartbeat.ts
28293
28567
  import { execFileSync as execFileSync5 } from "child_process";
28294
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync15, readdirSync as readdirSync4, unlinkSync } from "fs";
28295
- import { dirname as dirname10, join as join16, resolve as resolve3 } from "path";
28568
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync16, readdirSync as readdirSync5, unlinkSync } from "fs";
28569
+ import { dirname as dirname12, join as join19, resolve as resolve4 } from "path";
28296
28570
  var FIRED_DIR = "prim/post-commit-fired";
28297
28571
  var GIT_TIMEOUT_MS4 = 1e3;
28298
28572
  var MAX_STAMP_BYTES = 1024;
@@ -28307,11 +28581,11 @@ function gitPath(cwd, relative2) {
28307
28581
  timeout: GIT_TIMEOUT_MS4
28308
28582
  }).replace(/\r?\n$/u, "");
28309
28583
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
28310
- return resolve3(cwd, value);
28584
+ return resolve4(cwd, value);
28311
28585
  }
28312
28586
  function ensurePrivateParent(path) {
28313
- mkdirSync7(dirname10(dirname10(path)), { recursive: true, mode: 448 });
28314
- mkdirSync7(dirname10(path), { recursive: true, mode: 448 });
28587
+ mkdirSync8(dirname12(dirname12(path)), { recursive: true, mode: 448 });
28588
+ mkdirSync8(dirname12(path), { recursive: true, mode: 448 });
28315
28589
  }
28316
28590
  function writeStamp(path, at) {
28317
28591
  ensurePrivateParent(path);
@@ -28320,7 +28594,7 @@ function writeStamp(path, at) {
28320
28594
  }
28321
28595
  function readStampAt(path) {
28322
28596
  try {
28323
- const raw = readFileSync15(path, "utf8");
28597
+ const raw = readFileSync16(path, "utf8");
28324
28598
  if (raw.length > MAX_STAMP_BYTES) return void 0;
28325
28599
  const parsed = JSON.parse(raw);
28326
28600
  return typeof parsed.at === "number" && Number.isSafeInteger(parsed.at) && parsed.at > 0 ? parsed.at : void 0;
@@ -28332,11 +28606,11 @@ function recordPostCommitFired(cwd, sha, now = Date.now()) {
28332
28606
  if (!sha || !FULL_SHA_RE.test(sha)) return;
28333
28607
  try {
28334
28608
  const dir = gitPath(cwd, FIRED_DIR);
28335
- writeStamp(join16(dir, sha), now);
28336
- const names = readdirSync4(dir).filter((name) => FULL_SHA_RE.test(name));
28609
+ writeStamp(join19(dir, sha), now);
28610
+ const names = readdirSync5(dir).filter((name) => FULL_SHA_RE.test(name));
28337
28611
  if (names.length <= MAX_FIRED_STAMPS + PRUNE_SLACK) return;
28338
- const stale = names.map((name) => ({ name, at: readStampAt(join16(dir, name)) ?? 0 })).sort((left, right) => right.at - left.at || left.name.localeCompare(right.name)).slice(MAX_FIRED_STAMPS);
28339
- for (const { name } of stale) unlinkSync(join16(dir, name));
28612
+ const stale = names.map((name) => ({ name, at: readStampAt(join19(dir, name)) ?? 0 })).sort((left, right) => right.at - left.at || left.name.localeCompare(right.name)).slice(MAX_FIRED_STAMPS);
28613
+ for (const { name } of stale) unlinkSync(join19(dir, name));
28340
28614
  } catch {
28341
28615
  }
28342
28616
  }
@@ -28351,22 +28625,22 @@ function unattendedEnv(env = process.env) {
28351
28625
  import { execFileSync as execFileSync6 } from "child_process";
28352
28626
  import { randomUUID as randomUUID3 } from "crypto";
28353
28627
  import {
28354
- constants as constants2,
28355
- chmodSync as chmodSync5,
28628
+ constants as constants3,
28629
+ chmodSync as chmodSync6,
28356
28630
  closeSync as closeSync3,
28357
28631
  fchmodSync as fchmodSync2,
28358
28632
  fsyncSync as fsyncSync2,
28359
28633
  linkSync as linkSync2,
28360
- lstatSync as lstatSync6,
28361
- mkdirSync as mkdirSync8,
28634
+ lstatSync as lstatSync7,
28635
+ mkdirSync as mkdirSync9,
28362
28636
  openSync as openSync3,
28363
- readFileSync as readFileSync16,
28364
- statSync as statSync2,
28637
+ readFileSync as readFileSync17,
28638
+ statSync as statSync3,
28365
28639
  unlinkSync as unlinkSync2,
28366
- writeFileSync as writeFileSync5
28640
+ writeFileSync as writeFileSync6
28367
28641
  } from "fs";
28368
- import { dirname as dirname11, isAbsolute as isAbsolute4, join as join17, resolve as resolve4 } from "path";
28369
- var WORKSPACE_ID_RELATIVE_PATH = join17("prim", "workspace-id");
28642
+ import { dirname as dirname13, isAbsolute as isAbsolute5, join as join20, resolve as resolve5 } from "path";
28643
+ var WORKSPACE_ID_RELATIVE_PATH = join20("prim", "workspace-id");
28370
28644
  var MAX_ANCESTORS = 64;
28371
28645
  var MAX_GIT_FILE_BYTES = 4096;
28372
28646
  var MAX_ID_FILE_BYTES = 128;
@@ -28412,7 +28686,7 @@ function resolveWorkspaceIdPath(cwd) {
28412
28686
  }
28413
28687
  return {
28414
28688
  status: "resolved",
28415
- path: isAbsolute4(gitPath2) ? resolve4(gitPath2) : resolve4(cwd, gitPath2)
28689
+ path: isAbsolute5(gitPath2) ? resolve5(gitPath2) : resolve5(cwd, gitPath2)
28416
28690
  };
28417
28691
  } catch (error) {
28418
28692
  const code = errorCode(error);
@@ -28423,21 +28697,21 @@ function resolveWorkspaceIdPath(cwd) {
28423
28697
  }
28424
28698
  }
28425
28699
  function resolveFromFilesystem(cwd) {
28426
- let current = resolve4(cwd);
28700
+ let current = resolve5(cwd);
28427
28701
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
28428
- const dotGit = join17(current, ".git");
28702
+ const dotGit = join20(current, ".git");
28429
28703
  try {
28430
- const stat = lstatSync6(dotGit);
28704
+ const stat = lstatSync7(dotGit);
28431
28705
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
28432
- return join17(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28706
+ return join20(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28433
28707
  }
28434
28708
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
28435
- const contents = readFileSync16(dotGit, "utf8");
28709
+ const contents = readFileSync17(dotGit, "utf8");
28436
28710
  const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
28437
28711
  if (match?.[1]) {
28438
- const gitDirectory = isAbsolute4(match[1]) ? resolve4(match[1]) : resolve4(current, match[1]);
28712
+ const gitDirectory = isAbsolute5(match[1]) ? resolve5(match[1]) : resolve5(current, match[1]);
28439
28713
  if (isGitDirectory(gitDirectory)) {
28440
- return join17(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28714
+ return join20(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28441
28715
  }
28442
28716
  }
28443
28717
  }
@@ -28448,7 +28722,7 @@ function resolveFromFilesystem(cwd) {
28448
28722
  return null;
28449
28723
  }
28450
28724
  }
28451
- const parent = dirname11(current);
28725
+ const parent = dirname13(current);
28452
28726
  if (parent === current) break;
28453
28727
  current = parent;
28454
28728
  }
@@ -28456,7 +28730,7 @@ function resolveFromFilesystem(cwd) {
28456
28730
  }
28457
28731
  function isGitDirectory(path) {
28458
28732
  try {
28459
- return statSync2(join17(path, "HEAD")).isFile();
28733
+ return statSync3(join20(path, "HEAD")).isFile();
28460
28734
  } catch {
28461
28735
  return false;
28462
28736
  }
@@ -28464,7 +28738,7 @@ function isGitDirectory(path) {
28464
28738
  function inspectPath(path) {
28465
28739
  let stat;
28466
28740
  try {
28467
- stat = lstatSync6(path);
28741
+ stat = lstatSync7(path);
28468
28742
  } catch (error) {
28469
28743
  const code = errorCode(error);
28470
28744
  if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing", path };
@@ -28475,7 +28749,7 @@ function inspectPath(path) {
28475
28749
  return { status: "corrupt", path, reason: "invalid_content" };
28476
28750
  }
28477
28751
  try {
28478
- const contents = readFileSync16(path, "utf8");
28752
+ const contents = readFileSync17(path, "utf8");
28479
28753
  const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
28480
28754
  if ((contents === workspaceId || contents === `${workspaceId}
28481
28755
  `) && isCanonicalWorkspaceId(workspaceId)) {
@@ -28492,22 +28766,22 @@ function inspectPath(path) {
28492
28766
  }
28493
28767
  }
28494
28768
  function createWorkspaceId(path) {
28495
- const parent = dirname11(path);
28769
+ const parent = dirname13(path);
28496
28770
  const workspaceId = randomUUID3();
28497
- const temporaryPath = join17(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28771
+ const temporaryPath = join20(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28498
28772
  let temporaryCreated = false;
28499
28773
  let publishing = false;
28500
28774
  try {
28501
- mkdirSync8(parent, { recursive: true, mode: 448 });
28502
- chmodSync5(parent, 448);
28775
+ mkdirSync9(parent, { recursive: true, mode: 448 });
28776
+ chmodSync6(parent, 448);
28503
28777
  const fd = openSync3(
28504
28778
  temporaryPath,
28505
- constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY,
28779
+ constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY,
28506
28780
  384
28507
28781
  );
28508
28782
  temporaryCreated = true;
28509
28783
  try {
28510
- writeFileSync5(fd, `${workspaceId}
28784
+ writeFileSync6(fd, `${workspaceId}
28511
28785
  `, "utf8");
28512
28786
  fchmodSync2(fd, 384);
28513
28787
  fsyncSync2(fd);
@@ -28554,7 +28828,7 @@ function errorCode(error) {
28554
28828
  }
28555
28829
 
28556
28830
  // src/hooks/prim-hook-core.ts
28557
- import { createHash as createHash7, randomUUID as randomUUID4 } from "crypto";
28831
+ import { createHash as createHash9, randomUUID as randomUUID4 } from "crypto";
28558
28832
  import { platform } from "os";
28559
28833
 
28560
28834
  // src/protocol/move.ts
@@ -28563,8 +28837,8 @@ var AGENT_ENVELOPE_VERSION = 3;
28563
28837
  var ENVELOPE_VERSION = LEGACY_ENVELOPE_VERSION;
28564
28838
 
28565
28839
  // src/hooks/redact.ts
28566
- import { existsSync as existsSync10, readFileSync as readFileSync17, statSync as statSync3 } from "fs";
28567
- import { join as join18 } from "path";
28840
+ import { existsSync as existsSync12, readFileSync as readFileSync18, statSync as statSync4 } from "fs";
28841
+ import { join as join21 } from "path";
28568
28842
  import { Worker } from "worker_threads";
28569
28843
  var USER_HOME_RULES = [
28570
28844
  {
@@ -28707,7 +28981,7 @@ function toCommitMove(commit, cliVersion, cwd, context = {}) {
28707
28981
  const validatedAttribution = validatedWorkspaceId ? attribution : void 0;
28708
28982
  const validatedCapturedAt = typeof capturedAt === "number" && Number.isSafeInteger(capturedAt) && capturedAt > 0 ? capturedAt : Date.now();
28709
28983
  const fullSha = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commit.sha);
28710
- const moveId = validatedRepoSyncId && validatedWorkspaceId && fullSha ? `commit:v2:${createHash7("sha256").update(
28984
+ const moveId = validatedRepoSyncId && validatedWorkspaceId && fullSha ? `commit:v2:${createHash9("sha256").update(
28711
28985
  JSON.stringify(["commit:v2", validatedRepoSyncId, validatedWorkspaceId, commit.sha])
28712
28986
  ).digest("hex")}` : `commit:v2:unscoped:${randomUUID4()}`;
28713
28987
  const base = {
@@ -28745,7 +29019,7 @@ function toCommitMove(commit, cliVersion, cwd, context = {}) {
28745
29019
  }
28746
29020
 
28747
29021
  // src/hooks/post-commit.ts
28748
- var here = dirname12(fileURLToPath4(import.meta.url));
29022
+ var here = dirname14(fileURLToPath5(import.meta.url));
28749
29023
  var GIT_TIMEOUT_MS5 = 1e3;
28750
29024
  var FULL_SHA_RE2 = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u;
28751
29025
  var OBSERVATION_MARKER_RE = /^prim-post-commit-observed\.[A-Za-z0-9]+$/u;
@@ -28753,9 +29027,9 @@ var MAX_OBSERVATION_MARKER_AGE_MS = 10 * 60 * 1e3;
28753
29027
  var MAX_OBSERVATION_MARKER_FUTURE_SKEW_MS = 5e3;
28754
29028
  function capturedAtFromLauncher(env = process.env, now = Date.now()) {
28755
29029
  const path = env.PRIM_COMMIT_OBSERVED_FILE;
28756
- if (!path || !isAbsolute5(path) || !OBSERVATION_MARKER_RE.test(basename4(path))) return;
29030
+ if (!path || !isAbsolute6(path) || !OBSERVATION_MARKER_RE.test(basename4(path))) return;
28757
29031
  try {
28758
- const stat = lstatSync7(path);
29032
+ const stat = lstatSync8(path);
28759
29033
  const capturedAt = Math.trunc(stat.mtimeMs);
28760
29034
  const uid = process.getuid?.();
28761
29035
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== 0 || stat.nlink !== 1 || (stat.mode & 63) !== 0 || uid !== void 0 && stat.uid !== uid || !Number.isSafeInteger(capturedAt) || capturedAt <= 0 || capturedAt < now - MAX_OBSERVATION_MARKER_AGE_MS || capturedAt > now + MAX_OBSERVATION_MARKER_FUTURE_SKEW_MS) {
@@ -28839,14 +29113,14 @@ function readCommit() {
28839
29113
  }
28840
29114
  function resolveCliVersion() {
28841
29115
  try {
28842
- const pkg = JSON.parse(readFileSync18(join19(here, "..", "..", "package.json"), "utf-8"));
29116
+ const pkg = JSON.parse(readFileSync19(join22(here, "..", "..", "package.json"), "utf-8"));
28843
29117
  return pkg.version ?? "unknown";
28844
29118
  } catch {
28845
29119
  return "unknown";
28846
29120
  }
28847
29121
  }
28848
29122
  function spawnBackgroundFlush() {
28849
- const entry = join19(here, "..", "index.js");
29123
+ const entry = join22(here, "..", "index.js");
28850
29124
  spawn2(process.execPath, [entry, "moves", "flush"], {
28851
29125
  detached: true,
28852
29126
  stdio: "ignore",