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

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-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
  3. package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
  4. package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
  5. package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
  6. package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
  7. package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
  8. package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
  9. package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
  10. package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
  11. package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
  12. package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
  13. package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
  14. package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
  15. package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
  16. package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
  17. package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
  19. package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
  20. package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
  21. package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
  22. package/dist/daemon/server.js +1311 -364
  23. package/dist/hook-runtime/daemon/server.js +1311 -364
  24. package/dist/hook-runtime/hooks/post-commit.js +395 -242
  25. package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
  27. package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
  29. package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
  30. package/dist/hook-runtime/hooks/session-end.js +369 -216
  31. package/dist/hook-runtime/hooks/session-start.js +1209 -219
  32. package/dist/hook-runtime/index.js +2406 -1036
  33. package/dist/hook-runtime/statusline-main.js +360 -207
  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 +63 -20
  42. package/dist/index.js +387 -43
  43. package/dist/statusline-main.js +360 -207
  44. package/package.json +1 -1
@@ -55,33 +55,33 @@ var require_ucs2length = __commonJS({
55
55
  // src/hooks/post-commit.ts
56
56
  import { execFileSync as execFileSync7, spawn as spawn2 } from "child_process";
57
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";
58
+ import { basename as basename4, dirname as dirname12, isAbsolute as isAbsolute5, join as join20 } from "path";
59
59
  import { fileURLToPath as fileURLToPath4 } 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 existsSync4, readFileSync as readFileSync8 } from "fs";
63
+ import { dirname as dirname6, join as join10 } 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 createHash6 } from "crypto";
67
+ import { readFileSync as readFileSync7 } from "fs";
68
+ import { join as join9 } 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 createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
73
73
  import {
74
74
  chmodSync,
75
75
  existsSync as existsSync3,
76
76
  linkSync,
77
- lstatSync as lstatSync3,
77
+ lstatSync as lstatSync4,
78
78
  mkdirSync as mkdirSync3,
79
- readFileSync as readFileSync5,
80
- rmSync as rmSync5,
79
+ readFileSync as readFileSync6,
80
+ rmSync as rmSync6,
81
81
  writeFileSync as writeFileSync3
82
82
  } from "fs";
83
83
  import { createRequire } from "module";
84
- import { dirname as dirname4, join as join6 } from "path";
84
+ import { dirname as dirname5, join as join8 } from "path";
85
85
  import { fileURLToPath as fileURLToPath3 } from "url";
86
86
 
87
87
  // src/lib/atomic-file.ts
@@ -229,6 +229,8 @@ import { Readable } from "stream";
229
229
  function isClaudeCloudSession(env = process.env) {
230
230
  return env.CLAUDE_CODE_REMOTE === "true";
231
231
  }
232
+ 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';
233
+ 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
234
 
233
235
  // src/lib/workos-connect.ts
234
236
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -416,24 +418,320 @@ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rm
416
418
  import { join as join5 } from "path";
417
419
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
418
420
 
