@primitive.ai/prim 0.1.0-alpha.120 → 0.1.0-alpha.121

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 (46) hide show
  1. package/README.md +19 -9
  2. package/SKILL.md +7 -2
  3. package/dist/{chunk-HXICZG5J.js → chunk-2DNC2MUN.js} +4 -4
  4. package/dist/{chunk-NQFRQ56V.js → chunk-2PFJJO2M.js} +2 -2
  5. package/dist/{chunk-P2O7NLVN.js → chunk-4GYJHN26.js} +117 -18
  6. package/dist/{chunk-5BQ2NEMP.js → chunk-6DEROXLM.js} +2 -2
  7. package/dist/{chunk-CCGFRNAA.js → chunk-7LXRFXZG.js} +248 -127
  8. package/dist/{chunk-MWNRXAEB.js → chunk-AKGRY7OU.js} +1 -1
  9. package/dist/{chunk-L52OD62C.js → chunk-BHT6X3T5.js} +14 -8
  10. package/dist/{chunk-D235RJNO.js → chunk-DQ4I3FLF.js} +3 -3
  11. package/dist/{chunk-VOC4KOOP.js → chunk-DVHD6LBQ.js} +2 -2
  12. package/dist/{chunk-TC4FTRYO.js → chunk-HG7FJK7R.js} +2 -2
  13. package/dist/{chunk-GYQOZGGF.js → chunk-JXRJLHE4.js} +2 -2
  14. package/dist/{chunk-2AKDX4RU.js → chunk-JZC2LHS6.js} +1 -1
  15. package/dist/{chunk-YTF6OCF3.js → chunk-LQLP26RL.js} +5 -5
  16. package/dist/{chunk-EYBE724K.js → chunk-M4NZJCPQ.js} +4 -4
  17. package/dist/{chunk-R2NUH4B7.js → chunk-MRDY7VQP.js} +2 -2
  18. package/dist/{chunk-SLDZJD6Q.js → chunk-NMZSCSMY.js} +1 -1
  19. package/dist/{chunk-A6M2M5A2.js → chunk-NQZLXYTW.js} +1 -1
  20. package/dist/{chunk-LTTF4MBE.js → chunk-OXW6PSPT.js} +2 -2
  21. package/dist/{chunk-U67RBNIZ.js → chunk-S3ZIMGXV.js} +1 -1
  22. package/dist/{chunk-LBCPRHNG.js → chunk-WN7OURQ3.js} +1 -1
  23. package/dist/daemon/server.js +78 -16
  24. package/dist/hook-runtime/daemon/server.js +78 -16
  25. package/dist/hook-runtime/hooks/post-commit.js +88 -26
  26. package/dist/hook-runtime/hooks/post-rewrite.js +82 -20
  27. package/dist/hook-runtime/hooks/post-tool-use.js +82 -20
  28. package/dist/hook-runtime/hooks/pre-commit.js +9 -5
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +12 -8
  30. package/dist/hook-runtime/hooks/prim-hook.js +85 -23
  31. package/dist/hook-runtime/hooks/session-end.js +75 -13
  32. package/dist/hook-runtime/hooks/session-start.js +247 -176
  33. package/dist/hook-runtime/index.js +1147 -692
  34. package/dist/hook-runtime/statusline-main.js +76 -14
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +15 -15
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +9 -9
  40. package/dist/hooks/prim-hook.js +17 -17
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +11 -11
  43. package/dist/index.js +349 -98
  44. package/dist/statusline-main.js +76 -14
  45. package/package.json +3 -2
  46. package/skills/prim-welcome/SKILL.md +197 -0
