@primitive.ai/prim 0.1.0-alpha.97 → 0.1.0-alpha.99

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 (41) hide show
  1. package/README.md +20 -0
  2. package/dist/{chunk-ZYK3TBEW.js → chunk-25DDRMWS.js} +4 -6
  3. package/dist/{chunk-LY6NJ7KL.js → chunk-2IRLFOEL.js} +123 -19
  4. package/dist/{chunk-27ADT6FQ.js → chunk-2Q3OGSTV.js} +44 -6
  5. package/dist/{chunk-35FMRWJH.js → chunk-5LRKJTLA.js} +1 -1
  6. package/dist/{chunk-RK4ZS3HG.js → chunk-6C3CCVDI.js} +2 -2
  7. package/dist/{chunk-UO2U6IKF.js → chunk-7VIMU2HR.js} +1 -1
  8. package/dist/{chunk-OW4GJBLW.js → chunk-EJPKZT5M.js} +2 -2
  9. package/dist/{chunk-2MBV7ZMV.js → chunk-FK7FJPWS.js} +1 -1
  10. package/dist/{chunk-4GHANPWQ.js → chunk-JJI7FU24.js} +2 -2
  11. package/dist/{chunk-AJYZB5PF.js → chunk-JJYS7IPD.js} +3 -3
  12. package/dist/{chunk-Y5W4TZM7.js → chunk-K4JWJ6OM.js} +80 -269
  13. package/dist/{chunk-XEDJ5N3M.js → chunk-KGBMU76T.js} +2 -4
  14. package/dist/{chunk-7KABYYWG.js → chunk-O2WV5SQZ.js} +11 -13
  15. package/dist/{chunk-FBPZ4YUD.js → chunk-X5BN67D2.js} +2 -2
  16. package/dist/{chunk-DWRSEC34.js → chunk-XG7S3LIL.js} +596 -16
  17. package/dist/{chunk-3I4GEWXQ.js → chunk-XPS6LG6I.js} +8 -12
  18. package/dist/{chunk-QNPTWTBG.js → chunk-ZNLIGT3J.js} +2 -2
  19. package/dist/daemon/server.js +247 -180
  20. package/dist/hook-runtime/daemon/server.js +247 -180
  21. package/dist/hook-runtime/hooks/post-commit.js +114 -59
  22. package/dist/hook-runtime/hooks/post-rewrite.js +109 -54
  23. package/dist/hook-runtime/hooks/post-tool-use.js +256 -156
  24. package/dist/hook-runtime/hooks/pre-commit.js +374 -31
  25. package/dist/hook-runtime/hooks/pre-tool-use.js +237 -137
  26. package/dist/hook-runtime/hooks/prim-hook.js +281 -181
  27. package/dist/hook-runtime/hooks/session-start.js +209 -109
  28. package/dist/hook-runtime/index.js +656 -521
  29. package/dist/hook-runtime/statusline-main.js +71 -16
  30. package/dist/hooks/post-commit.js +7 -8
  31. package/dist/hooks/post-rewrite.js +6 -7
  32. package/dist/hooks/post-tool-use.js +13 -14
  33. package/dist/hooks/pre-commit.js +4 -4
  34. package/dist/hooks/pre-tool-use.js +11 -14
  35. package/dist/hooks/prim-hook.js +14 -15
  36. package/dist/hooks/session-end.js +6 -7
  37. package/dist/hooks/session-start.js +13 -14
  38. package/dist/index.js +33 -35
  39. package/dist/statusline-main.js +71 -16
  40. package/package.json +1 -1
  41. package/dist/chunk-DHOQGHKQ.js +0 -379
@@ -5,8 +5,8 @@ import { execSync } from "child_process";
5
5
 
6
6
  // src/client.ts
7
7
  import { createHash as createHash2 } from "crypto";
