@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
@@ -297,7 +297,7 @@ function providerError(value) {
297
297
  return exactString(error, "error", MAX_USER_CODE_LENGTH);
298
298
  }
299
299
  async function defaultSleep(milliseconds, signal) {
300
- await new Promise((resolve, reject) => {
300
+ await new Promise((resolve2, reject) => {
301
301
  if (signal.aborted) {
302
302
  reject(signal.reason);
303
303
  return;
@@ -308,7 +308,7 @@ async function defaultSleep(milliseconds, signal) {
308
308
  };
309
309
  const timer = setTimeout(() => {
310
310
  signal.removeEventListener("abort", abort);
311
- resolve();
311
+ resolve2();
312
312
  }, milliseconds);
313
313
  signal.addEventListener("abort", abort, { once: true });
314
314
  });
@@ -500,6 +500,551 @@ function jwtOrganizationId(token) {
500
500
  return typeof orgId === "string" && orgId.length > 0 ? orgId : void 0;
501
501
  }
502
502
 
503
+ // src/lib/git.ts
504
+ import { execFileSync } from "child_process";
505
+ import { createHash as createHash2 } from "crypto";
506
+ import { lstatSync, realpathSync } from "fs";
507
+ import { basename, dirname, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
508
+ var GIT_TIMEOUT_MS = 1e3;
509
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
510
+ var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
511
+ function gitToplevel(cwd) {
512
+ try {
513
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
514
+ cwd,
515
+ encoding: "utf-8",
516
+ stdio: ["ignore", "pipe", "ignore"],
517
+ timeout: GIT_TIMEOUT_MS
518
+ }).trim();
519
+ } catch {
520
+ return null;
521
+ }
522
+ }
523
+ function mainWorktreeRoot(cwd) {
524
+ try {
525
+ const [gitDir, commonDir] = execFileSync(
526
+ "git",
527
+ ["rev-parse", "--git-dir", "--git-common-dir"],
528
+ {
529
+ cwd,
530
+ encoding: "utf-8",
531
+ stdio: ["ignore", "pipe", "ignore"],
532
+ timeout: GIT_TIMEOUT_MS
533
+ }
534
+ ).trim().split("\n").map((value) => resolve(cwd ?? process.cwd(), value));
535
+ if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
536
+ return basename(commonDir) === ".git" ? dirname(commonDir) : null;
537
+ } catch {
538
+ return null;
539
+ }
540
+ }
541
+ function gitValue(cwd, args) {
542
+ try {
543
+ const value = execFileSync("git", args, {
544
+ cwd,
545
+ encoding: "utf-8",
546
+ stdio: ["ignore", "pipe", "ignore"],
547
+ timeout: GIT_TIMEOUT_MS
548
+ }).trim();
549
+ return value || void 0;
550
+ } catch {
551
+ return void 0;
552
+ }
553
+ }
554
+ function currentBranch(cwd) {
555
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
556
+ }
557
+ function githubRepositoryFullName(cwd) {
558
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
559
+ if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
560
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
561
+ remote
562
+ );
563
+ const path = match?.[1] ?? match?.[2];
564
+ if (!path) return null;
565
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
566
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
567
+ return null;
568
+ }
569
+ return `${parts[0]}/${parts[1]}`;
570
+ }
571
+ function canonicalGitRoot(cwd) {
572
+ try {
573
+ const top = gitToplevel(cwd);
574
+ return top ? realpathSync.native(top) : null;
575
+ } catch {
576
+ return null;
577
+ }
578
+ }
579
+ function relatedWorktreeTarget(path, cwd, origin) {
580
+ let parent = dirname(resolve(cwd, path));
581
+ while (true) {
582
+ try {
583
+ realpathSync.native(parent);
584
+ break;
585
+ } catch {
586
+ const next = dirname(parent);
587
+ if (next === parent) return null;
588
+ parent = next;
589
+ }
590
+ }
591
+ const target = resolveRepositoryContext(parent);
592
+ if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
593
+ const common = (root) => {
594
+ const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
595
+ try {
596
+ return value ? realpathSync.native(resolve(root, value)) : void 0;
597
+ } catch {
598
+ return void 0;
599
+ }
600
+ };
601
+ const originCommon = common(origin.repoRoot);
602
+ return originCommon && originCommon === common(target.repoRoot) ? target : null;
603
+ }
604
+ function normalizeOriginRemote(remote) {
605
+ const value = remote.trim();
606
+ if (!value) return void 0;
607
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
608
+ if (scp?.host && scp.path) {
609
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
610
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
611
+ }
612
+ try {
613
+ const url = new URL(value);
614
+ url.username = "";
615
+ url.password = "";
616
+ url.search = "";
617
+ url.hash = "";
618
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
619
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
620
+ return void 0;
621
+ } catch {
622
+ return void 0;
623
+ }
624
+ }
625
+ function opaqueRepoKey(source, value) {
626
+ return `repo_v1_${createHash2("sha256").update(`${source}\0${value}`).digest("hex")}`;
627
+ }
628
+ function resolveRepositoryContext(cwd = process.cwd()) {
629
+ const top = gitToplevel(cwd);
630
+ if (!top) return null;
631
+ let repoRoot;
632
+ try {
633
+ repoRoot = realpathSync.native(top);
634
+ } catch {
635
+ repoRoot = resolve(top);
636
+ }
637
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
638
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
639
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
640
+ if (normalizedOrigin) {
641
+ return {
642
+ repoRoot,
643
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
644
+ identitySource: "origin",
645
+ repoFullName
646
+ };
647
+ }
648
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
649
+ if (roots && roots.length > 0) {
650
+ return {
651
+ repoRoot,
652
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
653
+ identitySource: "root_commit",
654
+ repoFullName
655
+ };
656
+ }
657
+ return { repoRoot, repoFullName };
658
+ }
659
+ function nearestExistingAncestor(path) {
660
+ const suffix = [];
661
+ let cursor = path;
662
+ while (true) {
663
+ try {
664
+ lstatSync(cursor);
665
+ break;
666
+ } catch (error) {
667
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
668
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
669
+ const parent = dirname(cursor);
670
+ if (parent === cursor) return null;
671
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
672
+ cursor = parent;
673
+ }
674
+ }
675
+ try {
676
+ return { real: realpathSync.native(cursor), suffix };
677
+ } catch {
678
+ return null;
679
+ }
680
+ }
681
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
682
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
683
+ return { ok: false, reason: "invalid_path" };
684
+ }
685
+ const absolute = resolve(baseDir, filePath);
686
+ const resolved = nearestExistingAncestor(absolute);
687
+ if (!resolved) return { ok: false, reason: "invalid_path" };
688
+ const target = resolve(resolved.real, ...resolved.suffix);
689
+ const rel = relative(context.repoRoot, target);
690
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
691
+ if (isAbsolute2(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
692
+ return { ok: false, reason: "outside_repository" };
693
+ }
694
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
695
+ }
696
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
697
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
698
+ return null;
699
+ const absolute = resolve(cwd, filePath);
700
+ let target;
701
+ try {
702
+ const stat = lstatSync(absolute);
703
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
704
+ target = realpathSync.native(absolute);
705
+ } catch (error) {
706
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
707
+ return null;
708
+ }
709
+ try {
710
+ const parent = realpathSync.native(dirname(absolute));
711
+ if (!lstatSync(parent).isDirectory()) return null;
712
+ target = resolve(parent, basename(absolute));
713
+ } catch {
714
+ return null;
715
+ }
716
+ }
717
+ const rel = relative(repositoryRoot, target);
718
+ if (!rel || isAbsolute2(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
719
+ return null;
720
+ }
721
+ return sep === "/" ? rel : rel.split(sep).join("/");
722
+ }
723
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
724
+ if (typeof contextOrCwd === "string") {
725
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
726
+ }
727
+ return canonicalRepositoryPathScoped(
728
+ filePath,
729
+ contextOrCwd,
730
+ baseDirOrRoot ?? contextOrCwd.repoRoot
731
+ );
732
+ }
733
+
734
+ // src/lib/activation.ts
735
+ import { execFileSync as execFileSync2 } from "child_process";
736
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
737
+ import { homedir as homedir2 } from "os";
738
+ import { join as join3 } from "path";
739
+ var PRIM_ACTIVE_KEY = "prim.active";
740
+ var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
741
+ var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
742
+ var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
743
+ var GIT_TIMEOUT_MS2 = 1e3;
744
+ var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
745
+ var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
746
+ var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
747
+ function repoActiveFlag(cwd) {
748
+ try {
749
+ const value = execFileSync2("git", ["config", "--get", PRIM_ACTIVE_KEY], {
750
+ cwd,
751
+ encoding: "utf-8",
752
+ stdio: ["ignore", "pipe", "ignore"],
753
+ timeout: GIT_TIMEOUT_MS2
754
+ }).trim();
755
+ if (value === "true") return "true";
756
+ if (value === "false") return "false";
757
+ return void 0;
758
+ } catch {
759
+ return void 0;
760
+ }
761
+ }
762
+ function isRepoActive(cwd) {
763
+ return repoActiveFlag(cwd) === "true";
764
+ }
765
+ function setRepoActive(cwd, active) {
766
+ execFileSync2("git", ["config", "--local", PRIM_ACTIVE_KEY, active ? "true" : "false"], {
767
+ cwd,
768
+ stdio: ["ignore", "ignore", "pipe"],
769
+ timeout: GIT_TIMEOUT_MS2
770
+ });
771
+ }
772
+ function isValidRepoSyncId(value) {
773
+ return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
774
+ }
775
+ function localGitConfigValue(cwd, key) {
776
+ try {
777
+ const value = execFileSync2("git", ["config", "--local", "--get", key], {
778
+ cwd,
779
+ encoding: "utf-8",
780
+ stdio: ["ignore", "pipe", "ignore"],
781
+ timeout: GIT_TIMEOUT_MS2
782
+ }).trim();
783
+ return value || void 0;
784
+ } catch {
785
+ return void 0;
786
+ }
787
+ }
788
+ function setLocalGitConfigValue(cwd, key, value) {
789
+ execFileSync2("git", ["config", "--local", key, value], {
790
+ cwd,
791
+ stdio: ["ignore", "ignore", "pipe"],
792
+ timeout: GIT_TIMEOUT_MS2
793
+ });
794
+ }
795
+ function repoSyncId(cwd) {
796
+ const value = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
797
+ if (!isValidRepoSyncId(value)) return void 0;
798
+ const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
799
+ return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
800
+ }
801
+ function setRepoSyncId(cwd, value, repositoryFullName) {
802
+ if (!isValidRepoSyncId(value)) {
803
+ throw new Error("invalid repository binding returned by server");
804
+ }
805
+ execFileSync2("git", ["config", "--local", PRIM_REPO_SYNC_ID_KEY, value], {
806
+ cwd,
807
+ stdio: ["ignore", "ignore", "pipe"],
808
+ timeout: GIT_TIMEOUT_MS2
809
+ });
810
+ execFileSync2("git", ["config", "--local", PRIM_REPO_SYNC_REPOSITORY_KEY, repositoryFullName], {
811
+ cwd,
812
+ stdio: ["ignore", "ignore", "pipe"],
813
+ timeout: GIT_TIMEOUT_MS2
814
+ });
815
+ }
816
+ function setRepositoryBindingState(cwd, state) {
817
+ if (state !== "connected" && state !== "unbound" && state !== "invalid") {
818
+ throw new Error("invalid repository binding state");
819
+ }
820
+ execFileSync2("git", ["config", "--local", PRIM_REPO_BINDING_STATE_KEY, state], {
821
+ cwd,
822
+ stdio: ["ignore", "ignore", "pipe"],
823
+ timeout: GIT_TIMEOUT_MS2
824
+ });
825
+ }
826
+ function repositoryBindingState(cwd) {
827
+ const rawId = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
828
+ const marker = localGitConfigValue(cwd, PRIM_REPO_BINDING_STATE_KEY);
829
+ if (rawId !== void 0 && !isValidRepoSyncId(rawId)) return "invalid";
830
+ if (marker === "unbound" || marker === "invalid") return marker;
831
+ if (marker === "connected") return repoSyncId(cwd) ? "connected" : "invalid";
832
+ if (marker !== void 0) return "invalid";
833
+ return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
834
+ }
835
+ function hasProjectPrimInstall(cwd) {
836
+ const root = gitToplevel(cwd);
837
+ if (root === null || root === homedir2()) return false;
838
+ for (const rel of PROJECT_INSTALL_FILES) {
839
+ const path = join3(root, rel);
840
+ if (existsSync(path)) {
841
+ try {
842
+ const content = readFileSync2(path, "utf-8");
843
+ if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
844
+ } catch {
845
+ }
846
+ }
847
+ }
848
+ return false;
849
+ }
850
+ function isRepoActiveForCapture(cwd) {
851
+ const flag = repoActiveFlag(cwd);
852
+ if (flag === "true") return true;
853
+ if (flag === "false") return false;
854
+ return hasProjectPrimInstall(cwd);
855
+ }
856
+ function decisionIngestionStatus(cwd) {
857
+ return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
858
+ }
859
+
860
+ // src/lib/bin-path.ts
861
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
862
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join4 } from "path";
863
+ import { fileURLToPath } from "url";
864
+
865
+ // src/lib/semver.ts
866
+ function parseSemver(value) {
867
+ if (typeof value !== "string" || value.length > 256) return;
868
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
869
+ value
870
+ );
871
+ if (!match) return;
872
+ const prerelease = match[4]?.split(".") ?? [];
873
+ if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
874
+ return;
875
+ }
876
+ return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
877
+ }
878
+ function compareSemver(left, right) {
879
+ const a = parseSemver(left);
880
+ const b = parseSemver(right);
881
+ if (!a || !b) return;
882
+ for (let i = 0; i < a.core.length; i += 1) {
883
+ if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
884
+ }
885
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) {
886
+ return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
887
+ }
888
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
889
+ const x = a.prerelease[i];
890
+ const y = b.prerelease[i];
891
+ if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
892
+ if (x === y) continue;
893
+ const xNumeric = /^\d+$/u.test(x);
894
+ const yNumeric = /^\d+$/u.test(y);
895
+ if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
896
+ if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
897
+ return x < y ? -1 : 1;
898
+ }
899
+ return 0;
900
+ }
901
+
902
+ // src/lib/bin-path.ts
903
+ var PKG_NAME = "@primitive.ai/prim";
904
+ var ROOT_WALK_LIMIT = 6;
905
+ var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
906
+ var resolvedRoot;
907
+ function locateRoot() {
908
+ if (resolvedRoot !== void 0) {
909
+ return resolvedRoot;
910
+ }
911
+ let dir = dirname2(fileURLToPath(import.meta.url));
912
+ for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
913
+ const manifestPath = join4(dir, "package.json");
914
+ if (existsSync2(manifestPath)) {
915
+ try {
916
+ const manifest = JSON.parse(readFileSync3(manifestPath, "utf-8"));
917
+ if (manifest.name === PKG_NAME && manifest.bin) {
918
+ resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
919
+ return resolvedRoot;
920
+ }
921
+ } catch {
922
+ }
923
+ }
924
+ const parent = dirname2(dir);
925
+ if (parent === dir) {
926
+ break;
927
+ }
928
+ dir = parent;
929
+ }
930
+ resolvedRoot = null;
931
+ return resolvedRoot;
932
+ }
933
+ function binFile(bin) {
934
+ const root = locateRoot();
935
+ const rel = root?.bin[bin];
936
+ if (!root || !rel) {
937
+ return null;
938
+ }
939
+ return isAbsolute3(rel) ? rel : join4(root.dir, rel);
940
+ }
941
+ function packageVersion() {
942
+ return locateRoot()?.version ?? null;
943
+ }
944
+ function packageRoot() {
945
+ return locateRoot()?.dir ?? null;
946
+ }
947
+ function shellQuote(value) {
948
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
949
+ }
950
+ function shellWord(value) {
951
+ return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : shellQuote(value);
952
+ }
953
+ function pinnedNpxArgs(bin, args = [], options = {}) {
954
+ const version = packageVersion();
955
+ if (!version) throw new Error("cannot determine Primitive package version");
956
+ return [
957
+ "--yes",
958
+ "--ignore-scripts",
959
+ ...options.preferOnline ? ["--prefer-online"] : [],
960
+ "-p",
961
+ `${PKG_NAME}@${version}`,
962
+ bin,
963
+ ...args
964
+ ];
965
+ }
966
+ function pinnedNpxCommand(bin, args = [], options = {}) {
967
+ return ["npx", ...pinnedNpxArgs(bin, args, options)].map(shellWord).join(" ");
968
+ }
969
+ function pinnedHookCommand(bin, args = "") {
970
+ const suffix = args ? ` ${args}` : "";
971
+ const fallback = `${pinnedNpxCommand(bin)}${suffix}`;
972
+ const file = binFile(bin);
973
+ if (!file) return fallback;
974
+ return `if [ -x ${shellQuote(process.execPath)} ] && [ -f ${shellQuote(file)} ]; then ${shellQuote(process.execPath)} ${shellQuote(file)}${suffix}; else ${fallback}; fi`;
975
+ }
976
+ var STABLE_HOOK_ARGUMENTS_RE = /^[-A-Za-z0-9_ ]*$/u;
977
+ var STABLE_HOOK_BIN_RE = /^[A-Za-z0-9][A-Za-z0-9-]*$/u;
978
+ var PRIM_CONFIG_SHELL_RESOLVER = [
979
+ 'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
980
+ 'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
981
+ 'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
982
+ '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; ',
983
+ "fi; fi; "
984
+ ].join("");
985
+ function stableHookCommand(bin, args = "") {
986
+ if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
987
+ throw new Error("invalid stable hook command");
988
+ }
989
+ const resolver = [
990
+ // #242 and earlier identify managed commands by this package marker. Keep
991
+ // it as inert data during the rolling window so an older uninstall or
992
+ // reinstall can remove the stable entry without invoking npm or PATH.
993
+ `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
994
+ PRIM_CONFIG_SHELL_RESOLVER,
995
+ `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
996
+ 'exec "$prim_launcher" "$@"'
997
+ ].join("");
998
+ const suffix = args ? ` ${args}` : "";
999
+ return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
1000
+ }
1001
+ function detachedHookShimCommand(bin, args = "") {
1002
+ return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
1003
+ }
1004
+ function commandMatchesBin(command, bin) {
1005
+ if (!command) {
1006
+ return false;
1007
+ }
1008
+ const c = command.trim();
1009
+ if (c === bin || c.startsWith(`${bin} `)) {
1010
+ return true;
1011
+ }
1012
+ const exactBin = new RegExp(`(?:^|\\s)${bin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s|;|$)`);
1013
+ return c.includes(`command -v ${bin} `) || c.includes(`-p ${PKG_NAME}@`) && exactBin.test(c) || c.includes(STABLE_HOOK_LAUNCHER_NAME) && exactBin.test(c);
1014
+ }
1015
+ function exactPinnedNpxVersion(command, bin) {
1016
+ const escapedBin = bin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1017
+ const shellQuoted = `'(?:[^']|'"'"')*'`;
1018
+ const safeArgs = "(?: [A-Za-z0-9_@%+=:,./-]+)*";
1019
+ const direct = new RegExp(
1020
+ `^npx --yes --ignore-scripts -p @primitive\\.ai/prim@(?<version>[0-9A-Za-z.+-]+) ${escapedBin}${safeArgs}$`,
1021
+ "u"
1022
+ ).exec(command);
1023
+ const wrapped = new RegExp(
1024
+ `^if \\[ -x (?<node>${shellQuoted}) \\] && \\[ -f (?<entry>${shellQuoted}) \\]; then \\k<node> \\k<entry>(?<args>${safeArgs}); else npx --yes --ignore-scripts -p @primitive\\.ai/prim@(?<version>[0-9A-Za-z.+-]+) ${escapedBin}\\k<args>; fi$`,
1025
+ "u"
1026
+ ).exec(command);
1027
+ const version = direct?.groups?.version ?? wrapped?.groups?.version;
1028
+ return version && compareSemver(version, version) !== void 0 ? version : void 0;
1029
+ }
1030
+ function hookCommandResolution(command, bin) {
1031
+ const trimmed = command?.trim();
1032
+ if (!trimmed || !commandMatchesBin(trimmed, bin)) return void 0;
1033
+ if (trimmed.includes(STABLE_HOOK_LAUNCHER_NAME)) return { kind: "stable_launcher" };
1034
+ const version = exactPinnedNpxVersion(trimmed, bin);
1035
+ return version ? { kind: "exact_npx_fallback", version } : { kind: "legacy_path" };
1036
+ }
1037
+ function hookCommandResolutions(commands, bins) {
1038
+ const resolutions = [];
1039
+ for (const command of commands) {
1040
+ for (const bin of bins) {
1041
+ const resolution = hookCommandResolution(command, bin);
1042
+ if (resolution) resolutions.push(resolution);
1043
+ }
1044
+ }
1045
+ return resolutions;
1046
+ }
1047
+
503
1048
  // src/lib/atomic-file.ts