@@ -4964,7 +4964,7 @@ var require_rc = __commonJS({
4964
4964
  "node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js"(exports, module) {
4965
4965
  "use strict";
4966
4966
  var cc = require_utils();
4967
- var join39 = __require("path").join;
4967
+ var join41 = __require("path").join;
4968
4968
  var deepExtend = require_deep_extend();
4969
4969
  var etc = "/etc";
4970
4970
  var win = process.platform === "win32";
@@ -4989,15 +4989,15 @@ var require_rc = __commonJS({
4989
4989
  }
4990
4990
  if (!win)
4991
4991
  [
4992
- join39(etc, name2, "config"),
4993
- join39(etc, name2 + "rc")
4992
+ join41(etc, name2, "config"),
4993
+ join41(etc, name2 + "rc")
4994
4994
  ].forEach(addConfigFile);
4995
4995
  if (home)
4996
4996
  [
4997
- join39(home, ".config", name2, "config"),
4998
- join39(home, ".config", name2),
4999
- join39(home, "." + name2, "config"),
5000
- join39(home, "." + name2 + "rc")
4997
+ join41(home, ".config", name2, "config"),
4998
+ join41(home, ".config", name2),
4999
+ join41(home, "." + name2, "config"),
5000
+ join41(home, "." + name2 + "rc")
5001
5001
  ].forEach(addConfigFile);
5002
5002
  addConfigFile(cc.find("." + name2 + "rc"));
5003
5003
  if (env4.config) addConfigFile(env4.config);
@@ -6341,11 +6341,11 @@ var require_util = __commonJS({
6341
6341
  if (files.includes("node_modules") || files.includes("package.json") || files.includes("package.json5") || files.includes("package.yaml") || files.includes("pnpm-workspace.yaml")) {
6342
6342
  return name3;
6343
6343
  }
6344
- const dirname23 = path9.dirname(name3);
6345
- if (dirname23 === name3) {
6344
+ const dirname24 = path9.dirname(name3);
6345
+ if (dirname24 === name3) {
6346
6346
  return original;
6347
6347
  }
6348
- return find(dirname23, original);
6348
+ return find(dirname24, original);
6349
6349
  } catch (error) {
6350
6350
  if (name3 === original) {
6351
6351
  if (error.code === "ENOENT") {
@@ -11144,7 +11144,7 @@ var require_websocket = __commonJS({
11144
11144
  var http = __require("http");
11145
11145
  var net = __require("net");
11146
11146
  var tls = __require("tls");
11147
- var { randomBytes: randomBytes8, createHash: createHash16 } = __require("crypto");
11147
+ var { randomBytes: randomBytes8, createHash: createHash17 } = __require("crypto");
11148
11148
  var { Duplex, Readable: Readable2 } = __require("stream");
11149
11149
  var { URL: URL2 } = __require("url");
11150
11150
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -11812,8 +11812,8 @@ var require_websocket = __commonJS({
11812
11812
  abortHandshake(websocket, socket, "Invalid Upgrade header");
11813
11813
  return;
11814
11814
  }
11815
- const digest2 = createHash16("sha1").update(key + GUID).digest("base64");
11816
- if (res.headers["sec-websocket-accept"] !== digest2) {
11815
+ const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
11816
+ if (res.headers["sec-websocket-accept"] !== digest3) {
11817
11817
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
11818
11818
  return;
11819
11819
  }
@@ -12181,7 +12181,7 @@ var require_websocket_server = __commonJS({
12181
12181
  var EventEmitter = __require("events");
12182
12182
  var http = __require("http");
12183
12183
  var { Duplex } = __require("stream");
12184
- var { createHash: createHash16 } = __require("crypto");
12184
+ var { createHash: createHash17 } = __require("crypto");
12185
12185
  var extension2 = require_extension();
12186
12186
  var PerMessageDeflate2 = require_permessage_deflate();
12187
12187
  var subprotocol2 = require_subprotocol();
@@ -12488,12 +12488,12 @@ var require_websocket_server = __commonJS({
12488
12488
  );
12489
12489
  }
12490
12490
  if (this._state > RUNNING) return abortHandshake(socket, 503);
12491
- const digest2 = createHash16("sha1").update(key + GUID).digest("base64");
12491
+ const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
12492
12492
  const headers = [
12493
12493
  "HTTP/1.1 101 Switching Protocols",
12494
12494
  "Upgrade: websocket",
12495
12495
  "Connection: Upgrade",
12496
- `Sec-WebSocket-Accept: ${digest2}`
12496
+ `Sec-WebSocket-Accept: ${digest3}`
12497
12497
  ];
12498
12498
  const ws = new this.options.WebSocket(null, void 0, this.options);
12499
12499
  if (protocols.size) {
@@ -12576,8 +12576,8 @@ var require_websocket_server = __commonJS({
12576
12576
  });
12577
12577
 
12578
12578
  // src/index.ts
12579
- import { readFileSync as readFileSync30 } from "fs";
12580
- import { dirname as dirname22, resolve as resolve15 } from "path";
12579
+ import { readFileSync as readFileSync31 } from "fs";
12580
+ import { dirname as dirname23, resolve as resolve16 } from "path";
12581
12581
  import { fileURLToPath as fileURLToPath8 } from "url";
12582
12582
 
12583
12583
  // node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
@@ -12678,7 +12678,7 @@ var retryifyAsync = (fn, options) => {
12678
12678
  throw error;
12679
12679
  const delay3 = Math.round(interval * Math.random());
12680
12680
  if (delay3 > 0) {
12681
- const delayPromise = new Promise((resolve16) => setTimeout(resolve16, delay3));
12681
+ const delayPromise = new Promise((resolve17) => setTimeout(resolve17, delay3));
12682
12682
  return delayPromise.then(() => attempt.apply(void 0, args));
12683
12683
  } else {
12684
12684
  return attempt.apply(void 0, args);
@@ -14244,14 +14244,14 @@ var TimeoutError = class extends Error {
14244
14244
 
14245
14245
  // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/timeout.js
14246
14246
  async function timeout(request2, init, abortController, options) {
14247
- return new Promise((resolve16, reject) => {
14247
+ return new Promise((resolve17, reject) => {
14248
14248
  const timeoutId = setTimeout(() => {
14249
14249
  if (abortController) {
14250
14250
  abortController.abort();
14251
14251
  }
14252
14252
  reject(new TimeoutError(request2));
14253
14253
  }, options.timeout);
14254
- void options.fetch(request2, init).then(resolve16).catch(reject).then(() => {
14254
+ void options.fetch(request2, init).then(resolve17).catch(reject).then(() => {
14255
14255
  clearTimeout(timeoutId);
14256
14256
  });
14257
14257
  });
@@ -14259,7 +14259,7 @@ async function timeout(request2, init, abortController, options) {
14259
14259
 
14260
14260
  // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/delay.js
14261
14261
  async function delay(ms, { signal }) {
14262
- return new Promise((resolve16, reject) => {
14262
+ return new Promise((resolve17, reject) => {
14263
14263
  if (signal) {
14264
14264
  signal.throwIfAborted();
14265
14265
  signal.addEventListener("abort", abortHandler, { once: true });
@@ -14270,7 +14270,7 @@ async function delay(ms, { signal }) {
14270
14270
  }
14271
14271
  const timeoutId = setTimeout(() => {
14272
14272
  signal?.removeEventListener("abort", abortHandler);
14273
- resolve16();
14273
+ resolve17();
14274
14274
  }, ms);
14275
14275
  });
14276
14276
  }
@@ -16240,7 +16240,7 @@ function providerError(value) {
16240
16240
  return exactString(error, "error", MAX_USER_CODE_LENGTH);
16241
16241
  }
16242
16242
  async function defaultSleep(milliseconds, signal) {
16243
- await new Promise((resolve16, reject) => {
16243
+ await new Promise((resolve17, reject) => {
16244
16244
  if (signal.aborted) {
16245
16245
  reject(signal.reason);
16246
16246
  return;
@@ -16251,7 +16251,7 @@ async function defaultSleep(milliseconds, signal) {
16251
16251
  };
16252
16252
  const timer = setTimeout(() => {
16253
16253
  signal.removeEventListener("abort", abort);
16254
- resolve16();
16254
+ resolve17();
16255
16255
  }, milliseconds);
16256
16256
  signal.addEventListener("abort", abort, { once: true });
16257
16257
  });
@@ -16500,7 +16500,7 @@ function daemonRequest(method, params = {}, opts = {}) {
16500
16500
  ...caller ? { caller } : {}
16501
16501
  };
16502
16502
  const timeoutMs2 = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
16503
- return new Promise((resolve16) => {
16503
+ return new Promise((resolve17) => {
16504
16504
  let settled = false;
16505
16505
  let socket;
16506
16506
  let buffer = Buffer.alloc(0);
@@ -16515,7 +16515,7 @@ function daemonRequest(method, params = {}, opts = {}) {
16515
16515
  } catch {
16516
16516
  }
16517
16517
  }
16518
- resolve16(value);
16518
+ resolve17(value);
16519
16519
  };
16520
16520
  const timer = setTimeout(() => settle(null), timeoutMs2);
16521
16521
  timer.unref();
@@ -16581,26 +16581,116 @@ async function daemonIsLive(timeoutMs2 = DEFAULT_TIMEOUT_MS) {
16581
16581
  }
16582
16582
 
16583
16583
  // src/lib/activation.ts
16584
- import { execFileSync as execFileSync2 } from "child_process";
16584
+ import { execFileSync as execFileSync3 } from "child_process";
16585
16585
  import { existsSync, readFileSync as readFileSync2 } from "fs";
16586
16586
  import { homedir as homedir2 } from "os";
16587
16587
  import { join as join4 } from "path";
16588
16588
 
16589
- // src/lib/git.ts
16589
+ // src/lib/demo-pause.ts
16590
16590
  import { execFileSync } from "child_process";
16591
+ var DEMO_PAUSE_MS = 30 * 6e4;
16592
+ var PAUSE_KEY = "prim.demoPause";
16593
+ var GIT_TIMEOUT_MS = 1e3;
16594
+ function git(cwd, args) {
16595
+ try {
16596
+ return execFileSync("git", args, {
16597
+ cwd,
16598
+ encoding: "utf-8",
16599
+ stdio: ["ignore", "pipe", "ignore"],
16600
+ timeout: GIT_TIMEOUT_MS
16601
+ });
16602
+ } catch {
16603
+ return void 0;
16604
+ }
16605
+ }
16606
+ function setLocal(cwd, key, value) {
16607
+ try {
16608
+ execFileSync(
16609
+ "git",
16610
+ value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
16611
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
16612
+ );
16613
+ } catch (error) {
16614
+ if (value !== null || error.status !== 5) throw error;
16615
+ }
16616
+ }
16617
+ function parsePause(value) {
16618
+ const [runId = "", until, previous, state] = value.trim().split(" ");
16619
+ const flag = previous === "true" || previous === "false" ? previous : "unset";
16620
+ return { runId, until: Number(until) || 0, previous: flag, ending: state !== "active" };
16621
+ }
16622
+ function writePause(cwd, pause) {
16623
+ setLocal(
16624
+ cwd,
16625
+ PAUSE_KEY,
16626
+ `${pause.runId} ${pause.until} ${pause.previous} ${pause.ending ? "ending" : "active"}`
16627
+ );
16628
+ }
16629
+ function readCaptureConfig(cwd) {
16630
+ let active;
16631
+ let pause;
16632
+ const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
16633
+ for (const line of out.split("\n")) {
16634
+ const space3 = line.indexOf(" ");
16635
+ const key = line.slice(0, space3).toLowerCase();
16636
+ const value = line.slice(space3 + 1);
16637
+ if (key === "prim.active") active = value === "true" || value === "false" ? value : void 0;
16638
+ if (key === "prim.demopause") pause = parsePause(value);
16639
+ }
16640
+ return { active, pause };
16641
+ }
16642
+ function readDemoPause(cwd) {
16643
+ const value = git(cwd, ["config", "--local", "--get", PAUSE_KEY]);
16644
+ return value === void 0 ? void 0 : parsePause(value);
16645
+ }
16646
+ function pauseCaptureForDemo(cwd, runId, now = Date.now()) {
16647
+ const local = git(cwd, ["config", "--local", "--get", "prim.active"])?.trim();
16648
+ const previous = readDemoPause(cwd)?.previous ?? (local === "true" || local === "false" ? local : "unset");
16649
+ writePause(cwd, { runId, until: now + DEMO_PAUSE_MS, previous, ending: false });
16650
+ setLocal(cwd, "prim.active", "false");
16651
+ }
16652
+ function extendDemoPause(cwd, runId, now = Date.now()) {
16653
+ const pause = readDemoPause(cwd);
16654
+ if (pause?.runId === runId) writePause(cwd, { ...pause, until: now + DEMO_PAUSE_MS });
16655
+ }
16656
+ function endDemoPause(cwd, runId, now = Date.now()) {
16657
+ const pause = readDemoPause(cwd);
16658
+ if (pause?.runId === runId)
16659
+ writePause(cwd, { ...pause, until: now + DEMO_PAUSE_MS, ending: true });
16660
+ }
16661
+ function resumeCapture(cwd, pause) {
16662
+ setLocal(cwd, "prim.active", pause.previous === "unset" ? null : pause.previous);
16663
+ setLocal(cwd, PAUSE_KEY, null);
16664
+ }
16665
+ function clearDemoPause(cwd) {
16666
+ setLocal(cwd, PAUSE_KEY, null);
16667
+ }
16668
+ function healDemoPause(cwd, pause, options = {}) {
16669
+ if (pause.until > (options.now ?? Date.now()) && !(pause.ending && options.userPrompt))
16670
+ return false;
16671
+ try {
16672
+ resumeCapture(cwd, pause);
16673
+ return true;
16674
+ } catch {
16675
+ return false;
16676
+ }
16677
+ }
16678
+
16679
+ // src/lib/git.ts
16680
+ import { execFileSync as execFileSync2 } from "child_process";
16591
16681
  import { createHash as createHash3 } from "crypto";
16592
16682
  import { lstatSync, realpathSync } from "fs";
16593
16683
  import { basename, dirname, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
16594
- var GIT_TIMEOUT_MS = 1e3;
16684
+ var GIT_TIMEOUT_MS2 = 1e3;
16595
16685
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
16596
16686
  var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
16597
16687
  function gitToplevel(cwd) {
16598
16688
  try {
16599
- return execFileSync("git", ["rev-parse", "--show-toplevel"], {
16689
+ return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
16600
16690
  cwd,
16601
16691
  encoding: "utf-8",
16602
16692
  stdio: ["ignore", "pipe", "ignore"],
16603
- timeout: GIT_TIMEOUT_MS
16693
+ timeout: GIT_TIMEOUT_MS2
16604
16694
  }).trim();
16605
16695
  } catch {
16606
16696
  return null;
@@ -16608,14 +16698,14 @@ function gitToplevel(cwd) {
16608
16698
  }
16609
16699
  function mainWorktreeRoot(cwd) {
16610
16700
  try {
16611
- const [gitDir, commonDir] = execFileSync(
16701
+ const [gitDir, commonDir] = execFileSync2(
16612
16702
  "git",
16613
16703
  ["rev-parse", "--git-dir", "--git-common-dir"],
16614
16704
  {
16615
16705
  cwd,
16616
16706
  encoding: "utf-8",
16617
16707
  stdio: ["ignore", "pipe", "ignore"],
16618
- timeout: GIT_TIMEOUT_MS
16708
+ timeout: GIT_TIMEOUT_MS2
16619
16709
  }
16620
16710
  ).trim().split("\n").map((value) => resolve(cwd ?? process.cwd(), value));
16621
16711
  if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
@@ -16626,11 +16716,11 @@ function mainWorktreeRoot(cwd) {
16626
16716
  }
16627
16717
  function gitValue(cwd, args) {
16628
16718
  try {
16629
- const value = execFileSync("git", args, {
16719
+ const value = execFileSync2("git", args, {
16630
16720
  cwd,
16631
16721
  encoding: "utf-8",
16632
16722
  stdio: ["ignore", "pipe", "ignore"],
16633
- timeout: GIT_TIMEOUT_MS
16723
+ timeout: GIT_TIMEOUT_MS2
16634
16724
  }).trim();
16635
16725
  return value || void 0;
16636
16726
  } catch {
@@ -16742,17 +16832,17 @@ var PRIM_ACTIVE_KEY = "prim.active";
16742
16832
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
16743
16833
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
16744
16834
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
16745
- var GIT_TIMEOUT_MS2 = 1e3;
16835
+ var GIT_TIMEOUT_MS3 = 1e3;
16746
16836
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
16747
16837
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
16748
16838
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
16749
16839
  function repoActiveFlag(cwd, strict = false) {
16750
16840
  try {
16751
- const value = execFileSync2("git", ["config", "--get", PRIM_ACTIVE_KEY], {
16841
+ const value = execFileSync3("git", ["config", "--get", PRIM_ACTIVE_KEY], {
16752
16842
  cwd,
16753
16843
  encoding: "utf-8",
16754
16844
  stdio: ["ignore", "pipe", "ignore"],
16755
- timeout: GIT_TIMEOUT_MS2
16845
+ timeout: GIT_TIMEOUT_MS3
16756
16846
  }).trim();
16757
16847
  if (value === "true") return "true";
16758
16848
  if (value === "false") return "false";
@@ -16765,10 +16855,10 @@ function repoActiveFlag(cwd, strict = false) {
16765
16855
  }
16766
16856
  }
16767
16857
  function setRepoActive(cwd, active) {
16768
- execFileSync2("git", ["config", "--local", PRIM_ACTIVE_KEY, active ? "true" : "false"], {
16858
+ execFileSync3("git", ["config", "--local", PRIM_ACTIVE_KEY, active ? "true" : "false"], {
16769
16859
  cwd,
16770
16860
  stdio: ["ignore", "ignore", "pipe"],
16771
- timeout: GIT_TIMEOUT_MS2
16861
+ timeout: GIT_TIMEOUT_MS3
16772
16862
  });
16773
16863
  }
16774
16864
  function isValidRepoSyncId(value) {
@@ -16776,11 +16866,11 @@ function isValidRepoSyncId(value) {
16776
16866
  }
16777
16867
  function localGitConfigValue(cwd, key) {
16778
16868
  try {
16779
- const value = execFileSync2("git", ["config", "--local", "--get", key], {
16869
+ const value = execFileSync3("git", ["config", "--local", "--get", key], {
16780
16870
  cwd,
16781
16871
  encoding: "utf-8",
16782
16872
  stdio: ["ignore", "pipe", "ignore"],
16783
- timeout: GIT_TIMEOUT_MS2
16873
+ timeout: GIT_TIMEOUT_MS3
16784
16874
  }).trim();
16785
16875
  return value || void 0;
16786
16876
  } catch {
@@ -16788,10 +16878,10 @@ function localGitConfigValue(cwd, key) {
16788
16878
  }
16789
16879
  }
16790
16880
  function setLocalGitConfigValue(cwd, key, value) {
16791
- execFileSync2("git", ["config", "--local", key, value], {
16881
+ execFileSync3("git", ["config", "--local", key, value], {
16792
16882
  cwd,
16793
16883
  stdio: ["ignore", "ignore", "pipe"],
16794
- timeout: GIT_TIMEOUT_MS2
16884
+ timeout: GIT_TIMEOUT_MS3
16795
16885
  });
16796
16886
  }
16797
16887
  function repoSyncId(cwd) {
@@ -16804,25 +16894,25 @@ function setRepoSyncId(cwd, value, repositoryFullName) {
16804
16894
  if (!isValidRepoSyncId(value)) {
16805
16895
  throw new Error("invalid repository binding returned by server");
16806
16896
  }
16807
- execFileSync2("git", ["config", "--local", PRIM_REPO_SYNC_ID_KEY, value], {
16897
+ execFileSync3("git", ["config", "--local", PRIM_REPO_SYNC_ID_KEY, value], {
16808
16898
  cwd,
16809
16899
  stdio: ["ignore", "ignore", "pipe"],
16810
- timeout: GIT_TIMEOUT_MS2
16900
+ timeout: GIT_TIMEOUT_MS3
16811
16901
  });
16812
- execFileSync2("git", ["config", "--local", PRIM_REPO_SYNC_REPOSITORY_KEY, repositoryFullName], {
16902
+ execFileSync3("git", ["config", "--local", PRIM_REPO_SYNC_REPOSITORY_KEY, repositoryFullName], {
16813
16903
  cwd,
16814
16904
  stdio: ["ignore", "ignore", "pipe"],
16815
- timeout: GIT_TIMEOUT_MS2
16905
+ timeout: GIT_TIMEOUT_MS3
16816
16906
  });
16817
16907
  }
16818
16908
  function setRepositoryBindingState(cwd, state) {
16819
16909
  if (state !== "connected" && state !== "unbound" && state !== "invalid") {
16820
16910
  throw new Error("invalid repository binding state");
16821
16911
  }
16822
- execFileSync2("git", ["config", "--local", PRIM_REPO_BINDING_STATE_KEY, state], {
16912
+ execFileSync3("git", ["config", "--local", PRIM_REPO_BINDING_STATE_KEY, state], {
16823
16913
  cwd,
16824
16914
  stdio: ["ignore", "ignore", "pipe"],
16825
- timeout: GIT_TIMEOUT_MS2
16915
+ timeout: GIT_TIMEOUT_MS3
16826
16916
  });
16827
16917
  }
16828
16918
  function repositoryBindingState(cwd) {
@@ -16849,8 +16939,9 @@ function hasProjectPrimInstall(cwd) {
16849
16939
  }
16850
16940
  return false;
16851
16941
  }
16852
- function isRepoActiveForCapture(cwd) {
16853
- const flag = repoActiveFlag(cwd);
16942
+ function isRepoActiveForCapture(cwd, options = {}) {
16943
+ let { active: flag, pause } = readCaptureConfig(cwd);
16944
+ if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
16854
16945
  if (flag === "true") return true;
16855
16946
  if (flag === "false") return false;
16856
16947
  return hasProjectPrimInstall(cwd);
@@ -17121,14 +17212,14 @@ function throwIfAborted(signal) {
17121
17212
  }
17122
17213
  async function defaultSleep2(ms, signal) {
17123
17214
  if (!signal) {
17124
- await new Promise((resolve16) => setTimeout(resolve16, ms));
17215
+ await new Promise((resolve17) => setTimeout(resolve17, ms));
17125
17216
  return;
17126
17217
  }
17127
17218
  throwIfAborted(signal);
17128
- await new Promise((resolve16, reject) => {
17219
+ await new Promise((resolve17, reject) => {
17129
17220
  const timer = setTimeout(() => {
17130
17221
  signal.removeEventListener("abort", onAbort);
17131
- resolve16();
17222
+ resolve17();
17132
17223
  }, ms);
17133
17224
  const onAbort = () => {
17134
17225
  clearTimeout(timer);
@@ -17327,10 +17418,10 @@ function locateRoot() {
17327
17418
  }
17328
17419
  let dir = dirname4(fileURLToPath3(import.meta.url));
17329
17420
  for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
17330
- const manifestPath = join7(dir, "package.json");
17331
- if (existsSync3(manifestPath)) {
17421
+ const manifestPath2 = join7(dir, "package.json");
17422
+ if (existsSync3(manifestPath2)) {
17332
17423
  try {
17333
- const manifest = JSON.parse(readFileSync5(manifestPath, "utf-8"));
17424
+ const manifest = JSON.parse(readFileSync5(manifestPath2, "utf-8"));
17334
17425
  if (manifest.name === PKG_NAME && manifest.bin) {
17335
17426
  resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
17336
17427
  return resolvedRoot;
@@ -40483,12 +40574,12 @@ function scheduleCollectScopeRefresh(cwd, collectScopeVersion, dependencies = de
40483
40574
  }
40484
40575
 
40485
40576
  // src/lib/commit-heartbeat.ts
40486
- import { execFileSync as execFileSync3 } from "child_process";
40577
+ import { execFileSync as execFileSync4 } from "child_process";
40487
40578
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, readdirSync, unlinkSync } from "fs";
40488
40579
  import { dirname as dirname6, join as join9, resolve as resolve3 } from "path";
40489
40580
  var FIRED_DIR = "prim/post-commit-fired";
40490
40581
  var WIRED_PATH = "prim/git-hooks-wired";
40491
- var GIT_TIMEOUT_MS3 = 1e3;
40582
+ var GIT_TIMEOUT_MS4 = 1e3;
40492
40583
  var MAX_STAMP_BYTES = 1024;
40493
40584
  var REFLOG_SCAN_LIMIT = 50;
40494
40585
  var FULL_SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u;
@@ -40497,21 +40588,21 @@ var COMMIT_SUBJECT_RE = /^commit(?: \([^)]*\))?:/u;
40497
40588
  var REFLOG_RESOLUTION_MS = 1e3;
40498
40589
  var POST_COMMIT_GRACE_MS = 6e4;
40499
40590
  function commonPath(cwd, relative5) {
40500
- const value = execFileSync3("git", ["rev-parse", "--git-common-dir"], {
40591
+ const value = execFileSync4("git", ["rev-parse", "--git-common-dir"], {
40501
40592
  cwd,
40502
40593
  encoding: "utf8",
40503
40594
  stdio: ["ignore", "pipe", "ignore"],
40504
- timeout: GIT_TIMEOUT_MS3
40595
+ timeout: GIT_TIMEOUT_MS4
40505
40596
  }).replace(/\r?\n$/u, "");
40506
40597
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
40507
40598
  return join9(resolve3(cwd, value), relative5);
40508
40599
  }
40509
40600
  function gitPath(cwd, relative5) {
40510
- const value = execFileSync3("git", ["rev-parse", "--git-path", relative5], {
40601
+ const value = execFileSync4("git", ["rev-parse", "--git-path", relative5], {
40511
40602
  cwd,
40512
40603
  encoding: "utf8",
40513
40604
  stdio: ["ignore", "pipe", "ignore"],
40514
- timeout: GIT_TIMEOUT_MS3
40605
+ timeout: GIT_TIMEOUT_MS4
40515
40606
  }).replace(/\r?\n$/u, "");
40516
40607
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
40517
40608
  return resolve3(cwd, value);
@@ -40571,7 +40662,7 @@ function clearHooksWired(cwd) {
40571
40662
  function latestLocalCommit(cwd) {
40572
40663
  let output;
40573
40664
  try {
40574
- output = execFileSync3(
40665
+ output = execFileSync4(
40575
40666
  "git",
40576
40667
  [
40577
40668
  "log",
@@ -40583,7 +40674,7 @@ function latestLocalCommit(cwd) {
40583
40674
  "--format=%H%x09%gd%x09%gs",
40584
40675
  "HEAD"
40585
40676
  ],
40586
- { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS3 }
40677
+ { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS4 }
40587
40678
  );
40588
40679
  } catch {
40589
40680
  return void 0;
@@ -40641,7 +40732,7 @@ async function askConfirmation(question2, output = process.stdout) {
40641
40732
  }
40642
40733
 
40643
40734
  // src/lib/git-hooks.ts
40644
- import { execFileSync as execFileSync4 } from "child_process";
40735
+ import { execFileSync as execFileSync5 } from "child_process";
40645
40736
  import { createHash as createHash6, randomUUID as randomUUID2 } from "crypto";
40646
40737
  import {
40647
40738
  constants as constants3,
@@ -41178,16 +41269,16 @@ function directReleaseLayout(releaseDir) {
41178
41269
  }
41179
41270
  function readReleaseManifest(releaseDir, releaseName) {
41180
41271
  try {
41181
- const manifestPath = join11(releaseDir, "manifest.json");
41182
- const manifestStat = statSync2(manifestPath);
41272
+ const manifestPath2 = join11(releaseDir, "manifest.json");
41273
+ const manifestStat = statSync2(manifestPath2);
41183
41274
  if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
41184
- const raw = readFileSync8(manifestPath, "utf8");
41275
+ const raw = readFileSync8(manifestPath2, "utf8");
41185
41276
  const parsed = JSON.parse(raw);
41186
41277
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
41187
41278
  if (!exactKeys(parsed, ["schemaVersion", "version", "nodePath", "files"])) return null;
41188
41279
  const candidate = parsed;
41189
41280
  if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute5(candidate.nodePath) || /[\r\n]/u.test(candidate.nodePath) || !candidate.files || typeof candidate.files !== "object" || Array.isArray(candidate.files) || !exactKeys(candidate.files, Object.keys(HOOK_RUNTIME_ENTRIES)) || Object.values(candidate.files).some(
41190
- (digest2) => typeof digest2 !== "string" || !/^[0-9a-f]{64}$/u.test(digest2)
41281
+ (digest3) => typeof digest3 !== "string" || !/^[0-9a-f]{64}$/u.test(digest3)
41191
41282
  )) {
41192
41283
  return null;
41193
41284
  }
@@ -41392,13 +41483,13 @@ function writeRelease(sourceDir, releaseDir, manifest, releasesDir) {
41392
41483
  mode: DATA_FILE_MODE
41393
41484
  });
41394
41485
  syncStagedFile(packageJsonPath);
41395
- const manifestPath = join11(stagingDir, "manifest.json");
41396
- writeFileSync4(manifestPath, exactManifest(manifest), {
41486
+ const manifestPath2 = join11(stagingDir, "manifest.json");
41487
+ writeFileSync4(manifestPath2, exactManifest(manifest), {
41397
41488
  encoding: "utf8",
41398
41489
  flag: "wx",
41399
41490
  mode: DATA_FILE_MODE
41400
41491
  });
41401
- syncStagedFile(manifestPath);
41492
+ syncStagedFile(manifestPath2);
41402
41493
  for (const directory of [...directories].sort((left, right) => right.length - left.length)) {
41403
41494
  syncDirectory(directory);
41404
41495
  }
@@ -41616,7 +41707,7 @@ var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
41616
41707
  var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
41617
41708
  var LEGACY_GLOBAL_OWNED_HEADER = "# prim global post-commit hook (core.hooksPath) \u2014 managed by prim; do not edit.";
41618
41709
  var MAX_HOOK_BYTES = 1048576;
41619
- var GIT_TIMEOUT_MS4 = 1e3;
41710
+ var GIT_TIMEOUT_MS5 = 1e3;
41620
41711
  var SUPPORTED_SHEBANGS = /* @__PURE__ */ new Set([
41621
41712
  "#!/bin/sh",
41622
41713
  "#!/usr/bin/env sh",
@@ -41659,14 +41750,14 @@ function managedHookSpec(hookName) {
41659
41750
  }
41660
41751
  function gitHooksMode(options = {}) {
41661
41752
  try {
41662
- const value = execFileSync4(
41753
+ const value = execFileSync5(
41663
41754
  "git",
41664
41755
  ["config", ...options.global ? ["--global"] : [], "--get", "prim.gitHooks"],
41665
41756
  {
41666
41757
  cwd: options.cwd,
41667
41758
  encoding: "utf8",
41668
41759
  stdio: ["ignore", "pipe", "ignore"],
41669
- timeout: GIT_TIMEOUT_MS4
41760
+ timeout: GIT_TIMEOUT_MS5
41670
41761
  }
41671
41762
  ).trim();
41672
41763
  return value === "manual" ? "manual" : "auto";
@@ -41769,11 +41860,11 @@ function primGitHooksDirectory() {
41769
41860
  function otherWorktreeRoots(gitRoot) {
41770
41861
  try {
41771
41862
  const self = realpathLoose(gitRoot);
41772
- return execFileSync4("git", ["worktree", "list", "--porcelain"], {
41863
+ return execFileSync5("git", ["worktree", "list", "--porcelain"], {
41773
41864
  cwd: gitRoot,
41774
41865
  encoding: "utf8",
41775
41866
  stdio: ["ignore", "pipe", "ignore"],
41776
- timeout: GIT_TIMEOUT_MS4
41867
+ timeout: GIT_TIMEOUT_MS5
41777
41868
  }).split("\n").flatMap((line) => line.startsWith("worktree ") ? [realpathLoose(line.slice(9))] : []).filter((root) => root !== self);
41778
41869
  } catch {
41779
41870
  return [];
@@ -41793,11 +41884,11 @@ function hookLocation(hookPath, dirs) {
41793
41884
  }
41794
41885
  function hooksPathScope(cwd) {
41795
41886
  try {
41796
- const scope = execFileSync4("git", ["config", "--show-scope", "--get", "core.hooksPath"], {
41887
+ const scope = execFileSync5("git", ["config", "--show-scope", "--get", "core.hooksPath"], {
41797
41888
  cwd,
41798
41889
  encoding: "utf8",
41799
41890
  stdio: ["ignore", "pipe", "ignore"],
41800
- timeout: GIT_TIMEOUT_MS4
41891
+ timeout: GIT_TIMEOUT_MS5
41801
41892
  }).split(" ")[0];
41802
41893
  return scope === "local" || scope === "worktree" || scope === "global" || scope === "system" || scope === "command" ? scope : void 0;
41803
41894
  } catch {
@@ -41827,14 +41918,14 @@ function safeGitPath(root, value) {
41827
41918
  function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
41828
41919
  const gitRoot = gitToplevel(cwd);
41829
41920
  if (!gitRoot) throw new Error("not a git repository");
41830
- const lines = execFileSync4(
41921
+ const lines = execFileSync5(
41831
41922
  "git",
41832
41923
  ["rev-parse", "--git-path", "hooks", "--absolute-git-dir", "--git-common-dir"],
41833
41924
  {
41834
41925
  cwd: gitRoot,
41835
41926
  encoding: "utf8",
41836
41927
  stdio: ["ignore", "pipe", "ignore"],
41837
- timeout: GIT_TIMEOUT_MS4
41928
+ timeout: GIT_TIMEOUT_MS5
41838
41929
  }
41839
41930
  ).replace(/\r?\n$/u, "").split(/\r?\n/u);
41840
41931
  if (lines.length !== 3) throw new Error("Git returned unexpected repository paths");
@@ -42324,11 +42415,11 @@ function inspectEffectiveGitHook(hookName, cwd = process.cwd()) {
42324
42415
  function projectHooksPathIsConfigured(gitRoot) {
42325
42416
  for (const scope of ["--worktree", "--local"]) {
42326
42417
  try {
42327
- const value = execFileSync4("git", ["config", scope, "--get", "core.hooksPath"], {
42418
+ const value = execFileSync5("git", ["config", scope, "--get", "core.hooksPath"], {
42328
42419
  cwd: gitRoot,
42329
42420
  encoding: "utf8",
42330
42421
  stdio: ["ignore", "pipe", "ignore"],
42331
- timeout: GIT_TIMEOUT_MS4
42422
+ timeout: GIT_TIMEOUT_MS5
42332
42423
  }).trim();
42333
42424
  if (value.length > 0) return true;
42334
42425
  } catch {
@@ -42354,11 +42445,11 @@ function projectGitHookTarget(hookName, cwd = process.cwd()) {
42354
42445
  };
42355
42446
  }
42356
42447
  function projectHooksDir(gitRoot) {
42357
- const commonDir = execFileSync4("git", ["rev-parse", "--git-common-dir"], {
42448
+ const commonDir = execFileSync5("git", ["rev-parse", "--git-common-dir"], {
42358
42449
  cwd: gitRoot,
42359
42450
  encoding: "utf8",
42360
42451
  stdio: ["ignore", "pipe", "ignore"],
42361
- timeout: GIT_TIMEOUT_MS4
42452
+ timeout: GIT_TIMEOUT_MS5
42362
42453
  }).replace(/\r?\n$/u, "");
42363
42454
  return resolve5(safeGitPath(gitRoot, commonDir), "hooks");
42364
42455
  }
@@ -43405,8 +43496,8 @@ ${verificationUrl}`);
43405
43496
  const state = base64url(randomBytes5(16));
43406
43497
  const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
43407
43498
  let settle;
43408
- const outcome = new Promise((resolve16) => {
43409
- settle = resolve16;
43499
+ const outcome = new Promise((resolve17) => {
43500
+ settle = resolve17;
43410
43501
  });
43411
43502
  const server = createServer((req, res) => {
43412
43503
  const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
@@ -43420,12 +43511,12 @@ ${verificationUrl}`);
43420
43511
  res.end(page.html, () => settle(page.result));
43421
43512
  });
43422
43513
  try {
43423
- await new Promise((resolve16, reject) => {
43514
+ await new Promise((resolve17, reject) => {
43424
43515
  const onError = (err) => reject(err);
43425
43516
  server.once("error", onError);
43426
43517
  server.listen(CALLBACK_PORT, LOCALHOST, () => {
43427
43518
  server.removeListener("error", onError);
43428
- resolve16();
43519
+ resolve17();
43429
43520
  });
43430
43521
  });
43431
43522
  } catch (err) {
@@ -43706,7 +43797,7 @@ function registerGithubCommands(program3, dependencies = defaultDependencies3) {
43706
43797
  }
43707
43798
 
43708
43799
  // src/commands/hooks.ts
43709
- import { execFileSync as execFileSync5 } from "child_process";
43800
+ import { execFileSync as execFileSync6 } from "child_process";
43710
43801
  import {
43711
43802
  existsSync as existsSync8,
43712
43803
  lstatSync as lstatSync5,
@@ -43722,7 +43813,7 @@ var PRE_COMMIT2 = { hookName: "pre-commit", binName: "prim-pre-commit" };
43722
43813
  var POST_COMMIT2 = { hookName: "post-commit", binName: "prim-post-commit" };
43723
43814
  var POST_REWRITE2 = { hookName: "post-rewrite", binName: "prim-post-rewrite" };
43724
43815
  var HOOKS = [PRE_COMMIT2, POST_COMMIT2, POST_REWRITE2];
43725
- var GIT_TIMEOUT_MS5 = 1e3;
43816
+ var GIT_TIMEOUT_MS6 = 1e3;
43726
43817
  function blockMarkers3(spec) {
43727
43818
  return {
43728
43819
  start: `# >>> prim ${spec.hookName} hook >>>`,
@@ -43777,10 +43868,10 @@ function isOurHooksDir(value) {
43777
43868
  }
43778
43869
  function gitConfigGet(level) {
43779
43870
  try {
43780
- return execFileSync5("git", ["config", level, "--get", "core.hooksPath"], {
43871
+ return execFileSync6("git", ["config", level, "--get", "core.hooksPath"], {
43781
43872
  encoding: "utf-8",
43782
43873
  stdio: ["ignore", "pipe", "ignore"],
43783
- timeout: GIT_TIMEOUT_MS5
43874
+ timeout: GIT_TIMEOUT_MS6
43784
43875
  }).trim();
43785
43876
  } catch {
43786
43877
  return "";
@@ -44071,9 +44162,9 @@ function installGlobalHooks(opts = {}) {
44071
44162
  );
44072
44163
  }
44073
44164
  if (!writeOwnHooks()) return "runtime_missing";
44074
- execFileSync5("git", ["config", "--global", "core.hooksPath", PRIM_GIT_HOOKS_DIR], {
44165
+ execFileSync6("git", ["config", "--global", "core.hooksPath", PRIM_GIT_HOOKS_DIR], {
44075
44166
  stdio: ["ignore", "ignore", "pipe"],
44076
- timeout: GIT_TIMEOUT_MS5
44167
+ timeout: GIT_TIMEOUT_MS6
44077
44168
  });
44078
44169
  console.log(
44079
44170
  `Installed prim global git hooks; set core.hooksPath to ${PRIM_GIT_HOOKS_DIR}. Repos are opt-in: run \`prim enable\` in each repo to capture, or \`git config --global prim.active true\` for all.`
@@ -44099,9 +44190,9 @@ function uninstallGlobalHooks() {
44099
44190
  if (isOurHooksDir(global2)) {
44100
44191
  const entries = assertOwnedHooksDirectorySafeToRemove();
44101
44192
  for (const name2 of entries) unlinkSync3(resolve6(PRIM_GIT_HOOKS_DIR, name2));
44102
- execFileSync5("git", ["config", "--global", "--unset", "core.hooksPath"], {
44193
+ execFileSync6("git", ["config", "--global", "--unset", "core.hooksPath"], {
44103
44194
  stdio: ["ignore", "ignore", "pipe"],
44104
- timeout: GIT_TIMEOUT_MS5
44195
+ timeout: GIT_TIMEOUT_MS6
44105
44196
  });
44106
44197
  console.log("Removed prim global git hooks and unset core.hooksPath.");
44107
44198
  return;
@@ -44407,6 +44498,7 @@ async function applyActivation(active, globals = {}) {
44407
44498
  }
44408
44499
  }
44409
44500
  phase = "local activation";
44501
+ clearDemoPause(root);
44410
44502
  setRepoActive(root, active);
44411
44503
  if (!active) clearHooksWired(root);
44412
44504
  if (active) {
@@ -44448,7 +44540,7 @@ import { homedir as homedir5 } from "os";
44448
44540
  import { join as join14 } from "path";
44449
44541
 
44450
44542
  // src/lib/preflight-host.ts
44451
- import { execFileSync as execFileSync6 } from "child_process";
44543
+ import { execFileSync as execFileSync7 } from "child_process";
44452
44544
  function inspectFailureProtection(host) {
44453
44545
  if (host === "codex")
44454
44546
  return {
@@ -44458,7 +44550,7 @@ function inspectFailureProtection(host) {
44458
44550
  };
44459
44551
  let output;
44460
44552
  try {
44461
- output = execFileSync6(host, [host === "hermes" ? "version" : "--version"], {
44553
+ output = execFileSync7(host, [host === "hermes" ? "version" : "--version"], {
44462
44554
  encoding: "utf8",
44463
44555
  timeout: 3e3,
44464
44556
  maxBuffer: 64 * 1024,
@@ -45002,7 +45094,7 @@ async function inspectCodexHost(reload = false) {
45002
45094
  } catch {
45003
45095
  return unavailable("host-socket-unavailable");
45004
45096
  }
45005
- return new Promise((resolve16) => {
45097
+ return new Promise((resolve17) => {
45006
45098
  let finished = false;
45007
45099
  let refreshed = false;
45008
45100
  let requestId = 0;
@@ -45018,7 +45110,7 @@ async function inspectCodexHost(reload = false) {
45018
45110
  finished = true;
45019
45111
  clearTimeout(timer);
45020
45112
  socket.terminate();
45021
- resolve16(value);
45113
+ resolve17(value);
45022
45114
  };
45023
45115
  const fail = (reason) => finish({ ...unavailable(reason), ...refreshed ? { reload: "refreshed" } : {} });
45024
45116
  const timer = setTimeout(() => fail("host-timeout"), TIMEOUT_MS);
@@ -45619,7 +45711,7 @@ async function runPinnedEnsure(options) {
45619
45711
  npm_config_fetch_retry_maxtimeout: "5000",
45620
45712
  npm_config_fetch_timeout: "15000"
45621
45713
  };
45622
- return await new Promise((resolve16) => {
45714
+ return await new Promise((resolve17) => {
45623
45715
  let settled = false;
45624
45716
  let child;
45625
45717
  try {
@@ -45629,7 +45721,7 @@ async function runPinnedEnsure(options) {
45629
45721
  { env: env4, stdio: "ignore" }
45630
45722
  );
45631
45723
  } catch {
45632
- resolve16(false);
45724
+ resolve17(false);
45633
45725
  return;
45634
45726
  }
45635
45727
  const timer = setTimeout(() => {
@@ -45640,7 +45732,7 @@ async function runPinnedEnsure(options) {
45640
45732
  if (settled) return;
45641
45733
  settled = true;
45642
45734
  clearTimeout(timer);
45643
- resolve16(result);
45735
+ resolve17(result);
45644
45736
  };
45645
45737
  timer.unref();
45646
45738
  child.once("error", () => finish(false));
@@ -45841,10 +45933,10 @@ function exactKeys2(value, expected) {
45841
45933
  return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
45842
45934
  }
45843
45935
  function readOwnedRuntimeManifest(releaseDir) {
45844
- const manifestPath = join19(releaseDir, "manifest.json");
45936
+ const manifestPath2 = join19(releaseDir, "manifest.json");
45845
45937
  const daemonPath = join19(releaseDir, "prim-daemon-server");
45846
45938
  try {
45847
- const raw = readFileSync14(manifestPath, "utf8");
45939
+ const raw = readFileSync14(manifestPath2, "utf8");
45848
45940
  const parsed = JSON.parse(raw);
45849
45941
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
45850
45942
  if (!exactKeys2(parsed, [
@@ -47054,7 +47146,7 @@ function clearStaleArtifacts() {
47054
47146
  }
47055
47147
  }
47056
47148
  function sleep(ms) {
47057
- return new Promise((resolve16) => setTimeout(resolve16, ms));
47149
+ return new Promise((resolve17) => setTimeout(resolve17, ms));
47058
47150
  }
47059
47151
  function spawnDaemon(options) {
47060
47152
  const file = binFile(DAEMON_BIN);
@@ -59031,7 +59123,7 @@ function registerDecisionsCommands(program3) {
59031
59123
 
59032
59124
  // src/commands/demo.ts
59033
59125
  import { createHash as createHash11 } from "crypto";
59034
- import { resolve as resolve10 } from "path";
59126
+ import { join as join26, resolve as resolve10 } from "path";
59035
59127
  import { createInterface } from "readline/promises";
59036
59128
 
59037
59129
  // node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
@@ -59593,14 +59685,14 @@ function readRun(id2) {
59593
59685
  "cleanup",
59594
59686
  "completed",
59595
59687
  "skipped"
59596
- ].includes(run.stage) || run.needsStatus !== void 0 && typeof run.needsStatus !== "boolean" || run.server !== void 0 && !isDemoStatusResponse(run.server) || run.receipt !== void 0 && (!Number.isSafeInteger(run.receipt.revision) || run.receipt.revision < 0 || !/^[a-f0-9]{64}$/u.test(run.receipt.appliedDigest)) || typeof run.terminal !== "boolean" || !Array.isArray(run.launcher) || run.launcher.length !== 2 || run.launcher.some((value) => typeof value !== "string" || !value.startsWith("/")) || run.agent !== void 0 && !["claude_code", "codex", "cursor", "hermes"].includes(run.agent)) {
59688
+ ].includes(run.stage) || run.needsStatus !== void 0 && typeof run.needsStatus !== "boolean" || run.server !== void 0 && !isDemoStatusResponse(run.server) || run.receipt !== void 0 && (!Number.isSafeInteger(run.receipt.revision) || run.receipt.revision < 0 || !/^[a-f0-9]{64}$/u.test(run.receipt.appliedDigest)) || typeof run.terminal !== "boolean" || !Array.isArray(run.launcher) || run.launcher.length !== 2 || run.launcher.some((value) => typeof value !== "string" || !value.startsWith("/")) || run.agent !== void 0 && !["claude_code", "codex", "cursor", "hermes"].includes(run.agent) || run.welcomeRepo !== void 0 && (typeof run.welcomeRepo !== "string" || !run.welcomeRepo.startsWith("/"))) {
59597
59689
  throw new Error("invalid demo run state");
59598
59690
  }
59599
59691
  return run;
59600
59692
  }
59601
59693
  var saveRun = (run) => saveDemoJson(runPath(run.id), run);
59602
59694
  var lockRun = (id2, action) => withFileLockSync(`${runPath(id2)}.lock`, () => action(readRun(id2)), { timeoutMs: 500 });
59603
- function prepareRun(agent, terminal = false) {
59695
+ function prepareRun(agent, terminal = false, welcomeRepo) {
59604
59696
  const run = {
59605
59697
  version: 2,
59606
59698
  id: randomUUID3(),
@@ -59608,7 +59700,8 @@ function prepareRun(agent, terminal = false) {
59608
59700
  terminal,
59609
59701
  agent,
59610
59702
  preparationKey: preparationKey(agent),
59611
- launcher: [process.execPath, resolve9(process.argv[1])]
59703
+ launcher: [process.execPath, resolve9(process.argv[1])],
59704
+ ...welcomeRepo ? { welcomeRepo } : {}
59612
59705
  };
59613
59706
  saveRun(run);
59614
59707
  return run;
@@ -59655,10 +59748,13 @@ function onboardingFinished() {
59655
59748
  function finishOnboarding(outcome) {
59656
59749
  saveDemoJson(join23(demoDirectory(), "onboarding.json"), { outcome });
59657
59750
  }
59658
- function pendingRuns() {
59751
+ function runIds() {
59659
59752
  const path9 = join23(demoDirectory(), "runs");
59660
59753
  if (!existsSync14(path9)) return [];
59661
- return readdirSync5(path9).filter((name2) => name2.endsWith(".json") && RUN_ID.test(name2.slice(0, -5))).map((name2) => name2.slice(0, -5)).filter((id2) => !["completed", "skipped"].includes(readRun(id2).stage));
59754
+ return readdirSync5(path9).filter((name2) => name2.endsWith(".json") && RUN_ID.test(name2.slice(0, -5))).map((name2) => name2.slice(0, -5));
59755
+ }
59756
+ function pendingRuns() {
59757
+ return runIds().filter((id2) => !["completed", "skipped"].includes(readRun(id2).stage));
59662
59758
  }
59663
59759
  function sessionKey(agent, session) {
59664
59760
  return createHash10("sha256").update(`${agent}\0${session}`).digest("hex");
@@ -59767,10 +59863,10 @@ var WARNING_EDIT = 'export const loadOrders = () => fetch("/orders");\n';
59767
59863
  var REPOSITORY_EDIT = 'import { orders } from "./shared";\nexport const saveOrder = (order: unknown) => orders.save(order);\n';
59768
59864
 
59769
59865
  // src/demo/story.ts
59770
- var DEMO_TASK = "Implement CSV export for customer records, including name and email.";
59771
- var DEMO_ORIGINAL = "Exclude customer contact information e.g. email addresses from public-facing data pipelines";
59772
- var DEMO_RATIONALE = "Customer contact details are collected for account communication, not public distribution. Keeping them out of public-facing pipelines supports our data-minimization and purpose-limitation obligations and reduces the risk of unauthorized disclosure.";
59773
- var DEMO_REPLACEMENT = "Allow customer names and email addresses in CSV exports";
59866
+ var DEMO_TASK = "Implement CSV export for user records, including name and email.";
59867
+ var DEMO_ORIGINAL = "Exclude user contact information e.g. email addresses from public-facing data pipelines";
59868
+ var DEMO_RATIONALE = "User contact details are collected for account communication, not public distribution. Keeping them out of public-facing pipelines supports our data-minimization and purpose-limitation obligations and reduces the risk of unauthorized disclosure.";
59869
+ var DEMO_REPLACEMENT = "Allow user names and email addresses in CSV exports";
59774
59870
  var DEMO_INITIAL = '// Fictional customer export project.\nexport const customerCsv = "";\n';
59775
59871
  var DEMO_ADHERE = '// Fictional customer export project.\nexport const customerCsv = "name\\nAvery";\n';
59776
59872
  var DEMO_SUPERSEDE = '// Fictional customer export project.\nexport const customerCsv = "name,email\\nAvery,avery@example.invalid";\n';
@@ -59880,6 +59976,7 @@ function demoTrustGuidance(agent) {
59880
59976
  return "Activate the installed prim hooks in your agent, then retry the exact nextAction.";
59881
59977
  }
59882
59978
  function consumeAcknowledgment(run, action, choice, reason) {
59979
+ if (run.welcomeRepo) return isRepoActiveForCapture(run.welcomeRepo) ? "repo-active" : void 0;
59883
59980
  if (run.terminal)
59884
59981
  return process.stdin.isTTY && process.stderr.isTTY ? void 0 : "terminal-required";
59885
59982
  const ack = run.acknowledgment;
@@ -59919,7 +60016,7 @@ function present(run) {
59919
60016
  return `[DEMO] How Primitive Catches Conflicts
59920
60017
 
59921
60018
  You're a new engineer on ${safeMarkdown(server.story.orgName)}'s team.
59922
- And you've been tasked with implementing CSV export functionality for customer records.
60019
+ And you've been tasked with implementing CSV export functionality for user records.
59923
60020
  Enter this prompt to do so:
59924
60021
  ${DEMO_TASK}`;
59925
60022
  if (run.stage === "conflict")
@@ -60057,6 +60154,7 @@ async function finishResolution(run, choice, reason) {
60057
60154
  run.stage = "completed";
60058
60155
  saveRun(run);
60059
60156
  finishOnboarding("completed");
60157
+ if (run.welcomeRepo) endDemoPause(run.welcomeRepo, run.id);
60060
60158
  }
60061
60159
  }
60062
60160
  async function pendingIsolation(run, isolation, action, choice, reason) {
@@ -60085,7 +60183,7 @@ ${action === "status" ? guidance : "The pre-tool hook has not verified isolation
60085
60183
  async function advanceDemo(id2, action, choice, reason) {
60086
60184
  if (action === "status") {
60087
60185
  const run = readRun(id2);
60088
- if (!run.terminal && !run.acknowledgment)
60186
+ if (!run.terminal && !run.welcomeRepo && !run.acknowledgment)
60089
60187
  return pendingIsolation(run, "acknowledgment-missing", action);
60090
60188
  }
60091
60189
  return await lockRunAsync(id2, async (run) => {
@@ -60099,13 +60197,14 @@ async function advanceDemo(id2, action, choice, reason) {
60099
60197
  run.stage = "skipped";
60100
60198
  saveRun(run);
60101
60199
  finishOnboarding("skipped");
60200
+ if (run.welcomeRepo) endDemoPause(run.welcomeRepo, run.id);
60102
60201
  return handoff(run);
60103
60202
  }
60104
60203
  if (run.version === 1)
60105
60204
  throw new Error(
60106
60205
  `Legacy tour: clean up with ${demoCommand(run, "skip")}, then run prim demo again`
60107
60206
  );
60108
- const isolation = action === "status" && !run.terminal && !run.acknowledgment ? "acknowledgment-missing" : consumeAcknowledgment(run, action, choice, reason);
60207
+ const isolation = action === "status" && !run.terminal && !run.welcomeRepo && !run.acknowledgment ? "acknowledgment-missing" : consumeAcknowledgment(run, action, choice, reason);
60109
60208
  if (isolation) return pendingIsolation(run, isolation, action, choice, reason);
60110
60209
  if (action === "status") {
60111
60210
  const server = run.server ? await demoStatus(run.server.runId) : void 0;
@@ -60152,6 +60251,7 @@ async function advanceDemo(id2, action, choice, reason) {
60152
60251
  return {
60153
60252
  ...resultFor2(run),
60154
60253
  stage: "pending",
60254
+ detail: run.server.reasonCode ?? "evaluation in progress",
60155
60255
  nextAction: demoCommand(run, action, choice, reason),
60156
60256
  presentation: `${label}
60157
60257
 
@@ -60164,6 +60264,7 @@ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File uncha
60164
60264
  return {
60165
60265
  ...resultFor2(run),
60166
60266
  stage: "pending",
60267
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error)),
60167
60268
  nextAction: demoCommand(run, action, choice, reason),
60168
60269
  presentation: `Tour pending: ${terminalSafeLine(error instanceof Error ? error.message : String(error))}`,
60169
60270
  ...run.stage === "cleanup" ? { outcomePresentation: present(run) } : {}
@@ -60171,6 +60272,103 @@ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File uncha
60171
60272
  }
60172
60273
  });
60173
60274
  }
60275
+ function welcomeDemoState(run, result) {
60276
+ if (result.isolation === "repo-active") return { stage: "error", reason: "repo-active" };
60277
+ const server = run.server;
60278
+ if (result.stage === "pending" || !server)
60279
+ return { stage: "pending", ...result.detail ? { detail: result.detail } : {} };
60280
+ if (run.stage === "prompt")
60281
+ return { stage: "prompt", story: { org: safeMarkdown(server.story.orgName), task: DEMO_TASK } };
60282
+ if (run.stage === "conflict")
60283
+ return {
60284
+ stage: "conflict",
60285
+ conflict: {
60286
+ author: safeMarkdown(server.authorName),
60287
+ date: safeMarkdown(server.story.decisionDate),
60288
+ intent: DEMO_ORIGINAL,
60289
+ rationale: DEMO_RATIONALE,
60290
+ file: "customers.ts",
60291
+ code: readSample(run, "customers.ts").trimEnd()
60292
+ }
60293
+ };
60294
+ if ((run.stage === "completed" || run.stage === "cleanup") && server.choice)
60295
+ return {
60296
+ stage: "completed",
60297
+ outcome: {
60298
+ choice: server.choice,
60299
+ ...server.reason ? { reason: server.reason } : {},
60300
+ author: safeMarkdown(server.authorName),
60301
+ recipient: safeMarkdown(server.story.recipient),
60302
+ email: server.email
60303
+ },
60304
+ diff: compactDiff(DEMO_INITIAL, server.choice === "adhere" ? DEMO_ADHERE : DEMO_SUPERSEDE)
60305
+ };
60306
+ if (run.stage === "skipped") return { stage: "skipped" };
60307
+ return { stage: "pending" };
60308
+ }
60309
+ async function endWelcomeRuns() {
60310
+ for (let stale = pendingWelcomeRun(); stale; stale = pendingWelcomeRun()) {
60311
+ await advanceDemo(stale.id, "skip").catch(() => {
60312
+ if (stale.welcomeRepo) endDemoPause(stale.welcomeRepo, stale.id);
60313
+ cleanSandbox(stale);
60314
+ stale.stage = "skipped";
60315
+ saveRun(stale);
60316
+ });
60317
+ }
60318
+ }
60319
+ function pendingWelcomeRun(repo) {
60320
+ for (const id2 of runIds()) {
60321
+ try {
60322
+ const run = readRun(id2);
60323
+ if (run.welcomeRepo && (repo === void 0 || run.welcomeRepo === repo) && !["completed", "skipped"].includes(run.stage))
60324
+ return run;
60325
+ } catch {
60326
+ }
60327
+ }
60328
+ }
60329
+ async function advanceWelcomeDemo(action, choice, reason) {
60330
+ if (action === "start") {
60331
+ const root2 = gitToplevel();
60332
+ if (!root2) return { stage: "error", reason: "not-a-repo" };
60333
+ const run2 = await withFileLock(join26(demoDirectory(), "welcome.lock"), async () => {
60334
+ const existing = pendingWelcomeRun(root2);
60335
+ if (existing?.welcomeRepo === root2) {
60336
+ const active = isRepoActiveForCapture(root2);
60337
+ const pause = readDemoPause(root2);
60338
+ if (active || pause && (pause.runId !== existing.id || pause.ending))
60339
+ pauseCaptureForDemo(root2, existing.id);
60340
+ return existing;
60341
+ }
60342
+ await endWelcomeRuns();
60343
+ const run3 = prepareRun(void 0, false, root2);
60344
+ if (isRepoActiveForCapture(root2) || readDemoPause(root2)) pauseCaptureForDemo(root2, run3.id);
60345
+ return run3;
60346
+ });
60347
+ const result2 = await advanceDemo(
60348
+ run2.id,
60349
+ run2.stage === "prepared" || run2.stage === "prompt" ? "start" : "status"
60350
+ );
60351
+ return welcomeDemoState(readRun(run2.id), result2);
60352
+ }
60353
+ const root = gitToplevel();
60354
+ if (!root) return { stage: "error", reason: "not-a-repo" };
60355
+ const run = pendingWelcomeRun(root);
60356
+ if (!run?.welcomeRepo) return { stage: "error", reason: "not-started" };
60357
+ extendDemoPause(run.welcomeRepo, run.id);
60358
+ if (action === "resolve") {
60359
+ try {
60360
+ requireResolution(choice, reason);
60361
+ } catch (error) {
60362
+ return {
60363
+ stage: "error",
60364
+ reason: "invalid",
60365
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error))
60366
+ };
60367
+ }
60368
+ }
60369
+ const result = await advanceDemo(run.id, action, choice, reason);
60370
+ return welcomeDemoState(readRun(run.id), result);
60371
+ }
60174
60372
  function parseAgent(value) {
60175
60373
  if (value === "claude") return "claude_code";
60176
60374
  if (value === void 0 || ["claude_code", "codex", "cursor", "hermes"].includes(value))
@@ -60299,14 +60497,32 @@ function registerDemoCommands(program3) {
60299
60497
  }
60300
60498
  });
60301
60499
  for (const action of ["start", "attempt", "resolve", "status", "skip"]) {
60302
- const sub = demo.command(`${action} ${action === "skip" ? "[runId]" : "<runId>"}`);
60500
+ const sub = demo.command(`${action} ${action === "status" ? "<runId>" : "[runId]"}`);
60303
60501
  if (action === "resolve")
60304
60502
  sub.requiredOption("--choice <choice>", "adhere or supersede").option("--reason <reason>", "your reason for the displayed replacement");
60305
60503
  sub.action(
60306
60504
  async (id2, options) => {
60307
60505
  try {
60506
+ if (action !== "skip" && action !== "status" && !id2) {
60507
+ const state = await advanceWelcomeDemo(action, options.choice, options.reason).catch(
60508
+ (error) => ({
60509
+ stage: "error",
60510
+ reason: "invalid",
60511
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error))
60512
+ })
60513
+ );
60514
+ printJson2(state);
60515
+ if (state.stage === "error") process.exitCode = 1;
60516
+ return;
60517
+ }
60308
60518
  if (action === "skip" && !id2) {
60309
- finishOnboarding("skipped");
60519
+ await endWelcomeRuns();
60520
+ let finished = false;
60521
+ try {
60522
+ finished = onboardingFinished();
60523
+ } catch {
60524
+ }
60525
+ if (!finished) finishOnboarding("skipped");
60310
60526
  printJson2({
60311
60527
  fictional: true,
60312
60528
  stage: "skipped",
@@ -60485,7 +60701,7 @@ import {
60485
60701
  readSync as readSync2,
60486
60702
  readdirSync as readdirSync8
60487
60703
  } from "fs";
60488
- import { dirname as dirname13, join as join27 } from "path";
60704
+ import { dirname as dirname13, join as join28 } from "path";
60489
60705
 
60490
60706
  // src/drain-progress.ts
60491
60707
  import {
@@ -60496,7 +60712,7 @@ import {
60496
60712
  rmSync as rmSync6,
60497
60713
  rmdirSync as rmdirSync2
60498
60714
  } from "fs";
60499
- import { basename as basename5, dirname as dirname12, join as join26 } from "path";
60715
+ import { basename as basename5, dirname as dirname12, join as join27 } from "path";
60500
60716
  var DIRECTORY_MODE3 = 448;
60501
60717
  var FILE_MODE2 = 384;
60502
60718
  var DRAIN_PROGRESS_DIRNAME = "drain-progress";
@@ -60505,10 +60721,10 @@ function rotationIdentity(stat) {
60505
60721
  return { size: stat.size, ino: stat.ino, dev: stat.dev };
60506
60722
  }
60507
60723
  function drainProgressDirectory(flushingPath) {
60508
- return join26(dirname12(flushingPath), DRAIN_PROGRESS_DIRNAME);
60724
+ return join27(dirname12(flushingPath), DRAIN_PROGRESS_DIRNAME);
60509
60725
  }
60510
60726
  function drainProgressPath(flushingPath) {
60511
- return join26(drainProgressDirectory(flushingPath), `${basename5(flushingPath)}.json`);
60727
+ return join27(drainProgressDirectory(flushingPath), `${basename5(flushingPath)}.json`);
60512
60728
  }
60513
60729
  function isByteCount(value) {
60514
60730
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -60553,7 +60769,7 @@ function removeDrainCheckpoint(flushingPath) {
60553
60769
  removeEmptyDirectory(drainProgressDirectory(flushingPath));
60554
60770
  }
60555
60771
  function sweepOrphanedDrainCheckpoints(bucketDirectory) {
60556
- const directory = join26(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
60772
+ const directory = join27(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
60557
60773
  let names;
60558
60774
  try {
60559
60775
  names = readdirSync7(directory);
@@ -60562,11 +60778,11 @@ function sweepOrphanedDrainCheckpoints(bucketDirectory) {
60562
60778
  }
60563
60779
  for (const name2 of names) {
60564
60780
  const rotation = CHECKPOINT_NAME.exec(name2)?.[1];
60565
- if (rotation === void 0 || existsSync17(join26(bucketDirectory, rotation))) {
60781
+ if (rotation === void 0 || existsSync17(join27(bucketDirectory, rotation))) {
60566
60782
  continue;
60567
60783
  }
60568
60784
  try {
60569
- rmSync6(join26(directory, name2), { force: true });
60785
+ rmSync6(join27(directory, name2), { force: true });
60570
60786
  } catch {
60571
60787
  }
60572
60788
  }
@@ -60577,7 +60793,7 @@ function sweepOrphanedDrainCheckpoints(bucketDirectory) {
60577
60793
  }
60578
60794
 
60579
60795
  // src/journal.ts
60580
- var JOURNAL_DIR = join27(primConfigDirectory(), "moves");
60796
+ var JOURNAL_DIR = join28(primConfigDirectory(), "moves");
60581
60797
  var JOURNAL_BASENAME = "journal.ndjson";
60582
60798
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
60583
60799
  var PENDING_STATS_MAX_FILES = 128;
@@ -60589,7 +60805,7 @@ function envSlug(apiUrl) {
60589
60805
  return slug;
60590
60806
  }
60591
60807
  function currentEnvDir() {
60592
- return join27(JOURNAL_DIR, envSlug(getSiteUrl()));
60808
+ return join28(JOURNAL_DIR, envSlug(getSiteUrl()));
60593
60809
  }
60594
60810
  function parseMoves(content2) {
60595
60811
  const moves = [];
@@ -60620,7 +60836,7 @@ function listBuckets() {
60620
60836
  if (!entry.isDirectory()) {
60621
60837
  continue;
60622
60838
  }
60623
- const path9 = join27(envDir, entry.name, JOURNAL_BASENAME);
60839
+ const path9 = join28(envDir, entry.name, JOURNAL_BASENAME);
60624
60840
  if (existsSync18(path9)) {
60625
60841
  out.push({ bucket: entry.name, path: path9 });
60626
60842
  }
@@ -60697,7 +60913,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
60697
60913
  entry = entries.readSync();
60698
60914
  continue;
60699
60915
  }
60700
- const path9 = join27(dir, entry.name);
60916
+ const path9 = join28(dir, entry.name);
60701
60917
  let sample;
60702
60918
  try {
60703
60919
  sample = sampleJournalFile(path9, remainingBytes, { fromDrainCheckpoint: true });
@@ -60735,7 +60951,7 @@ function listFlushing(options = {}) {
60735
60951
  break;
60736
60952
  }
60737
60953
  if (entry.isDirectory()) {
60738
- const found = listFlushingInDir(join27(envDir, entry.name), entry.name, {
60954
+ const found = listFlushingInDir(join28(envDir, entry.name), entry.name, {
60739
60955
  sampleBytes: remainingBytes,
60740
60956
  maxFiles: maxFiles - out.length
60741
60957
  });
@@ -60755,7 +60971,7 @@ function sweepOrphanedDrainProgress() {
60755
60971
  }
60756
60972
  for (const entry of readdirSync8(envDir, { withFileTypes: true })) {
60757
60973
  if (entry.isDirectory()) {
60758
- sweepOrphanedDrainCheckpoints(join27(envDir, entry.name));
60974
+ sweepOrphanedDrainCheckpoints(join28(envDir, entry.name));
60759
60975
  }
60760
60976
  }
60761
60977
  }
@@ -60806,7 +61022,7 @@ function pendingJournalStats() {
60806
61022
  // src/commands/hermes-install.ts
60807
61023
  import { existsSync as existsSync19, readFileSync as readFileSync21, rmSync as rmSync7, statSync as statSync5 } from "fs";
60808
61024
  import { homedir as homedir10 } from "os";
60809
- import { join as join28 } from "path";
61025
+ import { join as join29 } from "path";
60810
61026
 
60811
61027
  // node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
60812
61028
  var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias");
@@ -64240,10 +64456,10 @@ function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeE
64240
64456
  let offset = bm.offset;
64241
64457
  let commentEnd = null;
64242
64458
  for (const collItem of bm.items) {
64243
- const { start, key, sep: sep5, value } = collItem;
64459
+ const { start, key, sep: sep6, value } = collItem;
64244
64460
  const keyProps = resolveProps(start, {
64245
64461
  indicator: "explicit-key-ind",
64246
- next: key ?? sep5?.[0],
64462
+ next: key ?? sep6?.[0],
64247
64463
  offset,
64248
64464
  onError,
64249
64465
  parentIndent: bm.indent,
@@ -64257,7 +64473,7 @@ function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeE
64257
64473
  else if ("indent" in key && key.indent !== bm.indent)
64258
64474
  onError(offset, "BAD_INDENT", startColMsg);
64259
64475
  }
64260
- if (!keyProps.anchor && !keyProps.tag && !sep5) {
64476
+ if (!keyProps.anchor && !keyProps.tag && !sep6) {
64261
64477
  commentEnd = keyProps.end;
64262
64478
  if (keyProps.comment) {
64263
64479
  if (map2.comment)
@@ -64281,7 +64497,7 @@ function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeE
64281
64497
  ctx.atKey = false;
64282
64498
  if (mapIncludes(ctx, map2.items, keyNode))
64283
64499
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
64284
- const valueProps = resolveProps(sep5 ?? [], {
64500
+ const valueProps = resolveProps(sep6 ?? [], {
64285
64501
  indicator: "map-value-ind",
64286
64502
  next: value,
64287
64503
  offset: keyNode.range[2],
@@ -64297,7 +64513,7 @@ function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeE
64297
64513
  if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
64298
64514
  onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
64299
64515
  }
64300
- const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : composeEmptyNode2(ctx, offset, sep5, null, valueProps, onError);
64516
+ const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : composeEmptyNode2(ctx, offset, sep6, null, valueProps, onError);
64301
64517
  if (ctx.schema.compat)
64302
64518
  flowIndentCheck(bm.indent, value, onError);
64303
64519
  offset = valueNode.range[2];
@@ -64373,7 +64589,7 @@ function resolveEnd(end, offset, reqSpace, onError) {
64373
64589
  let comment2 = "";
64374
64590
  if (end) {
64375
64591
  let hasSpace = false;
64376
- let sep5 = "";
64592
+ let sep6 = "";
64377
64593
  for (const token of end) {
64378
64594
  const { source, type } = token;
64379
64595
  switch (type) {
@@ -64387,13 +64603,13 @@ function resolveEnd(end, offset, reqSpace, onError) {
64387
64603
  if (!comment2)
64388
64604
  comment2 = cb;
64389
64605
  else
64390
- comment2 += sep5 + cb;
64391
- sep5 = "";
64606
+ comment2 += sep6 + cb;
64607
+ sep6 = "";
64392
64608
  break;
64393
64609
  }
64394
64610
  case "newline":
64395
64611
  if (comment2)
64396
- sep5 += source;
64612
+ sep6 += source;
64397
64613
  hasSpace = true;
64398
64614
  break;
64399
64615
  default:
@@ -64422,18 +64638,18 @@ function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: co
64422
64638
  let offset = fc.offset + fc.start.source.length;
64423
64639
  for (let i = 0; i < fc.items.length; ++i) {
64424
64640
  const collItem = fc.items[i];
64425
- const { start, key, sep: sep5, value } = collItem;
64641
+ const { start, key, sep: sep6, value } = collItem;
64426
64642
  const props = resolveProps(start, {
64427
64643
  flow: fcName,
64428
64644
  indicator: "explicit-key-ind",
64429
- next: key ?? sep5?.[0],
64645
+ next: key ?? sep6?.[0],
64430
64646
  offset,
64431
64647
  onError,
64432
64648
  parentIndent: fc.indent,
64433
64649
  startOnNewline: false
64434
64650
  });
64435
64651
  if (!props.found) {
64436
- if (!props.anchor && !props.tag && !sep5 && !value) {
64652
+ if (!props.anchor && !props.tag && !sep6 && !value) {
64437
64653
  if (i === 0 && props.comma)
64438
64654
  onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
64439
64655
  else if (i < fc.items.length - 1)
@@ -64487,8 +64703,8 @@ function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: co
64487
64703
  }
64488
64704
  }
64489
64705
  }
64490
- if (!isMap2 && !sep5 && !props.found) {
64491
- const valueNode = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, sep5, null, props, onError);
64706
+ if (!isMap2 && !sep6 && !props.found) {
64707
+ const valueNode = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, sep6, null, props, onError);
64492
64708
  coll.items.push(valueNode);
64493
64709
  offset = valueNode.range[2];
64494
64710
  if (isBlock(value))
@@ -64500,7 +64716,7 @@ function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: co
64500
64716
  if (isBlock(key))
64501
64717
  onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
64502
64718
  ctx.atKey = false;
64503
- const valueProps = resolveProps(sep5 ?? [], {
64719
+ const valueProps = resolveProps(sep6 ?? [], {
64504
64720
  flow: fcName,
64505
64721
  indicator: "map-value-ind",
64506
64722
  next: value,
@@ -64511,8 +64727,8 @@ function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: co
64511
64727
  });
64512
64728
  if (valueProps.found) {
64513
64729
  if (!isMap2 && !props.found && ctx.options.strict) {
64514
- if (sep5)
64515
- for (const st of sep5) {
64730
+ if (sep6)
64731
+ for (const st of sep6) {
64516
64732
  if (st === valueProps.found)
64517
64733
  break;
64518
64734
  if (st.type === "newline") {
@@ -64529,7 +64745,7 @@ function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: co
64529
64745
  else
64530
64746
  onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
64531
64747
  }
64532
- const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep5, null, valueProps, onError) : null;
64748
+ const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep6, null, valueProps, onError) : null;
64533
64749
  if (valueNode) {
64534
64750
  if (isBlock(value))
64535
64751
  onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
@@ -64689,7 +64905,7 @@ function resolveBlockScalar(ctx, scalar, onError) {
64689
64905
  chompStart = i + 1;
64690
64906
  }
64691
64907
  let value = "";
64692
- let sep5 = "";
64908
+ let sep6 = "";
64693
64909
  let prevMoreIndented = false;
64694
64910
  for (let i = 0; i < contentStart; ++i)
64695
64911
  value += lines[i][0].slice(trimIndent) + "\n";
@@ -64706,24 +64922,24 @@ function resolveBlockScalar(ctx, scalar, onError) {
64706
64922
  indent2 = "";
64707
64923
  }
64708
64924
  if (type === Scalar.BLOCK_LITERAL) {
64709
- value += sep5 + indent2.slice(trimIndent) + content2;
64710
- sep5 = "\n";
64925
+ value += sep6 + indent2.slice(trimIndent) + content2;
64926
+ sep6 = "\n";
64711
64927
  } else if (indent2.length > trimIndent || content2[0] === " ") {
64712
- if (sep5 === " ")
64713
- sep5 = "\n";
64714
- else if (!prevMoreIndented && sep5 === "\n")
64715
- sep5 = "\n\n";
64716
- value += sep5 + indent2.slice(trimIndent) + content2;
64717
- sep5 = "\n";
64928
+ if (sep6 === " ")
64929
+ sep6 = "\n";
64930
+ else if (!prevMoreIndented && sep6 === "\n")
64931
+ sep6 = "\n\n";
64932
+ value += sep6 + indent2.slice(trimIndent) + content2;
64933
+ sep6 = "\n";
64718
64934
  prevMoreIndented = true;
64719
64935
  } else if (content2 === "") {
64720
- if (sep5 === "\n")
64936
+ if (sep6 === "\n")
64721
64937
  value += "\n";
64722
64938
  else
64723
- sep5 = "\n";
64939
+ sep6 = "\n";
64724
64940
  } else {
64725
- value += sep5 + content2;
64726
- sep5 = " ";
64941
+ value += sep6 + content2;
64942
+ sep6 = " ";
64727
64943
  prevMoreIndented = false;
64728
64944
  }
64729
64945
  }
@@ -64897,25 +65113,25 @@ function foldLines(source) {
64897
65113
  if (!match)
64898
65114
  return source;
64899
65115
  let res = match[1];
64900
- let sep5 = " ";
65116
+ let sep6 = " ";
64901
65117
  let pos = first.lastIndex;
64902
65118
  line.lastIndex = pos;
64903
65119
  while (match = line.exec(source)) {
64904
65120
  if (match[1] === "") {
64905
- if (sep5 === "\n")
64906
- res += sep5;
65121
+ if (sep6 === "\n")
65122
+ res += sep6;
64907
65123
  else
64908
- sep5 = "\n";
65124
+ sep6 = "\n";
64909
65125
  } else {
64910
- res += sep5 + match[1];
64911
- sep5 = " ";
65126
+ res += sep6 + match[1];
65127
+ sep6 = " ";
64912
65128
  }
64913
65129
  pos = line.lastIndex;
64914
65130
  }
64915
65131
  const last = /[ \t]*(.*)/sy;
64916
65132
  last.lastIndex = pos;
64917
65133
  match = last.exec(source);
64918
- return res + sep5 + (match?.[1] ?? "");
65134
+ return res + sep6 + (match?.[1] ?? "");
64919
65135
  }
64920
65136
  function doubleQuotedValue(source, onError) {
64921
65137
  let res = "";
@@ -66532,18 +66748,18 @@ var Parser3 = class {
66532
66748
  if (this.type === "map-value-ind") {
66533
66749
  const prev = getPrevProps(this.peek(2));
66534
66750
  const start = getFirstKeyStartProps(prev);
66535
- let sep5;
66751
+ let sep6;
66536
66752
  if (scalar.end) {
66537
- sep5 = scalar.end;
66538
- sep5.push(this.sourceToken);
66753
+ sep6 = scalar.end;
66754
+ sep6.push(this.sourceToken);
66539
66755
  delete scalar.end;
66540
66756
  } else
66541
- sep5 = [this.sourceToken];
66757
+ sep6 = [this.sourceToken];
66542
66758
  const map2 = {
66543
66759
  type: "block-map",
66544
66760
  offset: scalar.offset,
66545
66761
  indent: scalar.indent,
66546
- items: [{ start, key: scalar, sep: sep5 }]
66762
+ items: [{ start, key: scalar, sep: sep6 }]
66547
66763
  };
66548
66764
  this.onKeyLine = true;
66549
66765
  this.stack[this.stack.length - 1] = map2;
@@ -66696,15 +66912,15 @@ var Parser3 = class {
66696
66912
  } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
66697
66913
  const start2 = getFirstKeyStartProps(it.start);
66698
66914
  const key = it.key;
66699
- const sep5 = it.sep;
66700
- sep5.push(this.sourceToken);
66915
+ const sep6 = it.sep;
66916
+ sep6.push(this.sourceToken);
66701
66917
  delete it.key;
66702
66918
  delete it.sep;
66703
66919
  this.stack.push({
66704
66920
  type: "block-map",
66705
66921
  offset: this.offset,
66706
66922
  indent: this.indent,
66707
- items: [{ start: start2, key, sep: sep5 }]
66923
+ items: [{ start: start2, key, sep: sep6 }]
66708
66924
  });
66709
66925
  } else if (start.length > 0) {
66710
66926
  it.sep = it.sep.concat(start, this.sourceToken);
@@ -66898,13 +67114,13 @@ var Parser3 = class {
66898
67114
  const prev = getPrevProps(parent);
66899
67115
  const start = getFirstKeyStartProps(prev);
66900
67116
  fixFlowSeqItems(fc);
66901
- const sep5 = fc.end.splice(1, fc.end.length);
66902
- sep5.push(this.sourceToken);
67117
+ const sep6 = fc.end.splice(1, fc.end.length);
67118
+ sep6.push(this.sourceToken);
66903
67119
  const map2 = {
66904
67120
  type: "block-map",
66905
67121
  offset: fc.offset,
66906
67122
  indent: fc.indent,
66907
- items: [{ start, key: fc, sep: sep5 }]
67123
+ items: [{ start, key: fc, sep: sep6 }]
66908
67124
  };
66909
67125
  this.onKeyLine = true;
66910
67126
  this.stack[this.stack.length - 1] = map2;
@@ -67085,13 +67301,13 @@ var JSON_INDENT3 = 2;
67085
67301
  var CONFIG_MODE = 384;
67086
67302
  var PRIM_BINS4 = [CAPTURE_BIN4, GATE_BIN4, POST_TOOL_USE_BIN3, SESSION_START_BIN4, SESSION_END_BIN3];
67087
67303
  function hermesHome() {
67088
- return process.env.HERMES_HOME ?? join28(homedir10(), ".hermes");
67304
+ return process.env.HERMES_HOME ?? join29(homedir10(), ".hermes");
67089
67305
  }
67090
67306
  function configPath() {
67091
- return join28(hermesHome(), "config.yaml");
67307
+ return join29(hermesHome(), "config.yaml");
67092
67308
  }
67093
67309
  function legacyShimPath() {
67094
- return join28(hermesHome(), "agent-hooks", "prim-shim.sh");
67310
+ return join29(hermesHome(), "agent-hooks", "prim-shim.sh");
67095
67311
  }
67096
67312
  function commandFor2(bin) {
67097
67313
  return stableHookCommand(bin, HERMES_ARGS);
@@ -67422,8 +67638,8 @@ function spliceHooks(raw, hooks) {
67422
67638
  const insertAt = endMarker?.index ?? raw.length;
67423
67639
  const beforeEnd = raw.slice(0, insertAt);
67424
67640
  const afterEnd = raw.slice(insertAt);
67425
- const sep5 = beforeEnd.length === 0 || beforeEnd.endsWith("\n") ? "" : newline4;
67426
- return `${beforeEnd}${sep5}${normalizedBlock}${afterEnd}`;
67641
+ const sep6 = beforeEnd.length === 0 || beforeEnd.endsWith("\n") ? "" : newline4;
67642
+ return `${beforeEnd}${sep6}${normalizedBlock}${afterEnd}`;
67427
67643
  }
67428
67644
  const hooksRemovalEnd = doc.get("hooks", true)?.range?.[2] ?? loc.end;
67429
67645
  const hasHooks = reconcileHooksDocument(doc, hooks);
@@ -67448,8 +67664,8 @@ function setAutoAccept(raw) {
67448
67664
  throw new Error("hooks_auto_accept must be a block-style boolean value");
67449
67665
  }
67450
67666
  const newline3 = raw.includes("\r\n") ? "\r\n" : "\n";
67451
- const sep5 = raw.length === 0 || raw.endsWith("\n") ? "" : newline3;
67452
- return `${raw}${sep5}hooks_auto_accept: true${newline3}`;
67667
+ const sep6 = raw.length === 0 || raw.endsWith("\n") ? "" : newline3;
67668
+ return `${raw}${sep6}hooks_auto_accept: true${newline3}`;
67453
67669
  }
67454
67670
  function mergeKeepsYamlValid(before, after) {
67455
67671
  try {
@@ -68122,7 +68338,7 @@ function classifyCodexHooks(statuses, uncoveredWorktree = null, capturedAt, host
68122
68338
  }
68123
68339
  return {
68124
68340
  name: "codex-hooks",
68125
- status: capturedAt === void 0 || host?.trust === "review-required" || host?.trust === "disabled" ? "warn" : "ok",
68341
+ status: capturedAt === void 0 || host?.trust !== "trusted" ? "warn" : "ok",
68126
68342
  detail: host && host.trust !== "unknown" ? `installed; ${capturedAt === void 0 ? "conversation capture unverified" : `conversation capture observed ${new Date(capturedAt).toISOString()}`}; ${host.trust === "trusted" ? "Codex reports hooks enabled and trusted" : codexHostGuidance(host)}` : capturedAt === void 0 ? "installed; conversation capture unverified; Codex trust unknown \u2014 verify with `/hooks`" : `installed; conversation capture observed ${new Date(capturedAt).toISOString()}; current trust unknown`
68127
68343
  };
68128
68344
  }
@@ -68412,12 +68628,42 @@ function checkPreflightHosts() {
68412
68628
  };
68413
68629
  });
68414
68630
  }
68631
+ function checkDemoPause(root, now = Date.now()) {
68632
+ const pause = root ? readDemoPause(root) : void 0;
68633
+ if (!root || !pause || healDemoPause(root, pause, { now })) return [];
68634
+ const minutes = String(Math.ceil((pause.until - now) / 6e4));
68635
+ return [
68636
+ {
68637
+ name: "demo-pause",
68638
+ status: "warn",
68639
+ detail: pause.ending ? `capture resumes with your next prompt (onboarding demo finished), or in ${minutes}m` : `capture paused for the onboarding demo; it resumes when the demo ends, or in ${minutes}m`
68640
+ }
68641
+ ];
68642
+ }
68643
+ function captureReadiness(agent, checks, root, now = Date.now()) {
68644
+ const name2 = agent === "claude" ? "feedback-hooks" : `${agent}-hooks`;
68645
+ const check = checks.find((item) => item.name === name2);
68646
+ const hooks = check?.status === "fail" ? "blocked" : check?.status === "ok" && !check.detail.startsWith("not installed") ? "ready" : "unverified";
68647
+ const observedAt = root ? lastConversationCaptured(root, agent === "claude" ? "claude_code" : agent) : void 0;
68648
+ const pause = root ? readDemoPause(root) : void 0;
68649
+ const active = root ? isRepoActiveForCapture(root) : false;
68650
+ const state = pause && pause.until > now ? "paused" : !active ? "off" : hooks === "blocked" ? "blocked" : hooks === "ready" && observedAt !== void 0 ? "observed" : "unverified";
68651
+ return {
68652
+ agent,
68653
+ state,
68654
+ hooks,
68655
+ ...state === "paused" ? { resumeOnNextPrompt: pause?.ending === true } : {},
68656
+ ...observedAt === void 0 ? {} : { observedAt },
68657
+ detail: state === "paused" ? pause?.ending ? "demo finished; capture resumes on the next trusted user-prompt hook" : "capture paused for the fictional demo" : state === "off" ? "capture is disabled for this repository" : check?.detail ?? "agent hook execution has not been verified"
68658
+ };
68659
+ }
68415
68660
  async function independentChecks() {
68416
68661
  const backend = await checkBackend();
68417
68662
  const firing = inspectFiringHere();
68418
68663
  return {
68419
68664
  before: [checkAuth()],
68420
68665
  after: [
68666
+ ...checkDemoPause(gitToplevel()),
68421
68667
  await checkJournalOrganization(),
68422
68668
  checkFeedbackHooks(),
68423
68669
  ...await checkAgentHooks(),
@@ -68450,6 +68696,7 @@ function icon(status2) {
68450
68696
  async function runDoctor(options, probes) {
68451
68697
  const checks = await collectChecks(options, probes);
68452
68698
  const { json, exitCode } = classifyDoctor(checks);
68699
+ const capture = options.agent === "claude" || options.agent === "codex" || options.agent === "cursor" || options.agent === "hermes" ? captureReadiness(options.agent, checks, gitToplevel()) : void 0;
68453
68700
  const headline = json.status === "ok" ? "\u2713 healthy" : json.status === "warn" ? "\u26A0 degraded" : "\u2717 unhealthy";
68454
68701
  process.stderr.write(`[prim] doctor: ${headline}
68455
68702
  `);
@@ -68458,7 +68705,7 @@ async function runDoctor(options, probes) {
68458
68705
  process.stderr.write(` ${icon(c.status)} ${c.name.padEnd(13)} ${c.detail}
68459
68706
  `);
68460
68707
  }
68461
- console.log(JSON.stringify(json, null, 2));
68708
+ console.log(JSON.stringify({ ...json, ...capture ? { capture } : {} }, null, 2));
68462
68709
  if (exitCode !== 0 && !process.exitCode) {
68463
68710
  process.exitCode = exitCode;
68464
68711
  }
@@ -68478,7 +68725,7 @@ function registerDoctorCommands(program3, dependencies = {}) {
68478
68725
  import { createHash as createHash12 } from "crypto";
68479
68726
  import { existsSync as existsSync21, lstatSync as lstatSync11, readFileSync as readFileSync22, readdirSync as readdirSync9, rmdirSync as rmdirSync3, unlinkSync as unlinkSync6 } from "fs";
68480
68727
  import { homedir as homedir11 } from "os";
68481
- import { dirname as dirname14, join as join29, resolve as resolve11 } from "path";
68728
+ import { dirname as dirname14, join as join30, resolve as resolve11 } from "path";
68482
68729
  import { fileURLToPath as fileURLToPath4 } from "url";
68483
68730
  var __dirname4 = dirname14(fileURLToPath4(import.meta.url));
68484
68731
  var SKILL_NAME = "primitive-gameplan";
@@ -68497,13 +68744,13 @@ ${END}`;
68497
68744
  function packageRoot2() {
68498
68745
  let directory = __dirname4;
68499
68746
  while (directory !== dirname14(directory)) {
68500
- if (existsSync21(join29(directory, "assets", SKILL_NAME, "SKILL.md"))) return directory;
68747
+ if (existsSync21(join30(directory, "assets", SKILL_NAME, "SKILL.md"))) return directory;
68501
68748
  directory = dirname14(directory);
68502
68749
  }
68503
68750
  throw new Error("Primitive gameplan assets are missing from this CLI package");
68504
68751
  }
68505
68752
  function packageVersion2(root) {
68506
- const parsed = JSON.parse(readFileSync22(join29(root, "package.json"), "utf8"));
68753
+ const parsed = JSON.parse(readFileSync22(join30(root, "package.json"), "utf8"));
68507
68754
  if (typeof parsed.version !== "string") throw new Error("CLI package version is missing");
68508
68755
  return parsed.version;
68509
68756
  }
@@ -68513,15 +68760,15 @@ function sha2563(content2) {
68513
68760
  function pathsFor(cwd) {
68514
68761
  const root = gitToplevel(cwd);
68515
68762
  if (root === null) throw new Error("Run prim gameplan from a Git worktree");
68516
- const skillDir = join29(root, ".agents", "skills", SKILL_NAME);
68517
- const codexHome = process.env.CODEX_HOME?.trim() ? resolve11(process.env.CODEX_HOME) : join29(homedir11(), ".codex");
68763
+ const skillDir = join30(root, ".agents", "skills", SKILL_NAME);
68764
+ const codexHome = process.env.CODEX_HOME?.trim() ? resolve11(process.env.CODEX_HOME) : join30(homedir11(), ".codex");
68518
68765
  return {
68519
68766
  root,
68520
68767
  skillDir,
68521
- manifest: join29(skillDir, MANIFEST_NAME),
68522
- agents: join29(root, "AGENTS.md"),
68523
- agentsOverride: join29(root, "AGENTS.override.md"),
68524
- userHooks: join29(codexHome, "hooks.json")
68768
+ manifest: join30(skillDir, MANIFEST_NAME),
68769
+ agents: join30(root, "AGENTS.md"),
68770
+ agentsOverride: join30(root, "AGENTS.override.md"),
68771
+ userHooks: join30(codexHome, "hooks.json")
68525
68772
  };
68526
68773
  }
68527
68774
  function readRegularFile(path9) {
@@ -68586,9 +68833,9 @@ function removeBlock(content2, separator) {
68586
68833
  function publicSkillPath(paths) {
68587
68834
  const codexHome = dirname14(paths.userHooks);
68588
68835
  const candidates = [
68589
- join29(paths.root, ".agents", "skills", "write-gameplan", "SKILL.md"),
68590
- join29(codexHome, "skills", "write-gameplan", "SKILL.md"),
68591
- join29(homedir11(), ".agents", "skills", "write-gameplan", "SKILL.md")
68836
+ join30(paths.root, ".agents", "skills", "write-gameplan", "SKILL.md"),
68837
+ join30(codexHome, "skills", "write-gameplan", "SKILL.md"),
68838
+ join30(homedir11(), ".agents", "skills", "write-gameplan", "SKILL.md")
68592
68839
  ];
68593
68840
  for (const path9 of candidates) {
68594
68841
  try {
@@ -68602,7 +68849,7 @@ function publicSkillPath(paths) {
68602
68849
  function assetContents() {
68603
68850
  const root = packageRoot2();
68604
68851
  return Object.fromEntries(
68605
- ASSET_FILES.map((file) => [file, readFileSync22(join29(root, "assets", SKILL_NAME, file), "utf8")])
68852
+ ASSET_FILES.map((file) => [file, readFileSync22(join30(root, "assets", SKILL_NAME, file), "utf8")])
68606
68853
  );
68607
68854
  }
68608
68855
  function markedHookCommands(settings) {
@@ -68651,7 +68898,7 @@ function checkOwnedFiles(paths, manifest) {
68651
68898
  }
68652
68899
  if (manifest === null) return;
68653
68900
  for (const file of ASSET_FILES) {
68654
- const path9 = join29(paths.skillDir, file);
68901
+ const path9 = join30(paths.skillDir, file);
68655
68902
  const current = readRegularFile(path9);
68656
68903
  if (current !== null && sha2563(current) !== manifest.files[file] && sha2563(current) !== manifest.previousFiles?.[file]) {
68657
68904
  throw new Error(`Refusing modified companion file at ${path9}`);
@@ -68700,7 +68947,7 @@ function install(cwd) {
68700
68947
  ensureParent: true
68701
68948
  });
68702
68949
  for (const file of ASSET_FILES) {
68703
- const path9 = join29(paths.skillDir, file);
68950
+ const path9 = join30(paths.skillDir, file);
68704
68951
  if (readRegularFile(path9) !== assets[file]) {
68705
68952
  atomicWriteFile(path9, assets[file], { ensureParent: true });
68706
68953
  }
@@ -68720,7 +68967,7 @@ function status(cwd) {
68720
68967
  const publicSkill = publicSkillPath(paths);
68721
68968
  const files = Object.fromEntries(
68722
68969
  ASSET_FILES.map((file) => {
68723
- const current = readRegularFile(join29(paths.skillDir, file));
68970
+ const current = readRegularFile(join30(paths.skillDir, file));
68724
68971
  return [
68725
68972
  file,
68726
68973
  current !== null && manifest !== null && sha2563(current) === manifest.files[file]
@@ -68754,7 +69001,7 @@ function uninstall(cwd, removeSharedHook) {
68754
69001
  checkOwnedFiles(paths, manifest);
68755
69002
  const expected = /* @__PURE__ */ new Set(["SKILL.md", "claude-hooks.json", "scripts", MANIFEST_NAME]);
68756
69003
  const extras = readdirSync9(paths.skillDir).filter((entry) => !expected.has(entry));
68757
- const scriptsPath = join29(paths.skillDir, "scripts");
69004
+ const scriptsPath = join30(paths.skillDir, "scripts");
68758
69005
  if (existsSync21(scriptsPath)) {
68759
69006
  extras.push(...readdirSync9(scriptsPath).filter((entry) => entry !== "activate.mjs"));
68760
69007
  }
@@ -68773,7 +69020,7 @@ function uninstall(cwd, removeSharedHook) {
68773
69020
  }
68774
69021
  }
68775
69022
  for (const file of ASSET_FILES) {
68776
- const path9 = join29(paths.skillDir, file);
69023
+ const path9 = join30(paths.skillDir, file);
68777
69024
  if (existsSync21(path9)) unlinkSync6(path9);
68778
69025
  }
68779
69026
  unlinkSync6(paths.manifest);
@@ -68831,11 +69078,11 @@ function registerGameplanCommands(program3) {
68831
69078
 
68832
69079
  // src/commands/moves.ts
68833
69080
  import { existsSync as existsSync23, mkdirSync as mkdirSync13, unlinkSync as unlinkSync8, writeFileSync as writeFileSync9 } from "fs";
68834
- import { join as join32 } from "path";
69081
+ import { join as join33 } from "path";
68835
69082
 
68836
69083
  // src/flusher.ts
68837
69084
  import { createReadStream, renameSync as renameSync6, statSync as statSync6, unlinkSync as unlinkSync7 } from "fs";
68838
- import { dirname as dirname16, join as join31 } from "path";
69085
+ import { dirname as dirname16, join as join32 } from "path";
68839
69086
 
68840
69087
  // src/dead-letter.ts
68841
69088
  import { createHash as createHash13, randomBytes as randomBytes7 } from "crypto";
@@ -68852,16 +69099,16 @@ import {
68852
69099
  rmSync as rmSync8,
68853
69100
  writeFileSync as writeFileSync8
68854
69101
  } from "fs";
68855
- import { dirname as dirname15, join as join30 } from "path";
69102
+ import { dirname as dirname15, join as join31 } from "path";
68856
69103
  var DIRECTORY_MODE4 = 448;
68857
69104
  var FILE_MODE3 = 384;
68858
69105
  var DEAD_LETTER_DIRNAME = "dead-letter";
68859
69106
  function deadLetterDirectoryForRotation(flushingPath) {
68860
- return join30(dirname15(flushingPath), DEAD_LETTER_DIRNAME);
69107
+ return join31(dirname15(flushingPath), DEAD_LETTER_DIRNAME);
68861
69108
  }
68862
69109
  function deadLetterPathForRawLine(flushingPath, rawLine) {
68863
69110
  const quarantineId = createHash13("sha256").update(rawLine).digest("hex");
68864
- return join30(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
69111
+ return join31(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
68865
69112
  }
68866
69113
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
68867
69114
  const directory = deadLetterDirectoryForRotation(flushingPath);
@@ -68875,7 +69122,7 @@ function persistDeadLetter(directory, path9, quarantineId, record3, persistDirec
68875
69122
  persistDirectory(directory);
68876
69123
  return;
68877
69124
  }
68878
- const temporaryPath = join30(
69125
+ const temporaryPath = join31(
68879
69126
  directory,
68880
69127
  `.${quarantineId}.${String(process.pid)}.${randomBytes7(8).toString("hex")}.tmp`
68881
69128
  );
@@ -68907,7 +69154,7 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
68907
69154
  reason,
68908
69155
  move
68909
69156
  };
68910
- const path9 = join30(directory, `${record3.quarantineId}.json`);
69157
+ const path9 = join31(directory, `${record3.quarantineId}.json`);
68911
69158
  persistDeadLetter(directory, path9, record3.quarantineId, record3, persistDirectory);
68912
69159
  return record3;
68913
69160
  }
@@ -69331,7 +69578,7 @@ async function flushOnce() {
69331
69578
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
69332
69579
  }
69333
69580
  var flushInFlight;
69334
- var FLUSH_LOCK_PATH = join31(dirname16(JOURNAL_DIR), ".flush.lock");
69581
+ var FLUSH_LOCK_PATH = join32(dirname16(JOURNAL_DIR), ".flush.lock");
69335
69582
  var FLUSH_LOCK_TIMEOUT_MS = 250;
69336
69583
  function isFlushLockContended(error) {
69337
69584
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -69463,18 +69710,18 @@ function registerMovesCommands(program3) {
69463
69710
  }
69464
69711
  });
69465
69712
  moves.command("bind").description("Pin the current directory to an org via .prim/workspace.json").requiredOption("--orgId <orgId>", "Convex organization id").action((opts) => {
69466
- const dir = join32(process.cwd(), ".prim");
69713
+ const dir = join33(process.cwd(), ".prim");
69467
69714
  if (!existsSync23(dir)) {
69468
69715
  mkdirSync13(dir, { recursive: true, mode: DIR_MODE });
69469
69716
  }
69470
- const file = join32(process.cwd(), WORKSPACE_FILE);
69717
+ const file = join33(process.cwd(), WORKSPACE_FILE);
69471
69718
  writeFileSync9(file, JSON.stringify({ orgId: opts.orgId, boundAt: Date.now() }, null, 2), {
69472
69719
  mode: FILE_MODE4
69473
69720
  });
69474
69721
  console.log(`[prim] bound ${process.cwd()} to org ${opts.orgId}`);
69475
69722
  });
69476
69723
  moves.command("drop").description("Remove the .prim/workspace.json binding from the cwd").action(() => {
69477
- const file = join32(process.cwd(), WORKSPACE_FILE);
69724
+ const file = join33(process.cwd(), WORKSPACE_FILE);
69478
69725
  if (!existsSync23(file)) {
69479
69726
  console.log("[prim] no workspace binding in cwd");
69480
69727
  return;
@@ -69560,13 +69807,13 @@ import {
69560
69807
  unlinkSync as unlinkSync9,
69561
69808
  writeFileSync as writeFileSync10
69562
69809
  } from "fs";
69563
- import { join as join34 } from "path";
69810
+ import { join as join35 } from "path";
69564
69811
 
69565
69812
  // src/binding.ts
69566
69813
  import { existsSync as existsSync24, readFileSync as readFileSync23 } from "fs";
69567
- import { dirname as dirname17, join as join33 } from "path";
69814
+ import { dirname as dirname17, join as join34 } from "path";
69568
69815
  var PRIM_CONFIG_DIR = primConfigDirectory();
69569
- var SESSIONS_DIR = join33(PRIM_CONFIG_DIR, "sessions");
69816
+ var SESSIONS_DIR = join34(PRIM_CONFIG_DIR, "sessions");
69570
69817
 
69571
69818
  // src/commands/session.ts
69572
69819
  var DIR_MODE2 = 448;
@@ -69577,7 +69824,7 @@ function ensureDir() {
69577
69824
  }
69578
69825
  }
69579
69826
  function markerPath(sessionId) {
69580
- return join34(SESSIONS_DIR, `${sessionId}.json`);
69827
+ return join35(SESSIONS_DIR, `${sessionId}.json`);
69581
69828
  }
69582
69829
  function registerSessionCommands(program3) {
69583
69830
  const session = program3.command("session").description("Decision Event Pipeline \u2014 session binding markers");
@@ -69605,7 +69852,7 @@ function registerSessionCommands(program3) {
69605
69852
  for (const f of files) {
69606
69853
  const sessionId = f.replace(/\.json$/, "");
69607
69854
  try {
69608
- const m = JSON.parse(readFileSync24(join34(SESSIONS_DIR, f), "utf-8"));
69855
+ const m = JSON.parse(readFileSync24(join35(SESSIONS_DIR, f), "utf-8"));
69609
69856
  console.log(`${sessionId} org=${m.orgId}`);
69610
69857
  } catch {
69611
69858
  }
@@ -69624,9 +69871,564 @@ function registerSessionCommands(program3) {
69624
69871
 
69625
69872
  // src/commands/setup.ts
69626
69873
  import { spawnSync as spawnSync2 } from "child_process";
69627
- import { existsSync as existsSync26, readFileSync as readFileSync25 } from "fs";
69628
- import { join as join35 } from "path";
69874
+ import { existsSync as existsSync29, readFileSync as readFileSync28 } from "fs";
69875
+ import { homedir as homedir15 } from "os";
69876
+ import { join as join39, resolve as resolve14, sep as sep5 } from "path";
69877
+
69878
+ // src/commands/claude-plugin.ts
69879
+ import { createHash as createHash16 } from "crypto";
69880
+ import {
69881
+ constants as constants8,
69882
+ closeSync as closeSync8,
69883
+ existsSync as existsSync28,
69884
+ fstatSync as fstatSync4,
69885
+ lstatSync as lstatSync14,
69886
+ mkdirSync as mkdirSync15,
69887
+ openSync as openSync8,
69888
+ readFileSync as readFileSync27,
69889
+ readSync as readSync4,
69890
+ readdirSync as readdirSync13,
69891
+ realpathSync as realpathSync8,
69892
+ rmSync as rmSync9,
69893
+ rmdirSync as rmdirSync6
69894
+ } from "fs";
69895
+ import { homedir as homedir14 } from "os";
69896
+ import { dirname as dirname20, isAbsolute as isAbsolute11, join as join38, relative as relative4, resolve as resolve13, sep as sep4 } from "path";
69897
+ import { fileURLToPath as fileURLToPath6 } from "url";
69898
+
69899
+ // src/commands/skill.ts
69900
+ import { createHash as createHash15 } from "crypto";
69901
+ import {
69902
+ constants as constants7,
69903
+ closeSync as closeSync7,
69904
+ existsSync as existsSync27,
69905
+ fstatSync as fstatSync3,
69906
+ lstatSync as lstatSync13,
69907
+ openSync as openSync7,
69908
+ readFileSync as readFileSync26,
69909
+ readSync as readSync3,
69910
+ readdirSync as readdirSync12,
69911
+ rmdirSync as rmdirSync5,
69912
+ unlinkSync as unlinkSync11
69913
+ } from "fs";
69914
+ import { homedir as homedir13 } from "os";
69915
+ import { dirname as dirname19, join as join37, resolve as resolve12 } from "path";
69916
+ import { fileURLToPath as fileURLToPath5 } from "url";
69917
+
69918
+ // src/commands/welcome-skill.ts
69919
+ import { createHash as createHash14 } from "crypto";
69920
+ import { existsSync as existsSync26, lstatSync as lstatSync12, readFileSync as readFileSync25, readdirSync as readdirSync11, rmdirSync as rmdirSync4, unlinkSync as unlinkSync10 } from "fs";
69921
+ import { homedir as homedir12 } from "os";
69922
+ import { dirname as dirname18, join as join36 } from "path";
69923
+ var WELCOME_SKILL_SOURCE = join36("skills", "prim-welcome", "SKILL.md");
69924
+ var OWNER = "@primitive.ai/prim";
69925
+ var MANIFEST = ".prim-owned.json";
69926
+ var digest2 = (content2) => createHash14("sha256").update(content2).digest("hex");
69927
+ var manifestPath = (skillPath) => join36(dirname18(skillPath), MANIFEST);
69928
+ function leafKind(path9) {
69929
+ try {
69930
+ return lstatSync12(path9).isFile() ? "file" : "foreign";
69931
+ } catch (error) {
69932
+ if (error.code === "ENOENT") return "missing";
69933
+ throw error;
69934
+ }
69935
+ }
69936
+ function codexWelcomeSkillPath() {
69937
+ return join36(homedir12(), ".agents", "skills", "prim-welcome", "SKILL.md");
69938
+ }
69939
+ function welcomeSkillStatus(skillPath) {
69940
+ const skillKind = leafKind(skillPath);
69941
+ const manifestKind = leafKind(manifestPath(skillPath));
69942
+ let manifest;
69943
+ if (manifestKind === "file")
69944
+ try {
69945
+ const value = JSON.parse(readFileSync25(manifestPath(skillPath), "utf8"));
69946
+ if (value.version === 1 && value.owner === OWNER && /^[a-f0-9]{64}$/u.test(value.contentSha256 ?? ""))
69947
+ manifest = value;
69948
+ } catch {
69949
+ }
69950
+ const content2 = skillKind === "file" ? readFileSync25(skillPath, "utf8") : void 0;
69951
+ const owned = manifest !== void 0;
69952
+ const installed = manifest !== void 0 && content2 !== void 0 && digest2(content2) === manifest.contentSha256;
69953
+ return {
69954
+ installed,
69955
+ owned,
69956
+ edited: owned && content2 !== void 0 && !installed,
69957
+ target: skillPath,
69958
+ content: content2,
69959
+ unsafe: skillKind === "foreign" || manifestKind === "foreign"
69960
+ };
69961
+ }
69962
+ function installWelcomeSkill(skillPath, content2, dryRun = false) {
69963
+ const status2 = welcomeSkillStatus(skillPath);
69964
+ const foreignManifest = existsSync26(manifestPath(skillPath)) && !status2.owned;
69965
+ if (status2.unsafe || foreignManifest || status2.edited || !status2.owned && status2.content !== void 0 && status2.content !== content2) {
69966
+ console.error(`Refusing to overwrite a foreign or edited welcome skill at ${skillPath}`);
69967
+ return 1;
69968
+ }
69969
+ if (status2.installed && status2.content === content2) return 0;
69970
+ if (dryRun) {
69971
+ console.log(`Would write welcome skill to ${skillPath}`);
69972
+ return 0;
69973
+ }
69974
+ const manifest = { version: 1, owner: OWNER, contentSha256: digest2(content2) };
69975
+ atomicWriteFile(skillPath, content2, { ensureParent: true });
69976
+ atomicWriteFile(manifestPath(skillPath), `${JSON.stringify(manifest, null, 2)}
69977
+ `, {
69978
+ ensureParent: true
69979
+ });
69980
+ console.log(`Installed prim-welcome skill at ${skillPath}`);
69981
+ return 0;
69982
+ }
69983
+ function uninstallWelcomeSkill(skillPath) {
69984
+ const status2 = welcomeSkillStatus(skillPath);
69985
+ if (status2.unsafe) {
69986
+ console.error(`Refusing to remove a non-file welcome skill at ${skillPath}`);
69987
+ return 1;
69988
+ }
69989
+ if (!status2.owned) return 0;
69990
+ if (status2.edited) {
69991
+ console.error(`Refusing to remove an edited welcome skill at ${skillPath}`);
69992
+ return 1;
69993
+ }
69994
+ if (existsSync26(skillPath)) unlinkSync10(skillPath);
69995
+ unlinkSync10(manifestPath(skillPath));
69996
+ if (readdirSync11(dirname18(skillPath)).length === 0) rmdirSync4(dirname18(skillPath));
69997
+ console.log(`Removed prim-welcome skill from ${skillPath}`);
69998
+ return 0;
69999
+ }
70000
+
70001
+ // src/commands/skill.ts
70002
+ var __dirname5 = dirname19(fileURLToPath5(import.meta.url));
70003
+ var SKILL_BEGIN = "<!-- BEGIN PRIM SKILL v1 -->";
70004
+ var SKILL_END = "<!-- END PRIM SKILL v1 -->";
70005
+ var CODEX_GUIDANCE_LIMIT_BYTES = 1024 * 1024;
70006
+ var CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES = 32 * 1024;
70007
+ var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
70008
+ var SKILL_END_BUFFER = Buffer.from(SKILL_END);
70009
+ var TARGET_CANDIDATES = [
70010
+ "CLAUDE.md",
70011
+ "AGENTS.md",
70012
+ ".hermes.md",
70013
+ ".cursor/rules",
70014
+ ".windsurfrules",
70015
+ ".github/instructions/primitive.md"
70016
+ ];
70017
+ var DEFAULT_TARGET = "CLAUDE.md";
70018
+ var AGENT_TARGET = {
70019
+ claude: "CLAUDE.md",
70020
+ codex: "AGENTS.md",
70021
+ hermes: ".hermes.md"
70022
+ };
70023
+ var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
70024
+ var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
70025
+ function sha2564(content2) {
70026
+ return createHash15("sha256").update(content2).digest("hex");
70027
+ }
70028
+ function cursorSkillDirectory(cwd, scope) {
70029
+ const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
70030
+ return join37(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
70031
+ }
70032
+ function cursorSkillPaths(cwd, scope) {
70033
+ const directory = cursorSkillDirectory(cwd, scope);
70034
+ return {
70035
+ directory,
70036
+ skill: join37(directory, "SKILL.md"),
70037
+ manifest: join37(directory, CURSOR_SKILL_MANIFEST)
70038
+ };
70039
+ }
70040
+ function readCursorSkillManifest(path9) {
70041
+ try {
70042
+ const value = JSON.parse(readFileSync26(path9, "utf8"));
70043
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
70044
+ const record3 = value;
70045
+ if (record3.version !== 1 || record3.owner !== CURSOR_SKILL_OWNER || typeof record3.contentSha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record3.contentSha256)) {
70046
+ return;
70047
+ }
70048
+ return record3;
70049
+ } catch {
70050
+ return;
70051
+ }
70052
+ }
70053
+ function cursorSkillStatus(cwd, scope) {
70054
+ const paths = cursorSkillPaths(cwd, scope);
70055
+ const manifest = readCursorSkillManifest(paths.manifest);
70056
+ const content2 = existsSync27(paths.skill) ? readFileSync26(paths.skill, "utf8") : void 0;
70057
+ const owned = manifest !== void 0;
70058
+ const installed = owned && content2 !== void 0 && sha2564(content2) === manifest.contentSha256;
70059
+ return {
70060
+ installed,
70061
+ owned,
70062
+ edited: owned && content2 !== void 0 && !installed,
70063
+ target: paths.skill
70064
+ };
70065
+ }
70066
+ function validCursorSkillScope(scope) {
70067
+ if (scope === void 0 || scope === "project" || scope === "user") return true;
70068
+ console.error(`Unknown --scope "${scope}" (expected user or project)`);
70069
+ return false;
70070
+ }
70071
+ function installCursorSkill(cwd, opts) {
70072
+ const paths = cursorSkillPaths(cwd, opts.scope);
70073
+ const status2 = cursorSkillStatus(cwd, opts.scope);
70074
+ const manifestExists = existsSync27(paths.manifest);
70075
+ const skillExists = existsSync27(paths.skill);
70076
+ if (manifestExists && !status2.owned || !manifestExists && skillExists || status2.edited) {
70077
+ console.error(`Refusing to overwrite a foreign or edited Cursor skill at ${paths.skill}`);
70078
+ return 1;
70079
+ }
70080
+ const content2 = loadSkill();
70081
+ const manifest = {
70082
+ version: 1,
70083
+ owner: CURSOR_SKILL_OWNER,
70084
+ contentSha256: sha2564(content2)
70085
+ };
70086
+ if (status2.installed && readFileSync26(paths.skill, "utf8") === content2) {
70087
+ console.log(`No changes \u2014 Cursor skill already up to date at ${paths.skill}`);
70088
+ return 0;
70089
+ }
70090
+ if (opts.dryRun) {
70091
+ const existing = skillExists ? readFileSync26(paths.skill, "utf8") : "";
70092
+ process.stdout.write(createPatch(paths.skill, existing, content2, "current", "proposed"));
70093
+ return 0;
70094
+ }
70095
+ atomicWriteFile(paths.skill, content2, { ensureParent: true });
70096
+ atomicWriteFile(paths.manifest, `${JSON.stringify(manifest, null, 2)}
70097
+ `, { ensureParent: true });
70098
+ console.log(`Installed Cursor skill at ${paths.skill}`);
70099
+ return 0;
70100
+ }
70101
+ function uninstallCursorSkill(cwd, scope) {
70102
+ const paths = cursorSkillPaths(cwd, scope);
70103
+ const status2 = cursorSkillStatus(cwd, scope);
70104
+ if (!status2.owned) {
70105
+ console.log(`No Primitive-owned Cursor skill at ${paths.skill}`);
70106
+ return 0;
70107
+ }
70108
+ if (status2.edited) {
70109
+ console.error(`Refusing to remove an edited Cursor skill at ${paths.skill}`);
70110
+ return 1;
70111
+ }
70112
+ if (existsSync27(paths.skill)) unlinkSync11(paths.skill);
70113
+ if (existsSync27(paths.manifest)) unlinkSync11(paths.manifest);
70114
+ try {
70115
+ if (readdirSync12(paths.directory).length === 0) rmdirSync5(paths.directory);
70116
+ } catch {
70117
+ }
70118
+ console.log(`Removed Primitive-owned Cursor skill from ${paths.skill}`);
70119
+ return 0;
70120
+ }
70121
+ function userTargetFor(agent) {
70122
+ if (agent === "claude") return join37(homedir13(), ".claude", "CLAUDE.md");
70123
+ if (agent === "codex") {
70124
+ const home = process.env.CODEX_HOME?.trim() ? resolve12(process.env.CODEX_HOME) : join37(homedir13(), ".codex");
70125
+ return join37(home, "AGENTS.md");
70126
+ }
70127
+ if (agent === "hermes") {
70128
+ return join37(process.env.HERMES_HOME ?? join37(homedir13(), ".hermes"), ".hermes.md");
70129
+ }
70130
+ return null;
70131
+ }
70132
+ function loadSkill(file = "SKILL.md") {
70133
+ let dir = __dirname5;
70134
+ while (dir !== dirname19(dir)) {
70135
+ const p = resolve12(dir, file);
70136
+ if (existsSync27(p)) return readFileSync26(p, "utf-8");
70137
+ dir = dirname19(dir);
70138
+ }
70139
+ throw new Error(`${file} not found in package`);
70140
+ }
70141
+ function detectTargets(cwd) {
70142
+ return TARGET_CANDIDATES.filter((p) => existsSync27(resolve12(cwd, p)));
70143
+ }
70144
+ function detectNewline(content2) {
70145
+ return content2.includes("\r\n") ? "\r\n" : "\n";
70146
+ }
70147
+ function composeBlock(skill, eol) {
70148
+ const body = skill.replace(/\r?\n/g, eol);
70149
+ return `${SKILL_BEGIN}${eol}${body}${eol}${SKILL_END}`;
70150
+ }
70151
+ function applyBlock(existing, block, eol) {
70152
+ const b = existing.indexOf(SKILL_BEGIN);
70153
+ const e = existing.indexOf(SKILL_END);
70154
+ if (b !== -1 && e !== -1) {
70155
+ return existing.slice(0, b) + block + existing.slice(e + SKILL_END.length);
70156
+ }
70157
+ if (existing.length === 0) return `${block}${eol}`;
70158
+ const sep6 = existing.endsWith(eol) ? "" : eol;
70159
+ return `${existing}${sep6}${block}${eol}`;
70160
+ }
70161
+ function removeBlock2(existing) {
70162
+ const b = existing.indexOf(SKILL_BEGIN);
70163
+ const e = existing.indexOf(SKILL_END);
70164
+ if (b === -1 || e === -1) return null;
70165
+ const out = existing.slice(0, b) + existing.slice(e + SKILL_END.length);
70166
+ return out.replace(/(\r?\n){2,}$/, "$1");
70167
+ }
70168
+ function atomicWrite5(target, content2) {
70169
+ atomicWriteFile(target, content2, { ensureParent: true });
70170
+ }
70171
+ function resolveTarget(cwd, opts) {
70172
+ if (opts.scope && opts.scope !== "user" && opts.scope !== "project") {
70173
+ console.error(`Unknown --scope "${opts.scope}" (expected user or project)`);
70174
+ return null;
70175
+ }
70176
+ if (opts.target) return resolve12(cwd, opts.target);
70177
+ if (opts.scope === "user") {
70178
+ if (!opts.agent) {
70179
+ console.error("--scope user requires --agent (claude, codex, cursor, or hermes)");
70180
+ return null;
70181
+ }
70182
+ const userTarget = userTargetFor(opts.agent);
70183
+ if (userTarget) return userTarget;
70184
+ console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
70185
+ return null;
70186
+ }
70187
+ if (opts.agent) {
70188
+ const mapped = AGENT_TARGET[opts.agent];
70189
+ if (typeof mapped === "string") return resolve12(cwd, mapped);
70190
+ console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
70191
+ return null;
70192
+ }
70193
+ const matches = detectTargets(cwd);
70194
+ if (matches.length === 0) return resolve12(cwd, DEFAULT_TARGET);
70195
+ if (matches.length === 1) return resolve12(cwd, matches[0]);
70196
+ console.error("Multiple rules files detected. Use --target to disambiguate:");
70197
+ for (const m of matches) console.error(` ${m}`);
70198
+ return null;
70199
+ }
70200
+ function runInstall(cwd, opts) {
70201
+ if (opts.agent === "claude" && !opts.target) return installClaudePlugin(cwd, opts);
70202
+ if (opts.agent === "cursor" && !opts.target) {
70203
+ if (!validCursorSkillScope(opts.scope)) return 1;
70204
+ return installCursorSkill(cwd, opts);
70205
+ }
70206
+ const target = resolveTarget(cwd, opts);
70207
+ if (target === null) return 1;
70208
+ const existing = existsSync27(target) ? readFileSync26(target, "utf-8") : "";
70209
+ const eol = existing ? detectNewline(existing) : "\n";
70210
+ const block = composeBlock(loadSkill(), eol);
70211
+ const next = applyBlock(existing, block, eol);
70212
+ const installCodexWelcome = () => opts.agent === "codex" && opts.scope === "user" && !opts.target ? installWelcomeSkill(codexWelcomeSkillPath(), loadSkill(WELCOME_SKILL_SOURCE), opts.dryRun) : 0;
70213
+ if (next === existing) {
70214
+ if (installCodexWelcome() !== 0) return 1;
70215
+ console.log("No changes \u2014 skill block already up to date.");
70216
+ return 0;
70217
+ }
70218
+ if (opts.dryRun) {
70219
+ if (installCodexWelcome() !== 0) return 1;
70220
+ process.stdout.write(createPatch(target, existing, next, "current", "proposed"));
70221
+ return 0;
70222
+ }
70223
+ if (installCodexWelcome() !== 0) return 1;
70224
+ atomicWrite5(target, next);
70225
+ console.log(`Wrote ${Buffer.byteLength(next)} bytes to ${target}`);
70226
+ return 0;
70227
+ }
70228
+ function runUninstall(cwd, opts) {
70229
+ if (opts.agent === "claude" && !opts.target) return uninstallClaudePlugin(cwd, opts);
70230
+ if (opts.agent === "cursor" && !opts.target) {
70231
+ if (!validCursorSkillScope(opts.scope)) return 1;
70232
+ return uninstallCursorSkill(cwd, opts.scope);
70233
+ }
70234
+ if (opts.agent === "codex" && opts.scope === "user" && !opts.target) {
70235
+ if (uninstallWelcomeSkill(codexWelcomeSkillPath()) !== 0) return 1;
70236
+ }
70237
+ const target = resolveTarget(cwd, opts);
70238
+ if (target === null) return 1;
70239
+ if (!existsSync27(target)) {
70240
+ console.log(`Skill block not present at ${target}`);
70241
+ return 0;
70242
+ }
70243
+ const existing = readFileSync26(target, "utf-8");
70244
+ const next = removeBlock2(existing);
70245
+ if (next === null) {
70246
+ console.log(`Skill block not present at ${target}`);
70247
+ return 0;
70248
+ }
70249
+ atomicWrite5(target, next);
70250
+ console.log(`Removed skill block from ${target}`);
70251
+ return 0;
70252
+ }
70253
+ function runStatus(cwd, opts) {
70254
+ if (opts.agent === "claude" && !opts.target) return statusClaudePlugin(cwd, opts);
70255
+ if (opts.agent === "cursor" && !opts.target) {
70256
+ if (!validCursorSkillScope(opts.scope)) return 1;
70257
+ const status2 = cursorSkillStatus(cwd, opts.scope);
70258
+ if (opts.json) printJson(status2);
70259
+ else
70260
+ console.log(
70261
+ status2.installed ? `Primitive Cursor skill installed at ${status2.target}` : `No intact Primitive-owned Cursor skill at ${status2.target}`
70262
+ );
70263
+ return status2.installed ? 0 : 1;
70264
+ }
70265
+ const target = resolveTarget(cwd, opts);
70266
+ if (target === null) return 1;
70267
+ const fileExists = existsSync27(target);
70268
+ let mainInstalled = false;
70269
+ if (fileExists) {
70270
+ const content2 = readFileSync26(target, "utf-8");
70271
+ mainInstalled = content2.includes(SKILL_BEGIN) && content2.includes(SKILL_END);
70272
+ }
70273
+ const welcome = opts.agent === "codex" && opts.scope === "user" && !opts.target ? welcomeSkillStatus(codexWelcomeSkillPath()) : void 0;
70274
+ const installed = mainInstalled && (!welcome || welcome.installed);
70275
+ if (opts.json) {
70276
+ printJson({
70277
+ installed,
70278
+ target,
70279
+ ...welcome ? { welcomeSkill: welcome.installed } : {}
70280
+ });
70281
+ return installed ? 0 : 1;
70282
+ }
70283
+ if (!fileExists) {
70284
+ console.log(`No rules file at ${target}`);
70285
+ return 1;
70286
+ }
70287
+ if (installed) {
70288
+ console.log(`PRIM SKILL v1 installed at ${target}`);
70289
+ return 0;
70290
+ }
70291
+ if (mainInstalled && welcome && !welcome.installed) {
70292
+ console.log(`No intact prim-welcome skill at ${welcome.target}`);
70293
+ return 1;
70294
+ }
70295
+ console.log(`No PRIM SKILL block at ${target}`);
70296
+ return 1;
70297
+ }
70298
+ function registerSkillCommands(program3) {
70299
+ const skill = program3.command("skill").description("Manage the prim skill in your project rules file");
70300
+ skill.command("install").description("Install the prim skill block into your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--dry-run", "Print a unified diff without writing").action((opts) => {
70301
+ try {
70302
+ process.exit(runInstall(process.cwd(), opts));
70303
+ } catch (err) {
70304
+ console.error(err instanceof Error ? err.message : String(err));
70305
+ process.exit(2);
70306
+ }
70307
+ });
70308
+ skill.command("uninstall").description("Remove the prim skill block from your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").action((opts) => {
70309
+ process.exit(runUninstall(process.cwd(), opts));
70310
+ });
70311
+ skill.command("status").description("Report whether the prim skill block is installed").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--json", "Output as JSON").action((opts) => {
70312
+ process.exit(runStatus(process.cwd(), opts));
70313
+ });
70314
+ }
70315
+
70316
+ // src/commands/claude-plugin.ts
70317
+ var __dirname6 = dirname20(fileURLToPath6(import.meta.url));
70318
+ var PLUGIN_DESCRIPTION = "Primitive decision-graph guidance for the prim CLI \u2014 a model-invoked skill installed by prim skill install.";
70319
+ var MAX_MANIFEST_BYTES2 = 64 * 1024;
70320
+ var MAX_SKILL_BYTES = 1024 * 1024;
70321
+ function pluginDirFor(cwd, scope) {
70322
+ const base = scope === "user" ? join38(homedir14(), ".claude") : join38(gitToplevel(cwd) ?? cwd, ".claude");
70323
+ return join38(base, "skills", "prim");
70324
+ }
70325
+ function resolvePluginDir(cwd, scope) {
70326
+ if (scope && scope !== "user" && scope !== "project") {
70327
+ console.error(`Unknown --scope "${scope}" (expected user or project)`);
70328
+ return null;
70329
+ }
70330
+ return pluginDirFor(cwd, scope === "user" ? "user" : "project");
70331
+ }
70332
+ function packageVersion3() {
70333
+ let dir = __dirname6;
70334
+ while (dir !== dirname20(dir)) {
70335
+ const p = resolve13(dir, "package.json");
70336
+ if (existsSync28(p)) return JSON.parse(readFileSync27(p, "utf-8")).version;
70337
+ dir = dirname20(dir);
70338
+ }
70339
+ return "0.0.0";
70340
+ }
70341
+ function pluginManifest(version) {
70342
+ const manifest = { name: "prim", description: PLUGIN_DESCRIPTION, version };
70343
+ return `${JSON.stringify(manifest, null, 2)}
70344
+ `;
70345
+ }
70346
+ function renderClaudePlugin() {
70347
+ const version = packageVersion3();
70348
+ return { manifest: pluginManifest(version), skill: loadSkill(), version };
70349
+ }
70350
+ function welcomeSkillPath(pluginDir) {
70351
+ return join38(dirname20(pluginDir), "prim-welcome", "SKILL.md");
70352
+ }
70353
+ function welcomeSkillPathFor(cwd, scope) {
70354
+ return welcomeSkillPath(pluginDirFor(cwd, scope));
70355
+ }
70356
+ function removeDirIfEmpty(dir) {
70357
+ if (existsSync28(dir) && readdirSync13(dir).length === 0) rmdirSync6(dir);
70358
+ }
70359
+ function pluginPaths(dir) {
70360
+ return {
70361
+ manifestPath: join38(dir, ".claude-plugin", "plugin.json"),
70362
+ skillPath: join38(dir, "SKILL.md")
70363
+ };
70364
+ }
70365
+ function installClaudePlugin(cwd, opts) {
70366
+ const dir = resolvePluginDir(cwd, opts.scope);
70367
+ if (dir === null) return 1;
70368
+ const { manifestPath: manifestPath2, skillPath } = pluginPaths(dir);
70369
+ const { manifest, skill } = renderClaudePlugin();
70370
+ const welcomePath = opts.scope === "user" ? welcomeSkillPath(dir) : null;
70371
+ const welcome = welcomePath ? loadSkill(WELCOME_SKILL_SOURCE) : null;
70372
+ const manifestCurrent = existsSync28(manifestPath2) ? readFileSync27(manifestPath2, "utf-8") : null;
70373
+ const skillCurrent = existsSync28(skillPath) ? readFileSync27(skillPath, "utf-8") : null;
70374
+ const welcomeStatus = welcomePath ? welcomeSkillStatus(welcomePath) : null;
70375
+ if (manifestCurrent === manifest && skillCurrent === skill && (!welcomePath || welcomeStatus?.installed && welcomeStatus.content === welcome)) {
70376
+ console.log("No changes \u2014 prim skill plugin already up to date.");
70377
+ return 0;
70378
+ }
70379
+ if (welcomePath && welcome !== null && installWelcomeSkill(welcomePath, welcome, opts.dryRun) !== 0)
70380
+ return 1;
70381
+ if (opts.dryRun) {
70382
+ console.log(`Would write plugin to ${dir} (.claude-plugin/plugin.json + SKILL.md)`);
70383
+ return 0;
70384
+ }
70385
+ mkdirSync15(join38(dir, ".claude-plugin"), { recursive: true });
70386
+ atomicWrite5(manifestPath2, manifest);
70387
+ atomicWrite5(skillPath, skill);
70388
+ console.log(`Installed prim skill plugin at ${dir}`);
70389
+ console.log("Restart Claude Code or run /reload-plugins to load it.");
70390
+ if (opts.scope !== "user") {
70391
+ console.log("Project-scope plugins load only when Claude Code launches from this directory.");
70392
+ }
70393
+ return 0;
70394
+ }
70395
+ function uninstallClaudePlugin(cwd, opts) {
70396
+ const dir = resolvePluginDir(cwd, opts.scope);
70397
+ if (dir === null) return 1;
70398
+ const { manifestPath: manifestPath2, skillPath } = pluginPaths(dir);
70399
+ if (opts.scope === "user" && uninstallWelcomeSkill(welcomeSkillPath(dir)) !== 0) return 1;
70400
+ if (!existsSync28(manifestPath2) && !existsSync28(skillPath)) {
70401
+ console.log(`prim skill plugin not present at ${dir}`);
70402
+ return 0;
70403
+ }
70404
+ rmSync9(manifestPath2, { force: true });
70405
+ rmSync9(skillPath, { force: true });
70406
+ removeDirIfEmpty(join38(dir, ".claude-plugin"));
70407
+ removeDirIfEmpty(dir);
70408
+ console.log(`Removed prim skill plugin from ${dir}`);
70409
+ return 0;
70410
+ }
70411
+ function statusClaudePlugin(cwd, opts) {
70412
+ const dir = resolvePluginDir(cwd, opts.scope);
70413
+ if (dir === null) return 1;
70414
+ const { skillPath } = pluginPaths(dir);
70415
+ const welcome = opts.scope === "user" ? welcomeSkillStatus(welcomeSkillPath(dir)) : void 0;
70416
+ const installed = existsSync28(skillPath) && (!welcome || welcome.installed);
70417
+ if (opts.json) {
70418
+ printJson({ installed, target: dir, ...welcome ? { welcomeSkill: welcome.installed } : {} });
70419
+ return installed ? 0 : 1;
70420
+ }
70421
+ if (installed) {
70422
+ console.log(`prim skill plugin installed at ${dir}`);
70423
+ return 0;
70424
+ }
70425
+ console.log(`No prim skill plugin at ${dir}`);
70426
+ return 1;
70427
+ }
70428
+
70429
+ // src/commands/setup.ts
69629
70430
  var EXIT_INCOMPLETE = 1;
70431
+ var GITHUB_CONNECT_TIMEOUT_MS = 9e4;
69630
70432
  var EXIT_USAGE3 = 2;
69631
70433
  var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
69632
70434
  var SETUP_DAEMON_DRAINS_ENV = "PRIM_SETUP_DAEMON_DRAINS";
@@ -69763,8 +70565,8 @@ function detectProjectConflicts(agent, run, globalHooksActive) {
69763
70565
  let preCommit;
69764
70566
  try {
69765
70567
  const root = gitToplevel();
69766
- const path9 = root && join35(root, ".git", "hooks", "pre-commit");
69767
- if (path9 && existsSync26(path9)) preCommit = readFileSync25(path9, "utf-8");
70568
+ const path9 = root && join39(root, ".git", "hooks", "pre-commit");
70569
+ if (path9 && existsSync29(path9)) preCommit = readFileSync28(path9, "utf-8");
69768
70570
  } catch {
69769
70571
  }
69770
70572
  if (projectHooksConflict(globalHooksActive, preCommit)) conflicts.push(CONFLICT_HOOKS);
@@ -69817,6 +70619,7 @@ function registerSetupCommand(program3, dependencies = {}) {
69817
70619
  "--migrate",
69818
70620
  "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
69819
70621
  ).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full human installation diagnostics on STDERR").option("--skip-demo", "skip the optional author story and remember that choice").action((opts) => {
70622
+ const setupAt = Date.now();
69820
70623
  const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
69821
70624
  if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
69822
70625
  process.stderr.write(
@@ -69841,16 +70644,15 @@ function registerSetupCommand(program3, dependencies = {}) {
69841
70644
  const scope = opts.scope;
69842
70645
  const self = process.argv[1];
69843
70646
  const globals = program3.optsWithGlobals();
69844
- const run = dependencies.run ?? ((args, capture = false) => {
70647
+ const run = dependencies.run ?? ((args, capture = false, timeoutMs2) => {
69845
70648
  const childArgs = opts.details ? args.filter((arg) => arg !== "--compact") : args;
69846
- const r = spawnSync2(
69847
- process.execPath,
69848
- [self, ...childArgs],
69849
- setupStepSpawnOptions(capture, process.env, {
70649
+ const r = spawnSync2(process.execPath, [self, ...childArgs], {
70650
+ ...setupStepSpawnOptions(capture, process.env, {
69850
70651
  startsDaemon: opts.daemon,
69851
70652
  compact: true
69852
- })
69853
- );
70653
+ }),
70654
+ timeout: timeoutMs2
70655
+ });
69854
70656
  if (!capture && r.status !== 0 && r.stdout) process.stderr.write(r.stdout);
69855
70657
  if (r.error) process.stderr.write(`[prim] ${r.error.message}
69856
70658
  `);
@@ -69926,6 +70728,11 @@ function registerSetupCommand(program3, dependencies = {}) {
69926
70728
  );
69927
70729
  }
69928
70730
  }
70731
+ const welcomeHandoff = scope === "user" && (agent === "claude" && (opts.agent === "claude" || Boolean(process.env.CLAUDECODE)) || agent === "codex" && Boolean(process.env.CODEX_THREAD_ID));
70732
+ if (welcomeHandoff && gitToplevel() && !isNonInteractive(globals)) {
70733
+ note("GitHub \xB7 connecting this repository (finish in your browser)\u2026");
70734
+ results.github = run(["github", "connect"], false, GITHUB_CONNECT_TIMEOUT_MS).code === 0 ? "ok" : "skipped";
70735
+ }
69929
70736
  const enableStep = setupSteps.find((candidate) => candidate.key === "enable");
69930
70737
  if (enableStep) {
69931
70738
  note(`${enableStep.label} \xB7 installing\u2026`);
@@ -69945,6 +70752,45 @@ function registerSetupCommand(program3, dependencies = {}) {
69945
70752
  health = setupChildPayload(stdout);
69946
70753
  results[healthStep.key] = code !== 0 || health?.status === "fail" ? healthStep.required ? "failed" : "skipped" : health?.status === "warn" ? "warn" : "ok";
69947
70754
  }
70755
+ if (welcomeHandoff) {
70756
+ const welcomeSkill = agent === "codex" ? codexWelcomeSkillPath() : welcomeSkillPathFor(process.cwd(), scope);
70757
+ const mainSkill = agent === "codex" ? userTargetFor("codex") : join39(homedir15(), ".claude", "skills", "prim", "SKILL.md");
70758
+ const failed2 = Object.keys(results).filter((key) => results[key] === "failed");
70759
+ if (failed2.length === 0 && opts.skipDemo && run(["demo", "skip"]).code !== 0)
70760
+ note("demo \xB7 could not remember skip; installation remains configured");
70761
+ let demoDone = false;
70762
+ try {
70763
+ demoDone = onboardingFinished();
70764
+ } catch {
70765
+ }
70766
+ note(
70767
+ failed2.length === 0 ? `setup complete \xB7 ${welcomeSkill}` : `setup incomplete (failed: ${failed2.join(", ")})`
70768
+ );
70769
+ printJson({
70770
+ setup: true,
70771
+ status: failed2.length ? "incomplete" : "complete",
70772
+ steps: results,
70773
+ ...health ? { health } : {},
70774
+ readiness: {
70775
+ installation: failed2.length ? "incomplete" : "installed",
70776
+ health: results.health ?? "not-checked",
70777
+ passiveCapture: "not-verified"
70778
+ },
70779
+ ...failed2.length ? {} : {
70780
+ welcomeSkill,
70781
+ mainSkill,
70782
+ agent,
70783
+ setupAt,
70784
+ prim: primCommand(),
70785
+ demo: demoDone ? "done" : "due",
70786
+ // For agents following the earlier setup prompt, which expects
70787
+ // setup to say what comes next. Remove with the old fields.
70788
+ instructions: "Read the file at welcomeSkill and follow it."
70789
+ }
70790
+ });
70791
+ exit(failed2.length === 0 ? 0 : EXIT_INCOMPLETE);
70792
+ return;
70793
+ }
69948
70794
  const installationSucceeded = !Object.values(results).includes("failed");
69949
70795
  let tourDue = false;
69950
70796
  if (installationSucceeded && !opts.skipDemo) {
@@ -70015,6 +70861,12 @@ function registerSetupCommand(program3, dependencies = {}) {
70015
70861
  exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
70016
70862
  });
70017
70863
  }
70864
+ function primCommand(argv = process.argv, version = packageVersion()) {
70865
+ const script = resolve14(argv[1]);
70866
+ if (version && script.includes(`${sep5}node_modules${sep5}`))
70867
+ return `npx --yes @primitive.ai/prim@${version}`;
70868
+ return [process.execPath, script].map((part) => `'${part.replaceAll("'", "'\\''")}'`).join(" ");
70869
+ }
70018
70870
  function setupChildPayload(stdout) {
70019
70871
  try {
70020
70872
  const value = JSON.parse(stdout);
@@ -70024,457 +70876,24 @@ function setupChildPayload(stdout) {
70024
70876
  }
70025
70877
  }
70026
70878
 
70027
- // src/commands/skill.ts
70028
- import { createHash as createHash15 } from "crypto";
70029
- import {
70030
- constants as constants8,
70031
- closeSync as closeSync8,
70032
- existsSync as existsSync28,
70033
- fstatSync as fstatSync4,
70034
- lstatSync as lstatSync13,
70035
- openSync as openSync8,
70036
- readFileSync as readFileSync27,
70037
- readSync as readSync4,
70038
- readdirSync as readdirSync12,
70039
- rmdirSync as rmdirSync5,
70040
- unlinkSync as unlinkSync10
70041
- } from "fs";
70042
- import { homedir as homedir13 } from "os";
70043
- import { dirname as dirname19, join as join37, resolve as resolve13 } from "path";
70044
- import { fileURLToPath as fileURLToPath6 } from "url";
70045
-
70046
- // src/commands/claude-plugin.ts
70047
- import { createHash as createHash14 } from "crypto";
70048
- import {
70049
- constants as constants7,
70050
- closeSync as closeSync7,
70051
- existsSync as existsSync27,
70052
- fstatSync as fstatSync3,
70053
- lstatSync as lstatSync12,
70054
- mkdirSync as mkdirSync15,
70055
- openSync as openSync7,
70056
- readFileSync as readFileSync26,
70057
- readSync as readSync3,
70058
- readdirSync as readdirSync11,
70059
- realpathSync as realpathSync8,
70060
- rmSync as rmSync9,
70061
- rmdirSync as rmdirSync4
70062
- } from "fs";
70063
- import { homedir as homedir12 } from "os";
70064
- import { dirname as dirname18, isAbsolute as isAbsolute11, join as join36, relative as relative4, resolve as resolve12, sep as sep4 } from "path";
70065
- import { fileURLToPath as fileURLToPath5 } from "url";
70066
- var __dirname5 = dirname18(fileURLToPath5(import.meta.url));
70067
- var PLUGIN_DESCRIPTION = "Primitive decision-graph guidance for the prim CLI \u2014 a model-invoked skill installed by prim skill install.";
70068
- var MAX_MANIFEST_BYTES2 = 64 * 1024;
70069
- var MAX_SKILL_BYTES = 1024 * 1024;
70070
- function pluginDirFor(cwd, scope) {
70071
- const base = scope === "user" ? join36(homedir12(), ".claude") : join36(gitToplevel(cwd) ?? cwd, ".claude");
70072
- return join36(base, "skills", "prim");
70073
- }
70074
- function resolvePluginDir(cwd, scope) {
70075
- if (scope && scope !== "user" && scope !== "project") {
70076
- console.error(`Unknown --scope "${scope}" (expected user or project)`);
70077
- return null;
70078
- }
70079
- return pluginDirFor(cwd, scope === "user" ? "user" : "project");
70080
- }
70081
- function packageVersion3() {
70082
- let dir = __dirname5;
70083
- while (dir !== dirname18(dir)) {
70084
- const p = resolve12(dir, "package.json");
70085
- if (existsSync27(p)) return JSON.parse(readFileSync26(p, "utf-8")).version;
70086
- dir = dirname18(dir);
70087
- }
70088
- return "0.0.0";
70089
- }
70090
- function pluginManifest(version) {
70091
- const manifest = { name: "prim", description: PLUGIN_DESCRIPTION, version };
70092
- return `${JSON.stringify(manifest, null, 2)}
70093
- `;
70094
- }
70095
- function renderClaudePlugin() {
70096
- const version = packageVersion3();
70097
- return { manifest: pluginManifest(version), skill: loadSkill(), version };
70098
- }
70099
- function removeDirIfEmpty(dir) {
70100
- if (existsSync27(dir) && readdirSync11(dir).length === 0) rmdirSync4(dir);
70101
- }
70102
- function pluginPaths(dir) {
70103
- return {
70104
- manifestPath: join36(dir, ".claude-plugin", "plugin.json"),
70105
- skillPath: join36(dir, "SKILL.md")
70106
- };
70107
- }
70108
- function installClaudePlugin(cwd, opts) {
70109
- const dir = resolvePluginDir(cwd, opts.scope);
70110
- if (dir === null) return 1;
70111
- const { manifestPath, skillPath } = pluginPaths(dir);
70112
- const { manifest, skill } = renderClaudePlugin();
70113
- const manifestCurrent = existsSync27(manifestPath) ? readFileSync26(manifestPath, "utf-8") : null;
70114
- const skillCurrent = existsSync27(skillPath) ? readFileSync26(skillPath, "utf-8") : null;
70115
- if (manifestCurrent === manifest && skillCurrent === skill) {
70116
- console.log("No changes \u2014 prim skill plugin already up to date.");
70117
- return 0;
70118
- }
70119
- if (opts.dryRun) {
70120
- console.log(`Would write plugin to ${dir} (.claude-plugin/plugin.json + SKILL.md)`);
70121
- return 0;
70122
- }
70123
- mkdirSync15(join36(dir, ".claude-plugin"), { recursive: true });
70124
- atomicWrite5(manifestPath, manifest);
70125
- atomicWrite5(skillPath, skill);
70126
- console.log(`Installed prim skill plugin at ${dir}`);
70127
- console.log("Restart Claude Code or run /reload-plugins to load it.");
70128
- if (opts.scope !== "user") {
70129
- console.log("Project-scope plugins load only when Claude Code launches from this directory.");
70130
- }
70131
- return 0;
70132
- }
70133
- function uninstallClaudePlugin(cwd, opts) {
70134
- const dir = resolvePluginDir(cwd, opts.scope);
70135
- if (dir === null) return 1;
70136
- const { manifestPath, skillPath } = pluginPaths(dir);
70137
- if (!existsSync27(manifestPath) && !existsSync27(skillPath)) {
70138
- console.log(`prim skill plugin not present at ${dir}`);
70139
- return 0;
70140
- }
70141
- rmSync9(manifestPath, { force: true });
70142
- rmSync9(skillPath, { force: true });
70143
- removeDirIfEmpty(join36(dir, ".claude-plugin"));
70144
- removeDirIfEmpty(dir);
70145
- console.log(`Removed prim skill plugin from ${dir}`);
70146
- return 0;
70147
- }
70148
- function statusClaudePlugin(cwd, opts) {
70149
- const dir = resolvePluginDir(cwd, opts.scope);
70150
- if (dir === null) return 1;
70151
- const { skillPath } = pluginPaths(dir);
70152
- const installed = existsSync27(skillPath);
70153
- if (opts.json) {
70154
- printJson({ installed, target: dir });
70155
- return installed ? 0 : 1;
70156
- }
70157
- if (installed) {
70158
- console.log(`prim skill plugin installed at ${dir}`);
70159
- return 0;
70160
- }
70161
- console.log(`No prim skill plugin at ${dir}`);
70162
- return 1;
70163
- }
70164
-
70165
- // src/commands/skill.ts
70166
- var __dirname6 = dirname19(fileURLToPath6(import.meta.url));
70167
- var SKILL_BEGIN = "<!-- BEGIN PRIM SKILL v1 -->";
70168
- var SKILL_END = "<!-- END PRIM SKILL v1 -->";
70169
- var CODEX_GUIDANCE_LIMIT_BYTES = 1024 * 1024;
70170
- var CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES = 32 * 1024;
70171
- var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
70172
- var SKILL_END_BUFFER = Buffer.from(SKILL_END);
70173
- var TARGET_CANDIDATES = [
70174
- "CLAUDE.md",
70175
- "AGENTS.md",
70176
- ".hermes.md",
70177
- ".cursor/rules",
70178
- ".windsurfrules",
70179
- ".github/instructions/primitive.md"
70180
- ];
70181
- var DEFAULT_TARGET = "CLAUDE.md";
70182
- var AGENT_TARGET = {
70183
- claude: "CLAUDE.md",
70184
- codex: "AGENTS.md",
70185
- hermes: ".hermes.md"
70186
- };
70187
- var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
70188
- var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
70189
- function sha2564(content2) {
70190
- return createHash15("sha256").update(content2).digest("hex");
70191
- }
70192
- function cursorSkillDirectory(cwd, scope) {
70193
- const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
70194
- return join37(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
70195
- }
70196
- function cursorSkillPaths(cwd, scope) {
70197
- const directory = cursorSkillDirectory(cwd, scope);
70198
- return {
70199
- directory,
70200
- skill: join37(directory, "SKILL.md"),
70201
- manifest: join37(directory, CURSOR_SKILL_MANIFEST)
70202
- };
70203
- }
70204
- function readCursorSkillManifest(path9) {
70205
- try {
70206
- const value = JSON.parse(readFileSync27(path9, "utf8"));
70207
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
70208
- const record3 = value;
70209
- if (record3.version !== 1 || record3.owner !== CURSOR_SKILL_OWNER || typeof record3.contentSha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record3.contentSha256)) {
70210
- return;
70211
- }
70212
- return record3;
70213
- } catch {
70214
- return;
70215
- }
70216
- }
70217
- function cursorSkillStatus(cwd, scope) {
70218
- const paths = cursorSkillPaths(cwd, scope);
70219
- const manifest = readCursorSkillManifest(paths.manifest);
70220
- const content2 = existsSync28(paths.skill) ? readFileSync27(paths.skill, "utf8") : void 0;
70221
- const owned = manifest !== void 0;
70222
- const installed = owned && content2 !== void 0 && sha2564(content2) === manifest.contentSha256;
70223
- return {
70224
- installed,
70225
- owned,
70226
- edited: owned && content2 !== void 0 && !installed,
70227
- target: paths.skill
70228
- };
70229
- }
70230
- function validCursorSkillScope(scope) {
70231
- if (scope === void 0 || scope === "project" || scope === "user") return true;
70232
- console.error(`Unknown --scope "${scope}" (expected user or project)`);
70233
- return false;
70234
- }
70235
- function installCursorSkill(cwd, opts) {
70236
- const paths = cursorSkillPaths(cwd, opts.scope);
70237
- const status2 = cursorSkillStatus(cwd, opts.scope);
70238
- const manifestExists = existsSync28(paths.manifest);
70239
- const skillExists = existsSync28(paths.skill);
70240
- if (manifestExists && !status2.owned || !manifestExists && skillExists || status2.edited) {
70241
- console.error(`Refusing to overwrite a foreign or edited Cursor skill at ${paths.skill}`);
70242
- return 1;
70243
- }
70244
- const content2 = loadSkill();
70245
- const manifest = {
70246
- version: 1,
70247
- owner: CURSOR_SKILL_OWNER,
70248
- contentSha256: sha2564(content2)
70249
- };
70250
- if (status2.installed && readFileSync27(paths.skill, "utf8") === content2) {
70251
- console.log(`No changes \u2014 Cursor skill already up to date at ${paths.skill}`);
70252
- return 0;
70253
- }
70254
- if (opts.dryRun) {
70255
- const existing = skillExists ? readFileSync27(paths.skill, "utf8") : "";
70256
- process.stdout.write(createPatch(paths.skill, existing, content2, "current", "proposed"));
70257
- return 0;
70258
- }
70259
- atomicWriteFile(paths.skill, content2, { ensureParent: true });
70260
- atomicWriteFile(paths.manifest, `${JSON.stringify(manifest, null, 2)}
70261
- `, { ensureParent: true });
70262
- console.log(`Installed Cursor skill at ${paths.skill}`);
70263
- return 0;
70264
- }
70265
- function uninstallCursorSkill(cwd, scope) {
70266
- const paths = cursorSkillPaths(cwd, scope);
70267
- const status2 = cursorSkillStatus(cwd, scope);
70268
- if (!status2.owned) {
70269
- console.log(`No Primitive-owned Cursor skill at ${paths.skill}`);
70270
- return 0;
70271
- }
70272
- if (status2.edited) {
70273
- console.error(`Refusing to remove an edited Cursor skill at ${paths.skill}`);
70274
- return 1;
70275
- }
70276
- if (existsSync28(paths.skill)) unlinkSync10(paths.skill);
70277
- if (existsSync28(paths.manifest)) unlinkSync10(paths.manifest);
70278
- try {
70279
- if (readdirSync12(paths.directory).length === 0) rmdirSync5(paths.directory);
70280
- } catch {
70281
- }
70282
- console.log(`Removed Primitive-owned Cursor skill from ${paths.skill}`);
70283
- return 0;
70284
- }
70285
- function userTargetFor(agent) {
70286
- if (agent === "claude") return join37(homedir13(), ".claude", "CLAUDE.md");
70287
- if (agent === "codex") return join37(homedir13(), ".codex", "AGENTS.md");
70288
- if (agent === "hermes") {
70289
- return join37(process.env.HERMES_HOME ?? join37(homedir13(), ".hermes"), ".hermes.md");
70290
- }
70291
- return null;
70292
- }
70293
- function loadSkill() {
70294
- let dir = __dirname6;
70295
- while (dir !== dirname19(dir)) {
70296
- const p = resolve13(dir, "SKILL.md");
70297
- if (existsSync28(p)) return readFileSync27(p, "utf-8");
70298
- dir = dirname19(dir);
70299
- }
70300
- throw new Error("SKILL.md not found in package");
70301
- }
70302
- function detectTargets(cwd) {
70303
- return TARGET_CANDIDATES.filter((p) => existsSync28(resolve13(cwd, p)));
70304
- }
70305
- function detectNewline(content2) {
70306
- return content2.includes("\r\n") ? "\r\n" : "\n";
70307
- }
70308
- function composeBlock(skill, eol) {
70309
- const body = skill.replace(/\r?\n/g, eol);
70310
- return `${SKILL_BEGIN}${eol}${body}${eol}${SKILL_END}`;
70311
- }
70312
- function applyBlock(existing, block, eol) {
70313
- const b = existing.indexOf(SKILL_BEGIN);
70314
- const e = existing.indexOf(SKILL_END);
70315
- if (b !== -1 && e !== -1) {
70316
- return existing.slice(0, b) + block + existing.slice(e + SKILL_END.length);
70317
- }
70318
- if (existing.length === 0) return `${block}${eol}`;
70319
- const sep5 = existing.endsWith(eol) ? "" : eol;
70320
- return `${existing}${sep5}${block}${eol}`;
70321
- }
70322
- function removeBlock2(existing) {
70323
- const b = existing.indexOf(SKILL_BEGIN);
70324
- const e = existing.indexOf(SKILL_END);
70325
- if (b === -1 || e === -1) return null;
70326
- const out = existing.slice(0, b) + existing.slice(e + SKILL_END.length);
70327
- return out.replace(/(\r?\n){2,}$/, "$1");
70328
- }
70329
- function atomicWrite5(target, content2) {
70330
- atomicWriteFile(target, content2);
70331
- }
70332
- function resolveTarget(cwd, opts) {
70333
- if (opts.scope && opts.scope !== "user" && opts.scope !== "project") {
70334
- console.error(`Unknown --scope "${opts.scope}" (expected user or project)`);
70335
- return null;
70336
- }
70337
- if (opts.target) return resolve13(cwd, opts.target);
70338
- if (opts.scope === "user") {
70339
- if (!opts.agent) {
70340
- console.error("--scope user requires --agent (claude, codex, cursor, or hermes)");
70341
- return null;
70342
- }
70343
- const userTarget = userTargetFor(opts.agent);
70344
- if (userTarget) return userTarget;
70345
- console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
70346
- return null;
70347
- }
70348
- if (opts.agent) {
70349
- const mapped = AGENT_TARGET[opts.agent];
70350
- if (typeof mapped === "string") return resolve13(cwd, mapped);
70351
- console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
70352
- return null;
70353
- }
70354
- const matches = detectTargets(cwd);
70355
- if (matches.length === 0) return resolve13(cwd, DEFAULT_TARGET);
70356
- if (matches.length === 1) return resolve13(cwd, matches[0]);
70357
- console.error("Multiple rules files detected. Use --target to disambiguate:");
70358
- for (const m of matches) console.error(` ${m}`);
70359
- return null;
70360
- }
70361
- function runInstall(cwd, opts) {
70362
- if (opts.agent === "claude" && !opts.target) return installClaudePlugin(cwd, opts);
70363
- if (opts.agent === "cursor" && !opts.target) {
70364
- if (!validCursorSkillScope(opts.scope)) return 1;
70365
- return installCursorSkill(cwd, opts);
70366
- }
70367
- const target = resolveTarget(cwd, opts);
70368
- if (target === null) return 1;
70369
- const existing = existsSync28(target) ? readFileSync27(target, "utf-8") : "";
70370
- const eol = existing ? detectNewline(existing) : "\n";
70371
- const block = composeBlock(loadSkill(), eol);
70372
- const next = applyBlock(existing, block, eol);
70373
- if (next === existing) {
70374
- console.log("No changes \u2014 skill block already up to date.");
70375
- return 0;
70376
- }
70377
- if (opts.dryRun) {
70378
- process.stdout.write(createPatch(target, existing, next, "current", "proposed"));
70379
- return 0;
70380
- }
70381
- atomicWrite5(target, next);
70382
- console.log(`Wrote ${Buffer.byteLength(next)} bytes to ${target}`);
70383
- return 0;
70384
- }
70385
- function runUninstall(cwd, opts) {
70386
- if (opts.agent === "claude" && !opts.target) return uninstallClaudePlugin(cwd, opts);
70387
- if (opts.agent === "cursor" && !opts.target) {
70388
- if (!validCursorSkillScope(opts.scope)) return 1;
70389
- return uninstallCursorSkill(cwd, opts.scope);
70390
- }
70391
- const target = resolveTarget(cwd, opts);
70392
- if (target === null) return 1;
70393
- if (!existsSync28(target)) {
70394
- console.log(`Skill block not present at ${target}`);
70395
- return 0;
70396
- }
70397
- const existing = readFileSync27(target, "utf-8");
70398
- const next = removeBlock2(existing);
70399
- if (next === null) {
70400
- console.log(`Skill block not present at ${target}`);
70401
- return 0;
70402
- }
70403
- atomicWrite5(target, next);
70404
- console.log(`Removed skill block from ${target}`);
70405
- return 0;
70406
- }
70407
- function runStatus(cwd, opts) {
70408
- if (opts.agent === "claude" && !opts.target) return statusClaudePlugin(cwd, opts);
70409
- if (opts.agent === "cursor" && !opts.target) {
70410
- if (!validCursorSkillScope(opts.scope)) return 1;
70411
- const status2 = cursorSkillStatus(cwd, opts.scope);
70412
- if (opts.json) printJson(status2);
70413
- else
70414
- console.log(
70415
- status2.installed ? `Primitive Cursor skill installed at ${status2.target}` : `No intact Primitive-owned Cursor skill at ${status2.target}`
70416
- );
70417
- return status2.installed ? 0 : 1;
70418
- }
70419
- const target = resolveTarget(cwd, opts);
70420
- if (target === null) return 1;
70421
- const fileExists = existsSync28(target);
70422
- let installed = false;
70423
- if (fileExists) {
70424
- const content2 = readFileSync27(target, "utf-8");
70425
- installed = content2.includes(SKILL_BEGIN) && content2.includes(SKILL_END);
70426
- }
70427
- if (opts.json) {
70428
- printJson({ installed, target });
70429
- return installed ? 0 : 1;
70430
- }
70431
- if (!fileExists) {
70432
- console.log(`No rules file at ${target}`);
70433
- return 1;
70434
- }
70435
- if (installed) {
70436
- console.log(`PRIM SKILL v1 installed at ${target}`);
70437
- return 0;
70438
- }
70439
- console.log(`No PRIM SKILL block at ${target}`);
70440
- return 1;
70441
- }
70442
- function registerSkillCommands(program3) {
70443
- const skill = program3.command("skill").description("Manage the prim skill in your project rules file");
70444
- skill.command("install").description("Install the prim skill block into your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--dry-run", "Print a unified diff without writing").action((opts) => {
70445
- try {
70446
- process.exit(runInstall(process.cwd(), opts));
70447
- } catch (err) {
70448
- console.error(err instanceof Error ? err.message : String(err));
70449
- process.exit(2);
70450
- }
70451
- });
70452
- skill.command("uninstall").description("Remove the prim skill block from your project rules file").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").action((opts) => {
70453
- process.exit(runUninstall(process.cwd(), opts));
70454
- });
70455
- skill.command("status").description("Report whether the prim skill block is installed").option("--target <path>", "Path to the rules file (overrides auto-detection)").option("--agent <agent>", "claude, codex, cursor, or hermes").option("--scope <scope>", "project (default, this repo) or user (machine-global \u2014 every repo)").option("--json", "Output as JSON").action((opts) => {
70456
- process.exit(runStatus(process.cwd(), opts));
70457
- });
70458
- }
70459
-
70460
70879
  // src/commands/statusline.ts
70461
- import { readFileSync as readFileSync28 } from "fs";
70462
- import { dirname as dirname20, resolve as resolve14 } from "path";
70880
+ import { readFileSync as readFileSync29 } from "fs";
70881
+ import { dirname as dirname21, resolve as resolve15 } from "path";
70463
70882
  import { fileURLToPath as fileURLToPath7 } from "url";
70464
70883
  var STATUSLINE_TIMEOUT_MS = 200;
70465
70884
  function readPackageVersion() {
70466
70885
  try {
70467
- const here = dirname20(fileURLToPath7(import.meta.url));
70886
+ const here = dirname21(fileURLToPath7(import.meta.url));
70468
70887
  const candidates = [
70469
70888
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
70470
70889
  // Keep resolving it while those legacy launchers transition to schema v3.
70471
- resolve14(here, "manifest.json"),
70472
- resolve14(here, "../../package.json"),
70473
- resolve14(here, "../package.json")
70890
+ resolve15(here, "manifest.json"),
70891
+ resolve15(here, "../../package.json"),
70892
+ resolve15(here, "../package.json")
70474
70893
  ];
70475
70894
  for (const path9 of candidates) {
70476
70895
  try {
70477
- const pkg2 = JSON.parse(readFileSync28(path9, "utf-8"));
70896
+ const pkg2 = JSON.parse(readFileSync29(path9, "utf-8"));
70478
70897
  if (pkg2.version) {
70479
70898
  return pkg2.version;
70480
70899
  }
@@ -70806,6 +71225,36 @@ function welcomeStateFromRecent(result) {
70806
71225
  }
70807
71226
  return { org: "active", recent };
70808
71227
  }
71228
+ var SAMPLE_WINDOW = 50;
71229
+ var escapeLinkText = (text) => text.replace(/\s+/gu, " ").replace(/[[\]\\]/gu, "\\$&");
71230
+ function sampleTeamDecisions(rows) {
71231
+ const byAuthor = /* @__PURE__ */ new Map();
71232
+ for (const row of rows) {
71233
+ if (row.status === "superseded") continue;
71234
+ byAuthor.set(row.authorName, [...byAuthor.get(row.authorName) ?? [], row]);
71235
+ }
71236
+ const picked = [];
71237
+ for (let round = 0; picked.length < RECENT_LIMIT; round++) {
71238
+ const next = [...byAuthor.values()].map((authored) => authored[round]).filter(Boolean);
71239
+ if (next.length === 0) break;
71240
+ picked.push(...next.slice(0, RECENT_LIMIT - picked.length));
71241
+ }
71242
+ return picked.sort((a, b) => b.classifiedAt - a.classifiedAt).flatMap((row) => {
71243
+ const id2 = decisionIdentifier(row.id, row.shortId);
71244
+ return id2 ? [
71245
+ {
71246
+ intent: escapeLinkText(row.intent),
71247
+ author: escapeLinkText(row.authorName),
71248
+ ...row.area ? { area: escapeLinkText(row.area) } : {},
71249
+ date: new Date(row.classifiedAt).toLocaleDateString("en-US", {
71250
+ month: "short",
71251
+ day: "numeric"
71252
+ }),
71253
+ url: `https://app.getprimitive.ai/decisions/${id2}`
71254
+ }
71255
+ ] : [];
71256
+ });
71257
+ }
70809
71258
  function formatWelcome(state, agent, captureExcluded = false) {
70810
71259
  const cmd = (command, desc) => ` ${dim(command.padEnd(CMD_GUTTER))}${desc}`;
70811
71260
  const bullet = (text) => ` ${color("\u2022", "green")} ${text}`;
@@ -70879,7 +71328,7 @@ function welcomeJson(state, agent, captureExcluded = false) {
70879
71328
  return { welcomed: true, org: "unknown" };
70880
71329
  }
70881
71330
  function registerWelcomeCommand(program3, deps = { getClient }) {
70882
- program3.command("welcome").description("Print a brief orientation to Primitive's decision graph").option("--agent <agent>", "claude, codex, cursor, or hermes \u2014 tailors the capture guidance").option("--defer-seeding", "let setup's author story finish before proposing real Decisions").option("--after-demo", "return a short transition after the author story").option("--capture-excluded", "explain the demo session's passive capture exclusion").action(
71331
+ program3.command("welcome").description("Print a brief orientation to Primitive's decision graph").option("--agent <agent>", "claude, codex, cursor, or hermes \u2014 tailors the capture guidance").option("--defer-seeding", "let setup's author story finish before proposing real Decisions").option("--after-demo", "return a short transition after the author story").option("--capture-excluded", "explain the demo session's passive capture exclusion").option("--team-sample", "with --after-demo, add recent decisions spread across authors").action(
70883
71332
  async (options) => {
70884
71333
  const agent = resolveWelcomeAgent(options.agent, process.env);
70885
71334
  if (options.deferSeeding) {
@@ -70889,7 +71338,10 @@ function registerWelcomeCommand(program3, deps = { getClient }) {
70889
71338
  printJson({ welcomed: true, onboarding: "demo", seedingDeferred: true });
70890
71339
  return;
70891
71340
  }
70892
- const result = await fetchRecent({ limit: RECENT_LIMIT }, deps);
71341
+ const result = await fetchRecent(
71342
+ { limit: options.teamSample ? SAMPLE_WINDOW : RECENT_LIMIT },
71343
+ deps
71344
+ );
70893
71345
  const state = welcomeStateFromRecent(result);
70894
71346
  if (options.afterDemo) {
70895
71347
  printJson({
@@ -70897,7 +71349,10 @@ function registerWelcomeCommand(program3, deps = { getClient }) {
70897
71349
  org: state.org,
70898
71350
  presentation: state.org === "seed" ? "Ready for your first real Decision? I can propose one from shared repository memory for your approval. Approved Decisions are visible to your team." : state.org === "active" ? "Ready for real work. Ask your agent to add a Decision whenever you need one." : "Your Decision history is unavailable; no seeding assumptions were made. Retry welcome when the connection is available.",
70899
71351
  ...state.org === "seed" ? { seedGuidance: seedGuidanceFor(agent, options.captureExcluded) } : {},
70900
- captureExcluded: options.captureExcluded === true
71352
+ captureExcluded: options.captureExcluded === true,
71353
+ ...options.teamSample ? {
71354
+ recent: result.unavailable === void 0 ? sampleTeamDecisions(result.decisions) : []
71355
+ } : {}
70901
71356
  });
70902
71357
  return;
70903
71358
  }
@@ -71038,13 +71493,13 @@ function healDaemonDrift(options = {}) {
71038
71493
 
71039
71494
  // src/lib/background-flush.ts
71040
71495
  import { spawn as spawn5 } from "child_process";
71041
- import { readFileSync as readFileSync29 } from "fs";
71496
+ import { readFileSync as readFileSync30 } from "fs";
71042
71497
 
71043
71498
  // src/daemon/health.ts
71044
- import { chmodSync as chmodSync8, existsSync as existsSync29, mkdirSync as mkdirSync16, renameSync as renameSync7, writeFileSync as writeFileSync11 } from "fs";
71045
- import { dirname as dirname21, join as join38 } from "path";
71499
+ import { chmodSync as chmodSync8, existsSync as existsSync30, mkdirSync as mkdirSync16, renameSync as renameSync7, writeFileSync as writeFileSync11 } from "fs";
71500
+ import { dirname as dirname22, join as join40 } from "path";
71046
71501
  var HEARTBEAT_FRESH_MS = 9e4;
71047
- var DAEMON_HEALTH_PATH = join38(primConfigDirectory(), "daemon-health.json");
71502
+ var DAEMON_HEALTH_PATH = join40(primConfigDirectory(), "daemon-health.json");
71048
71503
 
71049
71504
  // src/lib/background-flush.ts
71050
71505
  function record2(value) {
@@ -71055,7 +71510,7 @@ function daemonOwnsDrain(options = {}) {
71055
71510
  const expectedVersion = options.expectedVersion === void 0 ? packageVersion() : options.expectedVersion;
71056
71511
  if (!expectedVersion) return false;
71057
71512
  const health = record2(
71058
- JSON.parse(readFileSync29(options.healthPath ?? DAEMON_HEALTH_PATH, "utf8"))
71513
+ JSON.parse(readFileSync30(options.healthPath ?? DAEMON_HEALTH_PATH, "utf8"))
71059
71514
  );
71060
71515
  const heartbeat = record2(health?.heartbeat);
71061
71516
  const ingestion = record2(health?.ingestion);
@@ -71171,8 +71626,8 @@ function runStartupBackgroundWork(argv, env4, work) {
71171
71626
  }
71172
71627
 
71173
71628
  // src/index.ts
71174
- var __dirname7 = dirname22(fileURLToPath8(import.meta.url));
71175
- var pkg = JSON.parse(readFileSync30(resolve15(__dirname7, "../package.json"), "utf-8"));
71629
+ var __dirname7 = dirname23(fileURLToPath8(import.meta.url));
71630
+ var pkg = JSON.parse(readFileSync31(resolve16(__dirname7, "../package.json"), "utf-8"));
71176
71631
  runStartupBackgroundWork(process.argv.slice(2), process.env, {
71177
71632
  notify: () => updateNotifier({ pkg }).notify(),
71178
71633
  flush: () => startBackgroundFlush(),