8
- import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
9
- import { dirname as dirname3 } from "path";
8
+ import { chmodSync as chmodSync2, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync3 } from "fs";
9
+ import { dirname as dirname4 } from "path";
10
10
 
11
11
  // src/lib/atomic-file.ts
12
12
  import { randomUUID } from "crypto";
@@ -496,14 +496,14 @@ function throwIfAborted(signal) {
496
496
  }
497
497
  async function defaultSleep(ms, signal) {
498
498
  if (!signal) {
499
- await new Promise((resolve2) => setTimeout(resolve2, ms));
499
+ await new Promise((resolve3) => setTimeout(resolve3, ms));
500
500
  return;
501
501
  }
502
502
  throwIfAborted(signal);
503
- await new Promise((resolve2, reject) => {
503
+ await new Promise((resolve3, reject) => {
504
504
  const timer = setTimeout(() => {
505
505
  signal.removeEventListener("abort", onAbort);
506
- resolve2();
506
+ resolve3();
507
507
  }, ms);
508
508
  const onAbort = () => {
509
509
  clearTimeout(timer);
@@ -545,6 +545,149 @@ async function withFileLock(lockDir, operation, options = {}) {
545
545
  }
546
546
  }
547
547
 
548
+ // src/daemon/client-instance-id.ts
549
+ import { randomBytes as randomBytes2 } from "crypto";
550
+ import { chmodSync, lstatSync, readFileSync as readFileSync3 } from "fs";
551
+ import { join as join4 } from "path";
552
+ var CONFIG_DIRECTORY_MODE = 448;
553
+ var INSTANCE_FILE_MODE = 384;
554
+ var INSTANCE_ENTROPY_BYTES = 32;
555
+ var INSTANCE_BODY_CHARS = 43;
556
+ var INSTANCE_PREFIX = "pci_";
557
+ var CLIENT_INSTANCE_ID_RE = /^pci_[A-Za-z0-9_-]{43}$/u;
558
+ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
559
+ function isClientInstanceId(value) {
560
+ return typeof value === "string" && CLIENT_INSTANCE_ID_RE.test(value);
561
+ }
562
+ function ensurePrivateConfigDirectory(configDir) {
563
+ ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
564
+ const metadata = lstatSync(configDir);
565
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
566
+ throw new Error("prim config path must be a private directory");
567
+ }
568
+ chmodSync(configDir, CONFIG_DIRECTORY_MODE);
569
+ syncDirectory(configDir);
570
+ }
571
+ function readExisting(path) {
572
+ let metadata;
573
+ try {
574
+ metadata = lstatSync(path);
575
+ } catch (error) {
576
+ if (error.code === "ENOENT") {
577
+ return;
578
+ }
579
+ throw error;
580
+ }
581
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
582
+ throw new Error("stored client instance identity is invalid");
583
+ }
584
+ chmodSync(path, INSTANCE_FILE_MODE);
585
+ if (metadata.size > MAX_STORED_BYTES) {
586
+ throw new Error("stored client instance identity is invalid");
587
+ }
588
+ const raw = readFileSync3(path, "utf8");
589
+ const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
590
+ if (raw !== value && raw !== `${value}
591
+ ` || !isClientInstanceId(value)) {
592
+ throw new Error("stored client instance identity is invalid");
593
+ }
594
+ return value;
595
+ }
596
+ function atomicWrite(path, value) {
597
+ atomicWriteFile(path, `${value}
598
+ `, { mode: INSTANCE_FILE_MODE });
599
+ }
600
+ async function getOrCreateClientInstanceId(options) {
601
+ const configDir = options.configDir;
602
+ const path = join4(configDir, "client_instance_id");
603
+ const lockPath = join4(configDir, "client-instance.lock");
604
+ ensurePrivateConfigDirectory(configDir);
605
+ return withFileLock(
606
+ lockPath,
607
+ () => {
608
+ const existing = readExisting(path);
609
+ if (existing !== void 0) {
610
+ return existing;
611
+ }
612
+ const generated = `${INSTANCE_PREFIX}${randomBytes2(INSTANCE_ENTROPY_BYTES).toString(
613
+ "base64url"
614
+ )}`;
615
+ if (!isClientInstanceId(generated)) {
616
+ throw new Error("generated client instance identity is invalid");
617
+ }
618
+ atomicWrite(path, generated);
619
+ return generated;
620
+ },
621
+ options.lockOptions
622
+ );
623
+ }
624
+
625
+ // src/lib/bin-path.ts
626
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
627
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5 } from "path";
628
+ import { fileURLToPath } from "url";
629
+ var PKG_NAME = "@primitive.ai/prim";
630
+ var ROOT_WALK_LIMIT = 6;
631
+ var resolvedRoot;
632
+ function locateRoot() {
633
+ if (resolvedRoot !== void 0) {
634
+ return resolvedRoot;
635
+ }
636
+ let dir = dirname3(fileURLToPath(import.meta.url));
637
+ for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
638
+ const manifestPath = join5(dir, "package.json");
639
+ if (existsSync2(manifestPath)) {
640
+ try {
641
+ const manifest = JSON.parse(readFileSync4(manifestPath, "utf-8"));
642
+ if (manifest.name === PKG_NAME && manifest.bin) {
643
+ resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
644
+ return resolvedRoot;
645
+ }
646
+ } catch {
647
+ }
648
+ }
649
+ const parent = dirname3(dir);
650
+ if (parent === dir) {
651
+ break;
652
+ }
653
+ dir = parent;
654
+ }
655
+ resolvedRoot = null;
656
+ return resolvedRoot;
657
+ }
658
+ function packageVersion() {
659
+ return locateRoot()?.version ?? null;
660
+ }
661
+ var PRIM_CONFIG_SHELL_RESOLVER = [
662
+ 'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
663
+ 'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
664
+ 'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
665
+ 'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
666
+ "fi; fi; "
667
+ ].join("");
668
+
669
+ // src/lib/ingest-uploader.ts
670
+ var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
671
+ var VERSION_RE = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/u;
672
+ var instanceId;
673
+ async function ingestUploaderHeaders() {
674
+ const headers = {};
675
+ if (runtimeVersion && runtimeVersion.length <= 64 && VERSION_RE.test(runtimeVersion)) {
676
+ headers["X-Prim-Uploader-Version"] = runtimeVersion;
677
+ }
678
+ instanceId ??= getOrCreateClientInstanceId({
679
+ configDir: primConfigDirectory(),
680
+ // Attribution must not consume the upload deadline waiting for another process.
681
+ lockOptions: { timeoutMs: 0 }
682
+ }).catch(() => {
683
+ instanceId = void 0;
684
+ return void 0;
685
+ });
686
+ const id = await instanceId;
687
+ if (id) headers["X-Prim-Client-Instance-Id"] = id;
688
+ return headers;
689
+ }
690
+
548
691
  // src/lib/terminal-safe.ts
549
692
  function replaceIsolatedSurrogates(value) {
550
693
  let out = "";
@@ -594,7 +737,7 @@ var DEFAULT_API_URL = "https://api.getprimitive.ai";
594
737
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
595
738
  function readTrimmed2(path) {
596
739
  try {
597
- const value = readFileSync3(path, "utf8").trim();
740
+ const value = readFileSync5(path, "utf8").trim();
598
741
  return value || void 0;
599
742
  } catch {
600
743
  return void 0;
@@ -610,16 +753,16 @@ function expiresAtFor(token, expiresIn) {
610
753
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
611
754
  }
612
755
  function ensureConfigDirectory() {
613
- const directory = dirname3(TOKEN_FILE_PATH);
756
+ const directory = dirname4(TOKEN_FILE_PATH);
614
757
  mkdirSync3(directory, { recursive: true, mode: CONFIG_DIR_MODE });
615
- chmodSync(directory, CONFIG_DIR_MODE);
758
+ chmodSync2(directory, CONFIG_DIR_MODE);
616
759
  }
617
- function atomicWrite(path, content) {
760
+ function atomicWrite2(path, content) {
618
761
  ensureConfigDirectory();
619
762
  atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
620
763
  }
621
764
  function removeCredentialFile(path) {
622
- if (!existsSync2(path)) return false;
765
+ if (!existsSync3(path)) return false;
623
766
  rmSync3(path, { force: true });
624
767
  return true;
625
768
  }
@@ -653,7 +796,7 @@ function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
653
796
  return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
654
797
  }
655
798
  function writeCredentialMigrationSentinel() {
656
- atomicWrite(
799
+ atomicWrite2(
657
800
  CREDENTIAL_MIGRATION_PATH,
658
801
  `${JSON.stringify({
659
802
  version: CREDENTIAL_MIGRATION_VERSION,
@@ -671,7 +814,7 @@ function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
671
814
  return { state: "invalid" };
672
815
  }
673
816
  if (metadata.metadata === void 0) {
674
- atomicWrite(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
817
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
675
818
  `);
676
819
  }
677
820
  const migrationState = readCredentialMigrationState();
@@ -686,14 +829,14 @@ function preserveMarkerlessLegacyGeneration() {
686
829
  const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
687
830
  if (!(accessToken && refreshToken2)) return;
688
831
  const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
689
- atomicWrite(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
832
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
690
833
  `);
691
834
  }
692
835
  function terminalFingerprint() {
693
836
  return readTrimmed2(TERMINAL_REFRESH_PATH);
694
837
  }
695
838
  function writeTerminalFingerprint(refreshToken2) {
696
- atomicWrite(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
839
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
697
840
  `);
698
841
  }
699
842
  function clearTerminalFingerprint() {
@@ -718,24 +861,24 @@ function commitCredentialsUnlocked(credentials) {
718
861
  if (credentials.metadata !== void 0) {
719
862
  preserveMarkerlessLegacyGeneration();
720
863
  writeCredentialMigrationSentinel();
721
- atomicWrite(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
864
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
722
865
  `);
723
- atomicWrite(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
866
+ atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
724
867
  `);
725
- atomicWrite(REFRESH_TOKEN_PATH, `${refreshToken2}
868
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
726
869
  `);
727
870
  } else {
728
- atomicWrite(REFRESH_TOKEN_PATH, `${refreshToken2}
871
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
729
872
  `);
730
- atomicWrite(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
873
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
731
874
  `);
732
875
  removeCredentialFile(CREDENTIAL_METADATA_PATH);
733
876
  }
734
877
  const expiresAt = expiresAtFor(accessToken, credentials.expiresIn);
735
878
  if (expiresAt === void 0) removeCredentialFile(TOKEN_EXPIRES_PATH);
736
- else atomicWrite(TOKEN_EXPIRES_PATH, `${expiresAt}
879
+ else atomicWrite2(TOKEN_EXPIRES_PATH, `${expiresAt}
737
880
  `);
738
- atomicWrite(TOKEN_FILE_PATH, `${accessToken}
881
+ atomicWrite2(TOKEN_FILE_PATH, `${accessToken}
739
882
  `);
740
883
  clearTerminalFingerprint();
741
884
  _cachedCredential = { token: accessToken, source: "token_file" };
@@ -969,12 +1112,13 @@ function selectedCredential() {
969
1112
  }
970
1113
  return _cachedCredential;
971
1114
  }
972
- function fetchWithToken(method, path, body, options, token, siteUrl) {
1115
+ async function fetchWithToken(method, path, body, options, token, siteUrl) {
973
1116
  return fetch(`${siteUrl}${path}`, {
974
1117
  method,
975
1118
  headers: {
976
1119
  Authorization: `Bearer ${token}`,
977
- "Content-Type": "application/json"
1120
+ "Content-Type": "application/json",
1121
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
978
1122
  },
979
1123
  body: body === void 0 ? void 0 : JSON.stringify(body),
980
1124
  signal: options?.signal
@@ -1038,7 +1182,7 @@ function getClient() {
1038
1182
 
1039
1183
  // src/daemon/client.ts
1040
1184
  import { createConnection } from "net";
1041
- import { join as join5 } from "path";
1185
+ import { join as join7 } from "path";
1042
1186
 
1043
1187
  // src/daemon/principal.ts
1044
1188
  import { createHash as createHash3 } from "crypto";
@@ -1085,7 +1229,7 @@ function parseDaemonResponseEnvelope(value) {
1085
1229
  }
1086
1230
 
1087
1231
  // src/daemon/client.ts
1088
- var SOCK_PATH = join5(primConfigDirectory(), "sock");
1232
+ var SOCK_PATH = join7(primConfigDirectory(), "sock");
1089
1233
  var DEFAULT_TIMEOUT_MS2 = 250;
1090
1234
  var nextRequestId = 1;
1091
1235
  function daemonRequest(method, params = {}, opts = {}) {
@@ -1098,7 +1242,7 @@ function daemonRequest(method, params = {}, opts = {}) {
1098
1242
  ...caller ? { caller } : {}
1099
1243
  };
1100
1244
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
1101
- return new Promise((resolve2) => {
1245
+ return new Promise((resolve3) => {
1102
1246
  let settled = false;
1103
1247
  let socket;
1104
1248
  let buffer = Buffer.alloc(0);
@@ -1113,7 +1257,7 @@ function daemonRequest(method, params = {}, opts = {}) {
1113
1257
  } catch {
1114
1258
  }
1115
1259
  }
1116
- resolve2(value);
1260
+ resolve3(value);
1117
1261
  };
1118
1262
  const timer = setTimeout(() => settle(null), timeoutMs);
1119
1263
  timer.unref();
@@ -1196,6 +1340,173 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
1196
1340
  );
1197
1341
  }
1198
1342
 
1343
+ // src/lib/activation.ts
1344
+ import { execFileSync as execFileSync2 } from "child_process";
1345
+ import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
1346
+ import { homedir as homedir2 } from "os";
1347
+ import { join as join8 } from "path";
1348
+
1349
+ // src/lib/git.ts
1350
+ import { execFileSync } from "child_process";
1351
+ import { createHash as createHash4 } from "crypto";
1352
+ import { lstatSync as lstatSync2, realpathSync } from "fs";
1353
+ import { basename, dirname as dirname5, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
1354
+ var GIT_TIMEOUT_MS = 1e3;
1355
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1356
+ var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
1357
+ function gitToplevel(cwd) {
1358
+ try {
1359
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1360
+ cwd,
1361
+ encoding: "utf-8",
1362
+ stdio: ["ignore", "pipe", "ignore"],
1363
+ timeout: GIT_TIMEOUT_MS
1364
+ }).trim();
1365
+ } catch {
1366
+ return null;
1367
+ }
1368
+ }
1369
+ function gitValue(cwd, args) {
1370
+ try {
1371
+ const value = execFileSync("git", args, {
1372
+ cwd,
1373
+ encoding: "utf-8",
1374
+ stdio: ["ignore", "pipe", "ignore"],
1375
+ timeout: GIT_TIMEOUT_MS
1376
+ }).trim();
1377
+ return value || void 0;
1378
+ } catch {
1379
+ return void 0;
1380
+ }
1381
+ }
1382
+ function currentBranch(cwd) {
1383
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1384
+ }
1385
+ function githubRepositoryFullName(cwd) {
1386
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1387
+ if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
1388
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1389
+ remote
1390
+ );
1391
+ const path = match?.[1] ?? match?.[2];
1392
+ if (!path) return null;
1393
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1394
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1395
+ return null;
1396
+ }
1397
+ return `${parts[0]}/${parts[1]}`;
1398
+ }
1399
+ function canonicalGitRoot(cwd) {
1400
+ try {
1401
+ const top = gitToplevel(cwd);
1402
+ return top ? realpathSync.native(top) : null;
1403
+ } catch {
1404
+ return null;
1405
+ }
1406
+ }
1407
+ function nearestExistingAncestor(path) {
1408
+ const suffix = [];
1409
+ let cursor = path;
1410
+ while (true) {
1411
+ try {
1412
+ lstatSync2(cursor);
1413
+ break;
1414
+ } catch (error) {
1415
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1416
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
1417
+ const parent = dirname5(cursor);
1418
+ if (parent === cursor) return null;
1419
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
1420
+ cursor = parent;
1421
+ }
1422
+ }
1423
+ try {
1424
+ return { real: realpathSync.native(cursor), suffix };
1425
+ } catch {
1426
+ return null;
1427
+ }
1428
+ }
1429
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
1430
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
1431
+ return { ok: false, reason: "invalid_path" };
1432
+ }
1433
+ const absolute = resolve2(baseDir, filePath);
1434
+ const resolved = nearestExistingAncestor(absolute);
1435
+ if (!resolved) return { ok: false, reason: "invalid_path" };
1436
+ const target = resolve2(resolved.real, ...resolved.suffix);
1437
+ const rel = relative(context.repoRoot, target);
1438
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
1439
+ if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1440
+ return { ok: false, reason: "outside_repository" };
1441
+ }
1442
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
1443
+ }
1444
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
1445
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
1446
+ return null;
1447
+ const absolute = resolve2(cwd, filePath);
1448
+ let target;
1449
+ try {
1450
+ const stat = lstatSync2(absolute);
1451
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
1452
+ target = realpathSync.native(absolute);
1453
+ } catch (error) {
1454
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
1455
+ return null;
1456
+ }
1457
+ try {
1458
+ const parent = realpathSync.native(dirname5(absolute));
1459
+ if (!lstatSync2(parent).isDirectory()) return null;
1460
+ target = resolve2(parent, basename(absolute));
1461
+ } catch {
1462
+ return null;
1463
+ }
1464
+ }
1465
+ const rel = relative(repositoryRoot, target);
1466
+ if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1467
+ return null;
1468
+ }
1469
+ return sep === "/" ? rel : rel.split(sep).join("/");
1470
+ }
1471
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
1472
+ if (typeof contextOrCwd === "string") {
1473
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
1474
+ }
1475
+ return canonicalRepositoryPathScoped(
1476
+ filePath,
1477
+ contextOrCwd,
1478
+ baseDirOrRoot ?? contextOrCwd.repoRoot
1479
+ );
1480
+ }
1481
+
1482
+ // src/lib/activation.ts
1483
+ var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
1484
+ var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
1485
+ var GIT_TIMEOUT_MS2 = 1e3;
1486
+ var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
1487
+ function isValidRepoSyncId(value) {
1488
+ return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
1489
+ }
1490
+ function localGitConfigValue(cwd, key) {
1491
+ try {
1492
+ const value = execFileSync2("git", ["config", "--local", "--get", key], {
1493
+ cwd,
1494
+ encoding: "utf-8",
1495
+ stdio: ["ignore", "pipe", "ignore"],
1496
+ timeout: GIT_TIMEOUT_MS2
1497
+ }).trim();
1498
+ return value || void 0;
1499
+ } catch {
1500
+ return void 0;
1501
+ }
1502
+ }
1503
+ function repoSyncId(cwd) {
1504
+ const value = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
1505
+ if (!isValidRepoSyncId(value)) return void 0;
1506
+ const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
1507
+ return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
1508
+ }
1509
+
1199
1510
  // src/hooks/decisions-check.ts
1200
1511
  var DECISIONS_CHECK_TIMEOUT_MS = 1e4;
1201
1512
  var MAX_FILES_PER_REQUEST = 25;
@@ -1207,18 +1518,28 @@ function chunk(items, size) {
1207
1518
  }
1208
1519
  return out;
1209
1520
  }
1210
- async function fetchAffecting(client, batch) {
1521
+ async function fetchAffecting(client, batch, repository) {
1211
1522
  const params = new URLSearchParams();
1523
+ params.set("repoSyncId", repository.repoSyncId);
1524
+ if (repository.branch) params.set("branch", repository.branch);
1212
1525
  for (const file of batch) {
1213
1526
  params.append("files", file);
1214
1527
  }
1215
1528
  try {
1216
- return await daemonOrDirectGet(
1529
+ const response = await daemonOrDirectGet(
1217
1530
  "decisions_affecting",
1218
1531
  `/api/cli/decisions/affecting?${params.toString()}`,
1219
1532
  client,
1220
1533
  DECISIONS_CHECK_TIMEOUT_MS
1221
1534
  );
1535
+ if (response.repoSyncId !== repository.repoSyncId) {
1536
+ return {
1537
+ decisions: [],
1538
+ truncated: response.truncated === true,
1539
+ unavailable: response.unavailable ?? "service did not verify repository-scoped discovery"
1540
+ };
1541
+ }
1542
+ return response;
1222
1543
  } catch (err) {
1223
1544
  const detail = err instanceof Error ? err.message : String(err);
1224
1545
  return { decisions: [], truncated: false, unavailable: `decision check failed: ${detail}` };
@@ -1228,9 +1549,31 @@ async function checkAffectedDecisions(filePaths, deps = defaultDeps) {
1228
1549
  if (filePaths.length === 0) {
1229
1550
  return { decisions: [], truncated: false };
1230
1551
  }
1552
+ const cwd = process.cwd();
1553
+ const root = canonicalGitRoot(cwd);
1554
+ const binding = repoSyncId(cwd);
1555
+ if (!root || !binding) {
1556
+ return {
1557
+ decisions: [],
1558
+ truncated: false,
1559
+ unavailable: "this checkout has no current Primitive repository binding; run prim enable"
1560
+ };
1561
+ }
1562
+ const canonical = filePaths.map(
1563
+ (file) => canonicalRepositoryPath(file, { repoRoot: root }, root)
1564
+ );
1565
+ if (canonical.some((path) => !path.ok)) {
1566
+ return {
1567
+ decisions: [],
1568
+ truncated: false,
1569
+ unavailable: "files must resolve inside this repository; use repository-relative paths"
1570
+ };
1571
+ }
1572
+ const paths = [...new Set(canonical.flatMap((path) => path.ok ? [path.file] : []))];
1573
+ const repository = { repoSyncId: binding, branch: currentBranch(cwd) };
1231
1574
  const client = deps.getClient();
1232
1575
  const responses = await Promise.all(
1233
- chunk(filePaths, MAX_FILES_PER_REQUEST).map((batch) => fetchAffecting(client, batch))
1576
+ chunk(paths, MAX_FILES_PER_REQUEST).map((batch) => fetchAffecting(client, batch, repository))
1234
1577
  );
1235
1578
  const byId = /* @__PURE__ */ new Map();
1236
1579
  let truncated = false;
@@ -1278,7 +1621,7 @@ function formatDecisionsWarning(result) {
1278
1621
  }
1279
1622
  if (result.truncated) {
1280
1623
  lines.push(
1281
- "[prim] result truncated \u2014 more files than the server checks per request; not all decisions shown"
1624
+ "[prim] result truncated \u2014 a discovery scan or result limit was reached; not all decisions shown"
1282
1625
  );
1283
1626
  }
1284
1627
  return lines.join("\n");