504
1049
  import { randomUUID } from "crypto";
505
1050
  import {
@@ -513,7 +1058,7 @@ import {
513
1058
  rmSync,
514
1059
  writeFileSync
515
1060
  } from "fs";
516
- import { dirname } from "path";
1061
+ import { dirname as dirname3 } from "path";
517
1062
  var DEFAULT_FILE_MODE = 438;
518
1063
  function syncDirectory(path) {
519
1064
  const fd = openSync(path, constants.O_RDONLY);
@@ -536,14 +1081,14 @@ function syncCreatedParentChain(firstCreatedParent, parent) {
536
1081
  let current = parent;
537
1082
  while (current !== firstCreatedParent) {
538
1083
  createdDirectories.push(current);
539
- const next = dirname(current);
1084
+ const next = dirname3(current);
540
1085
  if (next === current) {
541
1086
  throw new Error("recursive mkdir returned a path outside the target parent chain");
542
1087
  }
543
1088
  current = next;
544
1089
  }
545
1090
  createdDirectories.push(firstCreatedParent);
546
- syncDirectory(dirname(firstCreatedParent));
1091
+ syncDirectory(dirname3(firstCreatedParent));
547
1092
  for (const directory of createdDirectories.reverse().slice(0, -1)) {
548
1093
  syncDirectory(directory);
549
1094
  }
@@ -555,7 +1100,7 @@ function ensureDurableDirectory(path, mode) {
555
1100
  }
556
1101
  }
557
1102
  function atomicWriteFile(target, content, options = {}) {
558
- const parent = dirname(target);
1103
+ const parent = dirname3(target);
559
1104
  if (options.ensureParent) {
560
1105
  ensureDurableDirectory(parent);
561
1106
  }
@@ -599,19 +1144,19 @@ function processIsAlive(pid, probe = process.kill) {
599
1144
 
600
1145
  // src/lib/file-lock.ts
601
1146
  import { randomBytes } from "crypto";
602
- import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
603
- import { dirname as dirname2, join as join3 } from "path";
1147
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync4, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
1148
+ import { dirname as dirname4, join as join5 } from "path";
604
1149
  var DEFAULT_TIMEOUT_MS = 3e4;
605
1150
  var DEFAULT_POLL_MS = 50;
606
1151
  var DEFAULT_INIT_GRACE_MS = 2e3;
607
1152
  var DIRECTORY_MODE = 448;
608
1153
  var FILE_MODE = 384;
609
1154
  function ownerPath(lockDir) {
610
- return join3(lockDir, "owner.json");
1155
+ return join5(lockDir, "owner.json");
611
1156
  }
612
1157
  function readOwner(lockDir) {
613
1158
  try {
614
- const owner = JSON.parse(readFileSync2(ownerPath(lockDir), "utf8"));
1159
+ const owner = JSON.parse(readFileSync4(ownerPath(lockDir), "utf8"));
615
1160
  if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
616
1161
  return null;
617
1162
  }
@@ -678,14 +1223,14 @@ function throwIfAborted(signal) {
678
1223
  }
679
1224
  async function defaultSleep2(ms, signal) {
680
1225
  if (!signal) {
681
- await new Promise((resolve) => setTimeout(resolve, ms));
1226
+ await new Promise((resolve2) => setTimeout(resolve2, ms));
682
1227
  return;
683
1228
  }
684
1229
  throwIfAborted(signal);
685
- await new Promise((resolve, reject) => {
1230
+ await new Promise((resolve2, reject) => {
686
1231
  const timer = setTimeout(() => {
687
1232
  signal.removeEventListener("abort", onAbort);
688
- resolve();
1233
+ resolve2();
689
1234
  }, ms);
690
1235
  const onAbort = () => {
691
1236
  clearTimeout(timer);
@@ -699,7 +1244,7 @@ function defaultSleepSync(ms) {
699
1244
  Atomics.wait(syncSleeper, 0, 0, ms);
700
1245
  }
701
1246
  function withFileLockSync(lockDir, operation, options = {}) {
702
- mkdirSync2(dirname2(lockDir), { recursive: true, mode: DIRECTORY_MODE });
1247
+ mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
703
1248
  const nowMs = options.nowMs ?? Date.now;
704
1249
  const alive = options.processAlive ?? processIsAlive;
705
1250
  const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -723,7 +1268,7 @@ function withFileLockSync(lockDir, operation, options = {}) {
723
1268
  }
724
1269
  }
725
1270
  async function withFileLock(lockDir, operation, options = {}) {
726
- mkdirSync2(dirname2(lockDir), { recursive: true, mode: DIRECTORY_MODE });
1271
+ mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
727
1272
  const nowMs = options.nowMs ?? Date.now;
728
1273
  const alive = options.processAlive ?? processIsAlive;
729
1274
  const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -782,11 +1327,46 @@ export {
782
1327
  decodeJwtPayload,
783
1328
  jwtExpiresAt,
784
1329
  jwtOrganizationId,
1330
+ gitToplevel,
1331
+ mainWorktreeRoot,
1332
+ currentBranch,
1333
+ githubRepositoryFullName,
1334
+ canonicalGitRoot,
1335
+ relatedWorktreeTarget,
1336
+ resolveRepositoryContext,
1337
+ canonicalRepositoryPath,
1338
+ repoActiveFlag,
1339
+ isRepoActive,
1340
+ setRepoActive,
1341
+ isValidRepoSyncId,
1342
+ localGitConfigValue,
1343
+ setLocalGitConfigValue,
1344
+ repoSyncId,
1345
+ setRepoSyncId,
1346
+ setRepositoryBindingState,
1347
+ repositoryBindingState,
1348
+ isRepoActiveForCapture,
1349
+ decisionIngestionStatus,
785
1350
  syncDirectory,
786
1351
  syncFile,
787
1352
  ensureDurableDirectory,
788
1353
  atomicWriteFile,
789
1354
  processIsAlive,
790
1355
  withFileLockSync,
791
- withFileLock
1356
+ withFileLock,
1357
+ compareSemver,
1358
+ STABLE_HOOK_LAUNCHER_NAME,
1359
+ binFile,
1360
+ packageVersion,
1361
+ packageRoot,
1362
+ shellQuote,
1363
+ pinnedNpxArgs,
1364
+ pinnedNpxCommand,
1365
+ pinnedHookCommand,
1366
+ PRIM_CONFIG_SHELL_RESOLVER,
1367
+ stableHookCommand,
1368
+ detachedHookShimCommand,
1369
+ commandMatchesBin,
1370
+ hookCommandResolution,
1371
+ hookCommandResolutions
792
1372
  };