421
+ // src/lib/session-identity.ts
422
+ import { execFile } from "child_process";
423
+ import { createHash as createHash4 } from "crypto";
424
+ import { rmSync as rmSync5 } from "fs";
425
+ import { join as join7 } from "path";
426
+ import { promisify } from "util";
427
+
428
+ // src/lib/git.ts
429
+ import { execFileSync } from "child_process";
430
+ import { createHash as createHash3 } from "crypto";
431
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
432
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
433
+ var GIT_TIMEOUT_MS = 1e3;
434
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
435
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
436
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
437
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
438
+ function gitChildEnvironment(env = process.env) {
439
+ return Object.fromEntries(
440
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
441
+ );
442
+ }
443
+ function gitToplevel(cwd) {
444
+ try {
445
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
446
+ cwd,
447
+ encoding: "utf-8",
448
+ stdio: ["ignore", "pipe", "ignore"],
449
+ timeout: GIT_TIMEOUT_MS,
450
+ env: gitChildEnvironment()
451
+ }).trim();
452
+ } catch {
453
+ return null;
454
+ }
455
+ }
456
+ function gitValue(cwd, args) {
457
+ try {
458
+ const value = execFileSync("git", args, {
459
+ cwd,
460
+ encoding: "utf-8",
461
+ stdio: ["ignore", "pipe", "ignore"],
462
+ timeout: GIT_TIMEOUT_MS,
463
+ env: gitChildEnvironment()
464
+ }).trim();
465
+ return value || void 0;
466
+ } catch {
467
+ return void 0;
468
+ }
469
+ }
470
+ function parseGithubRepositoryName(path) {
471
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
472
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
473
+ return null;
474
+ }
475
+ return `${parts[0]}/${parts[1]}`;
476
+ }
477
+ function githubRepositoryFromRemote(remote) {
478
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
479
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
480
+ remote
481
+ );
482
+ const path = match?.[1] ?? match?.[2];
483
+ return path ? parseGithubRepositoryName(path) : null;
484
+ }
485
+ function checkoutSettingsText(repoRoot) {
486
+ const path = join6(repoRoot, ".claude", "settings.json");
487
+ try {
488
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
489
+ const stat = lstatSync3(path);
490
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
491
+ return readFileSync5(path, "utf8");
492
+ } catch {
493
+ return null;
494
+ }
495
+ }
496
+ function checkoutDeclaration(repoRoot, name) {
497
+ const text = checkoutSettingsText(repoRoot);
498
+ if (text === null) return null;
499
+ let parsed;
500
+ try {
501
+ parsed = JSON.parse(text);
502
+ } catch {
503
+ return null;
504
+ }
505
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
506
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
507
+ return typeof value === "string" ? value : null;
508
+ }
509
+ function declaredGithubRepository(repoRoot) {
510
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
511
+ return value === null ? null : parseGithubRepositoryName(value.trim());
512
+ }
513
+ function githubRepositoryFullName(cwd) {
514
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
515
+ if (remote) {
516
+ const fromOrigin = githubRepositoryFromRemote(remote);
517
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
518
+ }
519
+ const root = gitToplevel(cwd);
520
+ return root ? declaredGithubRepository(root) : null;
521
+ }
522
+ function normalizeOriginRemote(remote) {
523
+ const value = remote.trim();
524
+ if (!value) return void 0;
525
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
526
+ if (scp?.host && scp.path) {
527
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
528
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
529
+ }
530
+ try {
531
+ const url = new URL(value);
532
+ url.username = "";
533
+ url.password = "";
534
+ url.search = "";
535
+ url.hash = "";
536
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
537
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
538
+ return void 0;
539
+ } catch {
540
+ return void 0;
541
+ }
542
+ }
543
+ function opaqueRepoKey(source, value) {
544
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
545
+ }
546
+ function resolveRepositoryContext(cwd = process.cwd()) {
547
+ const top = gitToplevel(cwd);
548
+ if (!top) return null;
549
+ let repoRoot;
550
+ try {
551
+ repoRoot = realpathSync.native(top);
552
+ } catch {
553
+ repoRoot = resolve(top);
554
+ }
555
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
556
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
557
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
558
+ if (normalizedOrigin) {
559
+ return {
560
+ repoRoot,
561
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
562
+ identitySource: "origin",
563
+ repoFullName
564
+ };
565
+ }
566
+ if (repoFullName) {
567
+ return {
568
+ repoRoot,
569
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
570
+ identitySource: "declared",
571
+ repoFullName
572
+ };
573
+ }
574
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
575
+ if (roots && roots.length > 0) {
576
+ return {
577
+ repoRoot,
578
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
579
+ identitySource: "root_commit",
580
+ repoFullName
581
+ };
582
+ }
583
+ return { repoRoot, repoFullName };
584
+ }
585
+
586
+ // src/lib/session-identity.ts
587
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
588
+ var SESSION_IDENTITY_VALUE = "session";
589
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
590
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
591
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
592
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
593
+ var RENEW_BEFORE_MS = 6e4;
594
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
595
+ var RESPONSE_MAX_BYTES = 64 * 1024;
596
+ function sessionIdentityRequested(env = process.env) {
597
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
598
+ }
599
+ function sessionIdentityMode(deps = {}) {
600
+ const env = deps.env ?? process.env;
601
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
602
+ }
603
+ function failure(code, cause, remedy) {
604
+ return { status: "failed", code, cause, remedy };
605
+ }
606
+ var NEW_SESSION_REMEDY = "start a new cloud session";
607
+ var SESSION_REVOKED = failure(
608
+ "session_revoked",
609
+ "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",
610
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
611
+ );
612
+ var CHALLENGE_WINDOW_PASSED = failure(
613
+ "challenge_expired",
614
+ "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)",
615
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
616
+ );
617
+ var CHALLENGE_GONE = failure(
618
+ "challenge_not_found",
619
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
620
+ NEW_SESSION_REMEDY
621
+ );
622
+ function hash(value) {
623
+ return createHash4("sha256").update(value).digest("hex");
624
+ }
625
+ function sessionContext(deps) {
626
+ const env = deps.env ?? process.env;
627
+ const environment = environmentCredentials(deps);
628
+ if (!environment)
629
+ return failure(
630
+ "environment_credential_missing",
631
+ "the cloud environment has no environment credential",
632
+ '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'
633
+ );
634
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
635
+ if (!sessionId || !SESSION_ID.test(sessionId))
636
+ return failure(
637
+ "session_id_missing",
638
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
639
+ NEW_SESSION_REMEDY
640
+ );
641
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
642
+ const directory = deps.directory ?? primConfigDirectory({ env });
643
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
644
+ return {
645
+ directory,
646
+ apiUrl,
647
+ clientId: environment.clientId,
648
+ generation: environment.generation,
649
+ sessionId,
650
+ tokenPath: join7(directory, `session_identity_${key}.json`),
651
+ statePath: join7(directory, `session_identity_${key}.state.json`),
652
+ lockPath: join7(directory, "session-identity.lock")
653
+ };
654
+ }
655
+ function readRecord(path) {
656
+ try {
657
+ const value = readMachineMetadata(path);
658
+ return value === void 0 ? void 0 : machineRecord(value);
659
+ } catch {
660
+ return void 0;
661
+ }
662
+ }
663
+ function finiteNumber(value) {
664
+ return typeof value === "number" && Number.isFinite(value);
665
+ }
666
+ function readToken(context) {
667
+ const data = readRecord(context.tokenPath);
668
+ 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))
669
+ return void 0;
670
+ const identity = data.identity;
671
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
672
+ return void 0;
673
+ return data;
674
+ }
675
+ function tokenValid(record, now = Date.now()) {
676
+ return now < record.expiresAt - RENEW_BEFORE_MS;
677
+ }
678
+ function toCredential(record) {
679
+ return {
680
+ issuer: record.issuer,
681
+ audience: record.audience,
682
+ ...record.identity,
683
+ accessToken: record.accessToken,
684
+ expiresAt: record.expiresAt,
685
+ apiUrl: record.apiUrl,
686
+ generation: record.generation,
687
+ storage: "environment",
688
+ session: {
689
+ userId: record.userId,
690
+ displayName: record.displayName,
691
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
692
+ refreshAfter: record.refreshAfter
693
+ }
694
+ };
695
+ }
696
+ function cachedSessionCredential(deps = {}) {
697
+ if (!sessionIdentityMode(deps)) return void 0;
698
+ let context;
699
+ try {
700
+ context = sessionContext(deps);
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ if ("status" in context) return void 0;
705
+ const record = readToken(context);
706
+ return record && tokenValid(record) ? toCredential(record) : void 0;
707
+ }
708
+ var SERVER_CONTRACT_FAILURE = failure(
709
+ "server_contract",
710
+ "Primitive's answer did not identify the linked member",
711
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
712
+ );
713
+
419
714
  // src/lib/machine-credentials.ts
715
+ function sessionScoped(deps) {
716
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
717
+ }
420
718
  var require2 = createRequire(import.meta.url);
421
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
719
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
422
720
  var PROFILE_FILE = "machine_profile.json";
423
721
  var cached;
424
722
  function configurationDirectory(deps) {
425
723
  return deps.directory ?? primConfigDirectory({ env: deps.env });
426
724
  }
427
725
  function apiUrlFor(deps) {
428
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
726
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
429
727
  }
430
- function hash(value) {
431
- return createHash3("sha256").update(value).digest("hex");
728
+ function hash2(value) {
729
+ return createHash5("sha256").update(value).digest("hex");
432
730
  }
433
731
  function environmentContextPath(deps, clientId) {
434
- return join6(
732
+ return join8(
435
733
  configurationDirectory(deps),
436
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
734
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
437
735
  );
438
736
  }
439
737
  function readEnvironmentContext(environment, deps) {
@@ -464,7 +762,7 @@ function protectPath(path, directory) {
464
762
  }
465
763
  const encodedPath = Buffer.from(path).toString("base64");
466
764
  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(
765
+ execFileSync2(
468
766
  "powershell.exe",
469
767
  [
470
768
  "-NoProfile",
@@ -477,24 +775,27 @@ function protectPath(path, directory) {
477
775
  }
478
776
  function ensureDirectory(directory) {
479
777
  mkdirSync3(directory, { recursive: true, mode: 448 });
480
- if (lstatSync3(directory).isSymbolicLink())
778
+ if (lstatSync4(directory).isSymbolicLink())
481
779
  throw new MachineAuthError(
482
780
  "unsafe_storage",
483
781
  "Credential directory must not be a symbolic link."
484
782
  );
485
783
  protectPath(directory, true);
486
784
  }
785
+ function readMachineMetadata(path) {
786
+ return readPrivate(path);
787
+ }
487
788
  function readPrivate(path) {
488
789
  let raw;
489
790
  try {
490
- const stat = lstatSync3(path);
791
+ const stat = lstatSync4(path);
491
792
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
492
793
  throw new MachineAuthError(
493
794
  "unsafe_storage",
494
795
  "Machine credential files must be owner-only regular files."
495
796
  );
496
797
  }
497
- raw = readFileSync5(path, "utf8");
798
+ raw = readFileSync6(path, "utf8");
498
799
  } catch (error) {
499
800
  if (error.code === "ENOENT") return void 0;
500
801
  throw error;
@@ -539,7 +840,7 @@ function parseProfile(value) {
539
840
  };
540
841
  }
541
842
  function readMachineProfile(deps = {}) {
542
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
843
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
543
844
  return value === void 0 ? void 0 : parseProfile(value);
544
845
  }
545
846
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -548,20 +849,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
548
849
  var brokerKeys = /* @__PURE__ */ new Map();
549
850
  function networkSecretBrokerKey(deps, clientId) {
550
851
  const directory = configurationDirectory(deps);
551
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
852
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
552
853
  const known = brokerKeys.get(path);
553
854
  if (known) return known;
554
855
  ensureDirectory(directory);
555
856
  const read = () => {
556
857
  try {
557
- const stat = lstatSync3(path);
858
+ const stat = lstatSync4(path);
558
859
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
559
860
  throw new MachineAuthError(
560
861
  "unsafe_storage",
561
862
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
562
863
  true
563
864
  );
564
- const value = readFileSync5(path, "utf8").trim();
865
+ const value = readFileSync6(path, "utf8").trim();
565
866
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
566
867
  } catch (error) {
567
868
  if (error.code === "ENOENT") return void 0;
@@ -589,7 +890,7 @@ function networkSecretBrokerKey(deps, clientId) {
589
890
  } catch (error) {
590
891
  if (error.code !== "EEXIST") throw error;
591
892
  } finally {
592
- rmSync5(staged, { force: true });
893
+ rmSync6(staged, { force: true });
593
894
  }
594
895
  }
595
896
  const key = read()?.key;
@@ -622,7 +923,7 @@ function environmentCredentials(deps) {
622
923
  "conflicting_credentials",
623
924
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
624
925
  );
625
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
926
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
626
927
  const credentials = {
627
928
  clientId,
628
929
  generation,
@@ -643,12 +944,12 @@ function environmentCredentials(deps) {
643
944
  return {
644
945
  clientId,
645
946
  clientSecret,
646
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
947
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
647
948
  };
648
949
  }
649
950
  function hasMachineConfiguration(deps = {}) {
650
951
  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));
952
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
652
953
  if (configured && env.PRIM_TOKEN?.trim()) {
653
954
  throw new MachineAuthError(
654
955
  "conflicting_credentials",
@@ -660,6 +961,7 @@ function hasMachineConfiguration(deps = {}) {
660
961
  }
661
962
  function machineContext(deps = {}) {
662
963
  if (!hasMachineConfiguration(deps)) return void 0;
964
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
663
965
  const environment = environmentCredentials(deps);
664
966
  if (environment) {
665
967
  if (environmentTerminal === environment.generation) return void 0;
@@ -674,6 +976,7 @@ function machineContext(deps = {}) {
674
976
  return profile;
675
977
  }
676
978
  function cachedMachineCredential(deps = {}) {
979
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
677
980
  const context = machineContext(deps);
678
981
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
679
982
  }
@@ -695,31 +998,31 @@ function machineCaptureActor(deps = {}) {
695
998
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
696
999
  }
697
1000
  function machineJournalBucket(identity) {
698
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1001
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
699
1002
  }
700
1003
  function identityPending(actor) {
701
1004
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
702
1005
  }
703
1006
  function machinePendingBucket(identity) {
704
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
1007
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
705
1008
  }
706
1009
 
707
1010
  // src/lib/credentials.ts
708
1011
  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");
1012
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
1013
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
1014
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
1015
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
1016
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
1017
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
1018
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
1019
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
717
1020
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
718
1021
  var CREDENTIAL_MIGRATION_VERSION = 1;
719
1022
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
720
1023
  function readTrimmed(path) {
721
1024
  try {
722
- const value = readFileSync6(path, "utf8").trim();
1025
+ const value = readFileSync7(path, "utf8").trim();
723
1026
  return value || void 0;
724
1027
  } catch {
725
1028
  return void 0;
@@ -756,7 +1059,7 @@ function resolveAuthCredential(options = {}) {
756
1059
  return { token: stored, source: "token_file" };
757
1060
  }
758
1061
  function credentialFingerprint(value) {
759
- return createHash4("sha256").update(value).digest("hex");
1062
+ return createHash6("sha256").update(value).digest("hex");
760
1063
  }
761
1064
  function parseLegacyBrokerCredentialMetadata(value) {
762
1065
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -776,7 +1079,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
776
1079
  function readBoundedCredentialJson(path) {
777
1080
  let raw;
778
1081
  try {
779
- raw = readFileSync6(path, "utf8");
1082
+ raw = readFileSync7(path, "utf8");
780
1083
  } catch (error) {
781
1084
  return error.code === "ENOENT" ? void 0 : null;
782
1085
  }
@@ -849,14 +1152,14 @@ function jwtOrganizationId(token) {
849
1152
 
850
1153
  // src/binding.ts
851
1154
  var PRIM_CONFIG_DIR = primConfigDirectory();
852
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
1155
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
853
1156
  var WORKSPACE_FILE = ".prim/workspace.json";
854
1157
  function readJsonSafe(path) {
855
1158
  if (!existsSync4(path)) {
856
1159
  return;
857
1160
  }
858
1161
  try {
859
- return JSON.parse(readFileSync7(path, "utf-8"));
1162
+ return JSON.parse(readFileSync8(path, "utf-8"));
860
1163
  } catch {
861
1164
  return;
862
1165
  }
@@ -865,17 +1168,17 @@ function fromSessionMarker(sessionId) {
865
1168
  if (!sessionId) {
866
1169
  return;
867
1170
  }
868
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
1171
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
869
1172
  return marker?.orgId;
870
1173
  }
871
1174
  function fromWorkspaceFile(startDir) {
872
1175
  let dir = startDir;
873
1176
  while (true) {
874
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
1177
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
875
1178
  if (config?.orgId) {
876
1179
  return config.orgId;
877
1180
  }
878
- const parent = dirname5(dir);
1181
+ const parent = dirname6(dir);
879
1182
  if (parent === dir) {
880
1183
  return;
881
1184
  }
@@ -916,21 +1219,21 @@ import {
916
1219
  mkdirSync as mkdirSync5,
917
1220
  openSync as openSync2,
918
1221
  opendirSync,
919
- readFileSync as readFileSync11,
1222
+ readFileSync as readFileSync12,
920
1223
  readSync,
921
1224
  readdirSync as readdirSync3
922
1225
  } from "fs";
923
- import { dirname as dirname8, join as join12 } from "path";
1226
+ import { dirname as dirname9, join as join14 } from "path";
924
1227
 
925
1228
  // 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";
1229
+ import { createHash as createHash7 } from "crypto";
1230
+ import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync7 } from "fs";
1231
+ import { dirname as dirname7 } from "path";
929
1232
 
930
1233
  // src/daemon/client-instance-id.ts
931
1234
  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";
1235
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync9 } from "fs";
1236
+ import { join as join11 } from "path";
934
1237
  var INSTANCE_BODY_CHARS = 43;
935
1238
  var INSTANCE_PREFIX = "pci_";
936
1239
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -939,12 +1242,12 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
939
1242
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
940
1243
 
941
1244
  // src/client.ts
942
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1245
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
943
1246
  function getSiteUrl() {
944
1247
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
945
1248
  }
946
1249
  function getSiteUrlForEnvironment(primApiUrl) {
947
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1250
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
948
1251
  }
949
1252
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
950
1253
 
@@ -952,15 +1255,15 @@ var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
952
1255
  import {
953
1256
  chmodSync as chmodSync4,
954
1257
  existsSync as existsSync6,
955
- readFileSync as readFileSync10,
1258
+ readFileSync as readFileSync11,
956
1259
  readdirSync as readdirSync2,
957
- rmSync as rmSync7,
1260
+ rmSync as rmSync8,
958
1261
  rmdirSync
959
1262
  } from "fs";
960
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
1263
+ import { basename as basename3, dirname as dirname8, join as join13 } from "path";
961
1264
 
962
1265
  // src/journal.ts
963
- var JOURNAL_DIR = join12(primConfigDirectory(), "moves");
1266
+ var JOURNAL_DIR = join14(primConfigDirectory(), "moves");
964
1267
  var UNBOUND_BUCKET = "_unbound";
965
1268
  var JOURNAL_BASENAME = "journal.ndjson";
966
1269
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -972,14 +1275,14 @@ function envSlug(apiUrl) {
972
1275
  return slug;
973
1276
  }
974
1277
  function currentEnvDir() {
975
- return join12(JOURNAL_DIR, envSlug(getSiteUrl()));
1278
+ return join14(JOURNAL_DIR, envSlug(getSiteUrl()));
976
1279
  }
977
1280
  var DIR_MODE = 448;
978
1281
  var FILE_MODE = 384;
979
1282
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
980
1283
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
981
1284
  function appendMoveToPath(path, move) {
982
- const dir = dirname8(path);
1285
+ const dir = dirname9(path);
983
1286
  if (!existsSync7(dir)) {
984
1287
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
985
1288
  }
@@ -988,10 +1291,10 @@ function appendMoveToPath(path, move) {
988
1291
  }
989
1292
  function bucketDir(orgId) {
990
1293
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
991
- return join12(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
1294
+ return join14(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
992
1295
  }
993
1296
  function journalPath(orgId) {
994
- return join12(bucketDir(orgId), JOURNAL_BASENAME);
1297
+ return join14(bucketDir(orgId), JOURNAL_BASENAME);
995
1298
  }
996
1299
  function appendMove(move, orgId) {
997
1300
  const actor = machineCaptureActor();
@@ -1006,14 +1309,14 @@ var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
1006
1309
  import { execFileSync as execFileSync4 } from "child_process";
1007
1310
  import { existsSync as existsSync9, readFileSync as readFileSync14 } from "fs";
1008
1311
  import { homedir as homedir2 } from "os";
1009
- import { join as join15 } from "path";
1312
+ import { join as join16 } from "path";
1010
1313
 
1011
1314
  // 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";
1315
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync9, writeFileSync as writeFileSync4 } from "fs";
1316
+ import { join as join15 } from "path";
1014
1317
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
1015
1318
  function cloudPreparedPath(env = process.env) {
1016
- return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1319
+ return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1017
1320
  }
1018
1321
  function isPreparedCloudSession(env = process.env) {
1019
1322
  if (!isClaudeCloudSession(env)) return false;
@@ -1025,17 +1328,17 @@ function isPreparedCloudSession(env = process.env) {
1025
1328
  }
1026
1329
 
1027
1330
  // src/lib/demo-pause.ts
1028
- import { execFileSync as execFileSync2 } from "child_process";
1331
+ import { execFileSync as execFileSync3 } from "child_process";
1029
1332
  var DEMO_PAUSE_MS = 30 * 6e4;
1030
1333
  var PAUSE_KEY = "prim.demoPause";
1031
- var GIT_TIMEOUT_MS = 1e3;
1334
+ var GIT_TIMEOUT_MS2 = 1e3;
1032
1335
  function git(cwd, args) {
1033
1336
  try {
1034
- return execFileSync2("git", args, {
1337
+ return execFileSync3("git", args, {
1035
1338
  cwd,
1036
1339
  encoding: "utf-8",
1037
1340
  stdio: ["ignore", "pipe", "ignore"],
1038
- timeout: GIT_TIMEOUT_MS
1341
+ timeout: GIT_TIMEOUT_MS2
1039
1342
  });
1040
1343
  } catch {
1041
1344
  return void 0;
@@ -1043,10 +1346,10 @@ function git(cwd, args) {
1043
1346
  }
1044
1347
  function setLocal(cwd, key, value) {
1045
1348
  try {
1046
- execFileSync2(
1349
+ execFileSync3(
1047
1350
  "git",
1048
1351
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
1049
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1352
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
1050
1353
  );
1051
1354
  } catch (error) {
1052
1355
  if (value !== null || error.status !== 5) throw error;
@@ -1085,156 +1388,6 @@ function healDemoPause(cwd, pause, options = {}) {
1085
1388
  }
1086
1389
  }
1087
1390
 
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
1391
  // src/lib/activation.ts
1239
1392
  var PRIM_ACTIVE_KEY = "prim.active";
1240
1393
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
@@ -1287,7 +1440,7 @@ function repoSyncId(cwd) {
1287
1440
  function projectPrimInstallAt(root) {
1288
1441
  if (root === null || root === homedir2()) return false;
1289
1442
  for (const rel of PROJECT_INSTALL_FILES) {
1290
- const path = join15(root, rel);
1443
+ const path = join16(root, rel);
1291
1444
  if (existsSync9(path)) {
1292
1445
  try {
1293
1446
  const content = readFileSync14(path, "utf-8");
@@ -28292,7 +28445,7 @@ function cachedCollectScopeAdmits(cwd, facts) {
28292
28445
  // src/lib/commit-heartbeat.ts
28293
28446
  import { execFileSync as execFileSync5 } from "child_process";
28294
28447
  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";
28448
+ import { dirname as dirname10, join as join17, resolve as resolve3 } from "path";
28296
28449
  var FIRED_DIR = "prim/post-commit-fired";
28297
28450
  var GIT_TIMEOUT_MS4 = 1e3;
28298
28451
  var MAX_STAMP_BYTES = 1024;
@@ -28332,11 +28485,11 @@ function recordPostCommitFired(cwd, sha, now = Date.now()) {
28332
28485
  if (!sha || !FULL_SHA_RE.test(sha)) return;
28333
28486
  try {
28334
28487
  const dir = gitPath(cwd, FIRED_DIR);
28335
- writeStamp(join16(dir, sha), now);
28488
+ writeStamp(join17(dir, sha), now);
28336
28489
  const names = readdirSync4(dir).filter((name) => FULL_SHA_RE.test(name));
28337
28490
  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));
28491
+ const stale = names.map((name) => ({ name, at: readStampAt(join17(dir, name)) ?? 0 })).sort((left, right) => right.at - left.at || left.name.localeCompare(right.name)).slice(MAX_FIRED_STAMPS);
28492
+ for (const { name } of stale) unlinkSync(join17(dir, name));
28340
28493
  } catch {
28341
28494
  }
28342
28495
  }
@@ -28365,8 +28518,8 @@ import {
28365
28518
  unlinkSync as unlinkSync2,
28366
28519
  writeFileSync as writeFileSync5
28367
28520
  } 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");
28521
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join18, resolve as resolve4 } from "path";
28522
+ var WORKSPACE_ID_RELATIVE_PATH = join18("prim", "workspace-id");
28370
28523
  var MAX_ANCESTORS = 64;
28371
28524
  var MAX_GIT_FILE_BYTES = 4096;
28372
28525
  var MAX_ID_FILE_BYTES = 128;
@@ -28425,11 +28578,11 @@ function resolveWorkspaceIdPath(cwd) {
28425
28578
  function resolveFromFilesystem(cwd) {
28426
28579
  let current = resolve4(cwd);
28427
28580
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
28428
- const dotGit = join17(current, ".git");
28581
+ const dotGit = join18(current, ".git");
28429
28582
  try {
28430
28583
  const stat = lstatSync6(dotGit);
28431
28584
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
28432
- return join17(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28585
+ return join18(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28433
28586
  }
28434
28587
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
28435
28588
  const contents = readFileSync16(dotGit, "utf8");
@@ -28437,7 +28590,7 @@ function resolveFromFilesystem(cwd) {
28437
28590
  if (match?.[1]) {
28438
28591
  const gitDirectory = isAbsolute4(match[1]) ? resolve4(match[1]) : resolve4(current, match[1]);
28439
28592
  if (isGitDirectory(gitDirectory)) {
28440
- return join17(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28593
+ return join18(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28441
28594
  }
28442
28595
  }
28443
28596
  }
@@ -28456,7 +28609,7 @@ function resolveFromFilesystem(cwd) {
28456
28609
  }
28457
28610
  function isGitDirectory(path) {
28458
28611
  try {
28459
- return statSync2(join17(path, "HEAD")).isFile();
28612
+ return statSync2(join18(path, "HEAD")).isFile();
28460
28613
  } catch {
28461
28614
  return false;
28462
28615
  }
@@ -28494,7 +28647,7 @@ function inspectPath(path) {
28494
28647
  function createWorkspaceId(path) {
28495
28648
  const parent = dirname11(path);
28496
28649
  const workspaceId = randomUUID3();
28497
- const temporaryPath = join17(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28650
+ const temporaryPath = join18(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28498
28651
  let temporaryCreated = false;
28499
28652
  let publishing = false;
28500
28653
  try {
@@ -28554,7 +28707,7 @@ function errorCode(error) {
28554
28707
  }
28555
28708
 
28556
28709
  // src/hooks/prim-hook-core.ts
28557
- import { createHash as createHash7, randomUUID as randomUUID4 } from "crypto";
28710
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto";
28558
28711
  import { platform } from "os";
28559
28712
 
28560
28713
  // src/protocol/move.ts
@@ -28564,7 +28717,7 @@ var ENVELOPE_VERSION = LEGACY_ENVELOPE_VERSION;
28564
28717
 
28565
28718
  // src/hooks/redact.ts
28566
28719
  import { existsSync as existsSync10, readFileSync as readFileSync17, statSync as statSync3 } from "fs";
28567
- import { join as join18 } from "path";
28720
+ import { join as join19 } from "path";
28568
28721
  import { Worker } from "worker_threads";
28569
28722
  var USER_HOME_RULES = [
28570
28723
  {
@@ -28707,7 +28860,7 @@ function toCommitMove(commit, cliVersion, cwd, context = {}) {
28707
28860
  const validatedAttribution = validatedWorkspaceId ? attribution : void 0;
28708
28861
  const validatedCapturedAt = typeof capturedAt === "number" && Number.isSafeInteger(capturedAt) && capturedAt > 0 ? capturedAt : Date.now();
28709
28862
  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(
28863
+ const moveId = validatedRepoSyncId && validatedWorkspaceId && fullSha ? `commit:v2:${createHash8("sha256").update(
28711
28864
  JSON.stringify(["commit:v2", validatedRepoSyncId, validatedWorkspaceId, commit.sha])
28712
28865
  ).digest("hex")}` : `commit:v2:unscoped:${randomUUID4()}`;
28713
28866
  const base = {
@@ -28839,14 +28992,14 @@ function readCommit() {
28839
28992
  }
28840
28993
  function resolveCliVersion() {
28841
28994
  try {
28842
- const pkg = JSON.parse(readFileSync18(join19(here, "..", "..", "package.json"), "utf-8"));
28995
+ const pkg = JSON.parse(readFileSync18(join20(here, "..", "..", "package.json"), "utf-8"));
28843
28996
  return pkg.version ?? "unknown";
28844
28997
  } catch {
28845
28998
  return "unknown";
28846
28999
  }
28847
29000
  }
28848
29001
  function spawnBackgroundFlush() {
28849
- const entry = join19(here, "..", "index.js");
29002
+ const entry = join20(here, "..", "index.js");
28850
29003
  spawn2(process.execPath, [entry, "moves", "flush"], {
28851
29004
  detached: true,
28852
29005
  stdio: "ignore",