@primitive.ai/prim 0.1.0-alpha.102 → 0.1.0-alpha.104

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.
@@ -4963,7 +4963,7 @@ var require_rc = __commonJS({
4963
4963
  "node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js"(exports, module) {
4964
4964
  "use strict";
4965
4965
  var cc = require_utils();
4966
- var join33 = __require("path").join;
4966
+ var join35 = __require("path").join;
4967
4967
  var deepExtend = require_deep_extend();
4968
4968
  var etc = "/etc";
4969
4969
  var win = process.platform === "win32";
@@ -4988,15 +4988,15 @@ var require_rc = __commonJS({
4988
4988
  }
4989
4989
  if (!win)
4990
4990
  [
4991
- join33(etc, name, "config"),
4992
- join33(etc, name + "rc")
4991
+ join35(etc, name, "config"),
4992
+ join35(etc, name + "rc")
4993
4993
  ].forEach(addConfigFile);
4994
4994
  if (home)
4995
4995
  [
4996
- join33(home, ".config", name, "config"),
4997
- join33(home, ".config", name),
4998
- join33(home, "." + name, "config"),
4999
- join33(home, "." + name + "rc")
4996
+ join35(home, ".config", name, "config"),
4997
+ join35(home, ".config", name),
4998
+ join35(home, "." + name, "config"),
4999
+ join35(home, "." + name + "rc")
5000
5000
  ].forEach(addConfigFile);
5001
5001
  addConfigFile(cc.find("." + name + "rc"));
5002
5002
  if (env4.config) addConfigFile(env4.config);
@@ -6340,11 +6340,11 @@ var require_util = __commonJS({
6340
6340
  if (files.includes("node_modules") || files.includes("package.json") || files.includes("package.json5") || files.includes("package.yaml") || files.includes("pnpm-workspace.yaml")) {
6341
6341
  return name2;
6342
6342
  }
6343
- const dirname21 = path9.dirname(name2);
6344
- if (dirname21 === name2) {
6343
+ const dirname22 = path9.dirname(name2);
6344
+ if (dirname22 === name2) {
6345
6345
  return original;
6346
6346
  }
6347
- return find(dirname21, original);
6347
+ return find(dirname22, original);
6348
6348
  } catch (error) {
6349
6349
  if (name2 === original) {
6350
6350
  if (error.code === "ENOENT") {
@@ -8896,8 +8896,8 @@ var require_ucs2length = __commonJS({
8896
8896
  });
8897
8897
 
8898
8898
  // src/index.ts
8899
- import { readFileSync as readFileSync26 } from "fs";
8900
- import { dirname as dirname20, resolve as resolve11 } from "path";
8899
+ import { readFileSync as readFileSync28 } from "fs";
8900
+ import { dirname as dirname21, resolve as resolve12 } from "path";
8901
8901
  import { fileURLToPath as fileURLToPath7 } from "url";
8902
8902
 
8903
8903
  // node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
@@ -8998,7 +8998,7 @@ var retryifyAsync = (fn, options) => {
8998
8998
  throw error;
8999
8999
  const delay2 = Math.round(interval * Math.random());
9000
9000
  if (delay2 > 0) {
9001
- const delayPromise = new Promise((resolve12) => setTimeout(resolve12, delay2));
9001
+ const delayPromise = new Promise((resolve13) => setTimeout(resolve13, delay2));
9002
9002
  return delayPromise.then(() => attempt.apply(void 0, args));
9003
9003
  } else {
9004
9004
  return attempt.apply(void 0, args);
@@ -9257,14 +9257,14 @@ var Temp = {
9257
9257
  }
9258
9258
  },
9259
9259
  truncate: (filePath) => {
9260
- const basename5 = path2.basename(filePath);
9261
- if (basename5.length <= LIMIT_BASENAME_LENGTH)
9260
+ const basename6 = path2.basename(filePath);
9261
+ if (basename6.length <= LIMIT_BASENAME_LENGTH)
9262
9262
  return filePath;
9263
- const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename5);
9263
+ const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename6);
9264
9264
  if (!truncable)
9265
9265
  return filePath;
9266
- const truncationLength = basename5.length - LIMIT_BASENAME_LENGTH;
9267
- return `${filePath.slice(0, -basename5.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
9266
+ const truncationLength = basename6.length - LIMIT_BASENAME_LENGTH;
9267
+ return `${filePath.slice(0, -basename6.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
9268
9268
  }
9269
9269
  };
9270
9270
  node_default(Temp.purgeSyncAll);
@@ -10564,14 +10564,14 @@ var TimeoutError = class extends Error {
10564
10564
 
10565
10565
  // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/timeout.js
10566
10566
  async function timeout(request2, init, abortController, options) {
10567
- return new Promise((resolve12, reject) => {
10567
+ return new Promise((resolve13, reject) => {
10568
10568
  const timeoutId = setTimeout(() => {
10569
10569
  if (abortController) {
10570
10570
  abortController.abort();
10571
10571
  }
10572
10572
  reject(new TimeoutError(request2));
10573
10573
  }, options.timeout);
10574
- void options.fetch(request2, init).then(resolve12).catch(reject).then(() => {
10574
+ void options.fetch(request2, init).then(resolve13).catch(reject).then(() => {
10575
10575
  clearTimeout(timeoutId);
10576
10576
  });
10577
10577
  });
@@ -10579,7 +10579,7 @@ async function timeout(request2, init, abortController, options) {
10579
10579
 
10580
10580
  // node_modules/.pnpm/ky@1.14.3/node_modules/ky/distribution/utils/delay.js
10581
10581
  async function delay(ms, { signal }) {
10582
- return new Promise((resolve12, reject) => {
10582
+ return new Promise((resolve13, reject) => {
10583
10583
  if (signal) {
10584
10584
  signal.throwIfAborted();
10585
10585
  signal.addEventListener("abort", abortHandler, { once: true });
@@ -10590,7 +10590,7 @@ async function delay(ms, { signal }) {
10590
10590
  }
10591
10591
  const timeoutId = setTimeout(() => {
10592
10592
  signal?.removeEventListener("abort", abortHandler);
10593
- resolve12();
10593
+ resolve13();
10594
10594
  }, ms);
10595
10595
  });
10596
10596
  }
@@ -12564,7 +12564,7 @@ function providerError(value) {
12564
12564
  return exactString(error, "error", MAX_USER_CODE_LENGTH);
12565
12565
  }
12566
12566
  async function defaultSleep(milliseconds, signal) {
12567
- await new Promise((resolve12, reject) => {
12567
+ await new Promise((resolve13, reject) => {
12568
12568
  if (signal.aborted) {
12569
12569
  reject(signal.reason);
12570
12570
  return;
@@ -12575,7 +12575,7 @@ async function defaultSleep(milliseconds, signal) {
12575
12575
  };
12576
12576
  const timer = setTimeout(() => {
12577
12577
  signal.removeEventListener("abort", abort);
12578
- resolve12();
12578
+ resolve13();
12579
12579
  }, milliseconds);
12580
12580
  signal.addEventListener("abort", abort, { once: true });
12581
12581
  });
@@ -12820,7 +12820,7 @@ function daemonRequest(method, params = {}, opts = {}) {
12820
12820
  ...caller ? { caller } : {}
12821
12821
  };
12822
12822
  const timeoutMs2 = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
12823
- return new Promise((resolve12) => {
12823
+ return new Promise((resolve13) => {
12824
12824
  let settled = false;
12825
12825
  let socket;
12826
12826
  let buffer = Buffer.alloc(0);
@@ -12835,7 +12835,7 @@ function daemonRequest(method, params = {}, opts = {}) {
12835
12835
  } catch {
12836
12836
  }
12837
12837
  }
12838
- resolve12(value);
12838
+ resolve13(value);
12839
12839
  };
12840
12840
  const timer = setTimeout(() => settle(null), timeoutMs2);
12841
12841
  timer.unref();
@@ -13359,14 +13359,14 @@ function throwIfAborted(signal) {
13359
13359
  }
13360
13360
  async function defaultSleep2(ms, signal) {
13361
13361
  if (!signal) {
13362
- await new Promise((resolve12) => setTimeout(resolve12, ms));
13362
+ await new Promise((resolve13) => setTimeout(resolve13, ms));
13363
13363
  return;
13364
13364
  }
13365
13365
  throwIfAborted(signal);
13366
- await new Promise((resolve12, reject) => {
13366
+ await new Promise((resolve13, reject) => {
13367
13367
  const timer = setTimeout(() => {
13368
13368
  signal.removeEventListener("abort", onAbort);
13369
- resolve12();
13369
+ resolve13();
13370
13370
  }, ms);
13371
13371
  const onAbort = () => {
13372
13372
  clearTimeout(timer);
@@ -33237,7 +33237,7 @@ var OPEN_WORDS = /* @__PURE__ */ new Set(["then", "do", "else", "{", "(", "&&",
33237
33237
  function canonicalHookBlock(text) {
33238
33238
  const tokens = [];
33239
33239
  let word = "";
33240
- let quote;
33240
+ let quote2;
33241
33241
  const separate = () => {
33242
33242
  const last = tokens.at(-1);
33243
33243
  if (last !== void 0 && last !== ";" && !OPEN_WORDS.has(last)) tokens.push(";");
@@ -33252,13 +33252,13 @@ function canonicalHookBlock(text) {
33252
33252
  };
33253
33253
  for (let index = 0; index < text.length; index += 1) {
33254
33254
  const char = text[index];
33255
- if (quote) {
33255
+ if (quote2) {
33256
33256
  word += char;
33257
- if (char === quote) quote = void 0;
33257
+ if (char === quote2) quote2 = void 0;
33258
33258
  continue;
33259
33259
  }
33260
33260
  if (char === "'" || char === '"') {
33261
- quote = char;
33261
+ quote2 = char;
33262
33262
  word += char;
33263
33263
  } else if (char === "#" && word === "") {
33264
33264
  const end = text.indexOf("\n", index);
@@ -33849,15 +33849,18 @@ function hasSafeRuntimeLayout(paths, selected) {
33849
33849
  (relativePath) => privateFile(join11(selected.dir, relativePath), DATA_FILE_MODE)
33850
33850
  );
33851
33851
  }
33852
- function recordedNodeMatchesCurrentProcess(nodePath) {
33852
+ function sameNodeExecutable(recorded, desired) {
33853
33853
  try {
33854
- if (!statSync2(nodePath).isFile()) return false;
33855
- accessSync(nodePath, constants2.X_OK);
33856
- return realpathSync2(nodePath) === realpathSync2(process.execPath);
33854
+ if (!statSync2(recorded).isFile()) return false;
33855
+ accessSync(recorded, constants2.X_OK);
33856
+ return realpathSync2(recorded) === realpathSync2(desired);
33857
33857
  } catch {
33858
33858
  return false;
33859
33859
  }
33860
33860
  }
33861
+ function recordedNodeMatchesCurrentProcess(nodePath) {
33862
+ return sameNodeExecutable(nodePath, process.execPath);
33863
+ }
33861
33864
  function inspectHookRuntime(options = {}) {
33862
33865
  let paths;
33863
33866
  try {
@@ -33984,7 +33987,7 @@ function stageHookRuntime(options = {}) {
33984
33987
  if (precedence === void 0) {
33985
33988
  throw new Error("cannot stage hook runtime: selected release version is malformed");
33986
33989
  }
33987
- const selectRequested = !selected || precedence < 0;
33990
+ const selectRequested = !selected || precedence < 0 || precedence === 0 && !sameNodeExecutable(selected.manifest.nodePath, nodePath);
33988
33991
  const requestedExists = existsSync5(releaseDir);
33989
33992
  const protectedBefore = new Set(selected ? [selected.name] : []);
33990
33993
  if (selectRequested && requestedExists) protectedBefore.add(releaseName);
@@ -35939,8 +35942,8 @@ ${verificationUrl}`);
35939
35942
  const state = base64url(randomBytes5(16));
35940
35943
  const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
35941
35944
  let settle;
35942
- const outcome = new Promise((resolve12) => {
35943
- settle = resolve12;
35945
+ const outcome = new Promise((resolve13) => {
35946
+ settle = resolve13;
35944
35947
  });
35945
35948
  const server = createServer((req, res) => {
35946
35949
  const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
@@ -35954,12 +35957,12 @@ ${verificationUrl}`);
35954
35957
  res.end(page.html, () => settle(page.result));
35955
35958
  });
35956
35959
  try {
35957
- await new Promise((resolve12, reject) => {
35960
+ await new Promise((resolve13, reject) => {
35958
35961
  const onError = (err) => reject(err);
35959
35962
  server.once("error", onError);
35960
35963
  server.listen(CALLBACK_PORT, LOCALHOST, () => {
35961
35964
  server.removeListener("error", onError);
35962
- resolve12();
35965
+ resolve13();
35963
35966
  });
35964
35967
  });
35965
35968
  } catch (err) {
@@ -37925,7 +37928,7 @@ async function runPinnedEnsure(options) {
37925
37928
  npm_config_fetch_retry_maxtimeout: "5000",
37926
37929
  npm_config_fetch_timeout: "15000"
37927
37930
  };
37928
- return await new Promise((resolve12) => {
37931
+ return await new Promise((resolve13) => {
37929
37932
  let settled = false;
37930
37933
  let child;
37931
37934
  try {
@@ -37935,7 +37938,7 @@ async function runPinnedEnsure(options) {
37935
37938
  { env: env4, stdio: "ignore" }
37936
37939
  );
37937
37940
  } catch {
37938
- resolve12(false);
37941
+ resolve13(false);
37939
37942
  return;
37940
37943
  }
37941
37944
  const timer = setTimeout(() => {
@@ -37946,7 +37949,7 @@ async function runPinnedEnsure(options) {
37946
37949
  if (settled) return;
37947
37950
  settled = true;
37948
37951
  clearTimeout(timer);
37949
- resolve12(result);
37952
+ resolve13(result);
37950
37953
  };
37951
37954
  timer.unref();
37952
37955
  child.once("error", () => finish(false));
@@ -39360,7 +39363,7 @@ function clearStaleArtifacts() {
39360
39363
  }
39361
39364
  }
39362
39365
  function sleep(ms) {
39363
- return new Promise((resolve12) => setTimeout(resolve12, ms));
39366
+ return new Promise((resolve13) => setTimeout(resolve13, ms));
39364
39367
  }
39365
39368
  function spawnDaemon(options) {
39366
39369
  const file = binFile(DAEMON_BIN);
@@ -42510,526 +42513,1577 @@ function registerDecisionsCommands(program3) {
42510
42513
  });
42511
42514
  }
42512
42515
 
42513
- // src/commands/doctor.ts
42514
- import { existsSync as existsSync16 } from "fs";
42515
-
42516
- // src/decisions/feedback.ts
42517
- var FEEDBACK_PROTOCOL_VERSION = 2;
42518
- var FEEDBACK_MIN_PROTOCOL_VERSION = 1;
42519
- var STATUS_PATH = "/api/cli/decisions/feedback/status";
42520
- function isRecord2(value) {
42521
- return typeof value === "object" && value !== null && !Array.isArray(value);
42522
- }
42523
- function isSupportedProtocolVersion(value) {
42524
- return Number.isSafeInteger(value) && Number(value) >= FEEDBACK_MIN_PROTOCOL_VERSION && Number(value) <= FEEDBACK_PROTOCOL_VERSION;
42525
- }
42526
- function parseFeedbackCapability(value) {
42527
- if (!isRecord2(value) || !isSupportedProtocolVersion(value.protocolVersion)) return void 0;
42528
- if (value.status === "available") return { status: "available" };
42529
- if (value.status === "unavailable" && value.reason === "organization_unbound") {
42530
- return { status: "unavailable", reason: "organization_unbound" };
42531
- }
42532
- return void 0;
42533
- }
42534
- async function fetchFeedbackCapability(signal, client = getClient()) {
42535
- const result = parseFeedbackCapability(await client.get(STATUS_PATH, { signal }));
42536
- if (!result) throw new Error("server returned an unsupported decision-feedback contract");
42537
- return result;
42538
- }
42539
-
42540
- // src/protocol/decision-lifecycle.ts
42541
- var DECISION_LIFECYCLE_PROTOCOL_VERSION = 2;
42542
-
42543
- // src/journal-organization.ts
42544
- var ORGANIZATION_BINDING_VERSION = 1;
42545
- var ORGANIZATION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
42546
- var UNBOUND_BUCKET = "_unbound";
42547
- var InvalidJournalEnvelopeError = class extends Error {
42548
- constructor() {
42549
- super("Invalid locally journaled move");
42550
- this.name = "InvalidJournalEnvelopeError";
42551
- }
42552
- };
42553
- function safeOrganizationId(value) {
42554
- return typeof value === "string" && ORGANIZATION_ID_RE.test(value);
42555
- }
42556
- function isCaptureAuthorityKind(value) {
42557
- return value === "workos" || value === "service_token";
42516
+ // node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
42517
+ function Diff() {
42558
42518
  }
42559
- function parseOrganizationBinding(value) {
42560
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
42561
- return { state: "server_contract_unavailable" };
42562
- }
42563
- const record3 = value;
42564
- if (record3.authenticated !== true || record3.organizationBindingVersion !== ORGANIZATION_BINDING_VERSION || !isCaptureAuthorityKind(record3.captureAuthorityKind)) {
42565
- return { state: "server_contract_unavailable" };
42566
- }
42567
- if (record3.organizationId === null && record3.workosOrganizationId === null) {
42568
- return { state: "no_current_organization" };
42569
- }
42570
- if (safeOrganizationId(record3.organizationId) && record3.workosOrganizationId === null) {
42571
- return { state: "organization_identity_unreconciled" };
42572
- }
42573
- if (!safeOrganizationId(record3.organizationId) || !safeOrganizationId(record3.workosOrganizationId)) {
42574
- return { state: "server_contract_unavailable" };
42575
- }
42576
- return {
42577
- state: "current",
42578
- binding: {
42579
- captureAuthorityKind: record3.captureAuthorityKind,
42580
- organizationId: record3.organizationId,
42581
- workosOrganizationId: record3.workosOrganizationId
42519
+ Diff.prototype = {
42520
+ diff: function diff(oldString, newString) {
42521
+ var _options$timeout;
42522
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
42523
+ var callback = options.callback;
42524
+ if (typeof options === "function") {
42525
+ callback = options;
42526
+ options = {};
42582
42527
  }
42583
- };
42584
- }
42585
- function summarizeRetainedBuckets(retained) {
42586
- const counts = /* @__PURE__ */ new Map();
42587
- for (const item of retained) {
42588
- counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
42589
- }
42590
- return [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([reason, count]) => `${reason}:${String(count)}`).join(", ");
42591
- }
42592
- function classifyJournalBuckets(buckets, binding) {
42593
- const deliverableBuckets = /* @__PURE__ */ new Set();
42594
- const retainedBuckets = [];
42595
- for (const bucket of [...new Set(buckets)].sort()) {
42596
- if (bucket === UNBOUND_BUCKET) {
42597
- retainedBuckets.push({ bucket, reason: "unbound" });
42598
- continue;
42528
+ this.options = options;
42529
+ var self = this;
42530
+ function done(value) {
42531
+ if (callback) {
42532
+ setTimeout(function() {
42533
+ callback(void 0, value);
42534
+ }, 0);
42535
+ return true;
42536
+ } else {
42537
+ return value;
42538
+ }
42599
42539
  }
42600
- if (typeof binding === "string") {
42601
- retainedBuckets.push({ bucket, reason: binding });
42602
- continue;
42540
+ oldString = this.castInput(oldString);
42541
+ newString = this.castInput(newString);
42542
+ oldString = this.removeEmpty(this.tokenize(oldString));
42543
+ newString = this.removeEmpty(this.tokenize(newString));
42544
+ var newLen = newString.length, oldLen = oldString.length;
42545
+ var editLength = 1;
42546
+ var maxEditLength = newLen + oldLen;
42547
+ if (options.maxEditLength) {
42548
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
42603
42549
  }
42604
- if (bucket === binding.organizationId || bucket === binding.workosOrganizationId) {
42605
- deliverableBuckets.add(bucket);
42606
- } else {
42607
- retainedBuckets.push({ bucket, reason: "organization_mismatch" });
42550
+ var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;
42551
+ var abortAfterTimestamp = Date.now() + maxExecutionTime;
42552
+ var bestPath = [{
42553
+ oldPos: -1,
42554
+ lastComponent: void 0
42555
+ }];
42556
+ var newPos = this.extractCommon(bestPath[0], newString, oldString, 0);
42557
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
42558
+ return done([{
42559
+ value: this.join(newString),
42560
+ count: newString.length
42561
+ }]);
42608
42562
  }
42609
- }
42610
- return { deliverableBuckets, retainedBuckets };
42611
- }
42612
- function buildOrganizationBoundMoveRequest(batch, binding) {
42613
- const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
42614
- const request2 = {
42615
- batch: batch.map((move) => {
42616
- if (typeof move !== "object" || move === null || Array.isArray(move)) {
42617
- return move;
42563
+ var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
42564
+ function execEditLength() {
42565
+ for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
42566
+ var basePath = void 0;
42567
+ var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
42568
+ if (removePath) {
42569
+ bestPath[diagonalPath - 1] = void 0;
42570
+ }
42571
+ var canAdd = false;
42572
+ if (addPath) {
42573
+ var addPathNewPos = addPath.oldPos - diagonalPath;
42574
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
42575
+ }
42576
+ var canRemove = removePath && removePath.oldPos + 1 < oldLen;
42577
+ if (!canAdd && !canRemove) {
42578
+ bestPath[diagonalPath] = void 0;
42579
+ continue;
42580
+ }
42581
+ if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) {
42582
+ basePath = self.addToPath(addPath, true, void 0, 0);
42583
+ } else {
42584
+ basePath = self.addToPath(removePath, void 0, true, 1);
42585
+ }
42586
+ newPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
42587
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
42588
+ return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken));
42589
+ } else {
42590
+ bestPath[diagonalPath] = basePath;
42591
+ if (basePath.oldPos + 1 >= oldLen) {
42592
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
42593
+ }
42594
+ if (newPos + 1 >= newLen) {
42595
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
42596
+ }
42597
+ }
42598
+ }
42599
+ editLength++;
42600
+ }
42601
+ if (callback) {
42602
+ (function exec2() {
42603
+ setTimeout(function() {
42604
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
42605
+ return callback();
42606
+ }
42607
+ if (!execEditLength()) {
42608
+ exec2();
42609
+ }
42610
+ }, 0);
42611
+ })();
42612
+ } else {
42613
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
42614
+ var ret = execEditLength();
42615
+ if (ret) {
42616
+ return ret;
42617
+ }
42618
42618
  }
42619
+ }
42620
+ },
42621
+ addToPath: function addToPath(path9, added, removed, oldPosInc) {
42622
+ var last = path9.lastComponent;
42623
+ if (last && last.added === added && last.removed === removed) {
42619
42624
  return {
42620
- ...move,
42621
- envelopeVersion: 4,
42622
- capturedOrganizationId,
42623
- captureAuthorityKind: binding.captureAuthorityKind,
42624
- decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
42625
+ oldPos: path9.oldPos + oldPosInc,
42626
+ lastComponent: {
42627
+ count: last.count + 1,
42628
+ added,
42629
+ removed,
42630
+ previousComponent: last.previousComponent
42631
+ }
42625
42632
  };
42626
- })
42627
- };
42628
- if (!isMoveIngestRequest(request2)) {
42629
- throw new InvalidJournalEnvelopeError();
42633
+ } else {
42634
+ return {
42635
+ oldPos: path9.oldPos + oldPosInc,
42636
+ lastComponent: {
42637
+ count: 1,
42638
+ added,
42639
+ removed,
42640
+ previousComponent: last
42641
+ }
42642
+ };
42643
+ }
42644
+ },
42645
+ extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
42646
+ var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
42647
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
42648
+ newPos++;
42649
+ oldPos++;
42650
+ commonCount++;
42651
+ }
42652
+ if (commonCount) {
42653
+ basePath.lastComponent = {
42654
+ count: commonCount,
42655
+ previousComponent: basePath.lastComponent
42656
+ };
42657
+ }
42658
+ basePath.oldPos = oldPos;
42659
+ return newPos;
42660
+ },
42661
+ equals: function equals(left, right) {
42662
+ if (this.options.comparator) {
42663
+ return this.options.comparator(left, right);
42664
+ } else {
42665
+ return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
42666
+ }
42667
+ },
42668
+ removeEmpty: function removeEmpty(array) {
42669
+ var ret = [];
42670
+ for (var i = 0; i < array.length; i++) {
42671
+ if (array[i]) {
42672
+ ret.push(array[i]);
42673
+ }
42674
+ }
42675
+ return ret;
42676
+ },
42677
+ castInput: function castInput(value) {
42678
+ return value;
42679
+ },
42680
+ tokenize: function tokenize(value) {
42681
+ return value.split("");
42682
+ },
42683
+ join: function join20(chars) {
42684
+ return chars.join("");
42630
42685
  }
42631
- return request2;
42632
- }
42633
- async function inspectJournalDelivery(buckets, options = {}) {
42634
- const bucketList = [...new Set(buckets)];
42635
- let client;
42636
- try {
42637
- client = options.client ?? await (options.createClient ?? (() => getPinnedClient()))();
42638
- } catch {
42639
- return classifyJournalBuckets(bucketList, "identity_unavailable");
42686
+ };
42687
+ function buildValues(diff2, lastComponent, newString, oldString, useLongestToken) {
42688
+ var components = [];
42689
+ var nextComponent;
42690
+ while (lastComponent) {
42691
+ components.push(lastComponent);
42692
+ nextComponent = lastComponent.previousComponent;
42693
+ delete lastComponent.previousComponent;
42694
+ lastComponent = nextComponent;
42640
42695
  }
42641
- let parsed;
42642
- try {
42643
- parsed = parseOrganizationBinding(
42644
- await client.get("/api/cli/auth/status", {
42645
- signal: AbortSignal.timeout(1e4),
42646
- quietRefresh: true
42647
- })
42648
- );
42649
- } catch {
42650
- return classifyJournalBuckets(bucketList, "identity_unavailable");
42696
+ components.reverse();
42697
+ var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
42698
+ for (; componentPos < componentLen; componentPos++) {
42699
+ var component = components[componentPos];
42700
+ if (!component.removed) {
42701
+ if (!component.added && useLongestToken) {
42702
+ var value = newString.slice(newPos, newPos + component.count);
42703
+ value = value.map(function(value2, i) {
42704
+ var oldValue = oldString[oldPos + i];
42705
+ return oldValue.length > value2.length ? oldValue : value2;
42706
+ });
42707
+ component.value = diff2.join(value);
42708
+ } else {
42709
+ component.value = diff2.join(newString.slice(newPos, newPos + component.count));
42710
+ }
42711
+ newPos += component.count;
42712
+ if (!component.added) {
42713
+ oldPos += component.count;
42714
+ }
42715
+ } else {
42716
+ component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
42717
+ oldPos += component.count;
42718
+ if (componentPos && components[componentPos - 1].added) {
42719
+ var tmp = components[componentPos - 1];
42720
+ components[componentPos - 1] = components[componentPos];
42721
+ components[componentPos] = tmp;
42722
+ }
42723
+ }
42651
42724
  }
42652
- if (parsed.state !== "current") {
42653
- return classifyJournalBuckets(bucketList, parsed.state);
42725
+ var finalComponent = components[componentLen - 1];
42726
+ if (componentLen > 1 && typeof finalComponent.value === "string" && (finalComponent.added || finalComponent.removed) && diff2.equals("", finalComponent.value)) {
42727
+ components[componentLen - 2].value += finalComponent.value;
42728
+ components.pop();
42654
42729
  }
42655
- return {
42656
- client,
42657
- binding: parsed.binding,
42658
- ...classifyJournalBuckets(bucketList, parsed.binding)
42659
- };
42660
- }
42661
-
42662
- // src/journal.ts
42663
- import {
42664
- appendFileSync,
42665
- closeSync as closeSync5,
42666
- existsSync as existsSync14,
42667
- fstatSync as fstatSync2,
42668
- mkdirSync as mkdirSync11,
42669
- openSync as openSync5,
42670
- opendirSync,
42671
- readFileSync as readFileSync17,
42672
- readSync as readSync2,
42673
- readdirSync as readdirSync6
42674
- } from "fs";
42675
- import { dirname as dirname12, join as join21 } from "path";
42676
-
42677
- // src/drain-progress.ts
42678
- import {
42679
- chmodSync as chmodSync6,
42680
- existsSync as existsSync13,
42681
- readFileSync as readFileSync16,
42682
- readdirSync as readdirSync5,
42683
- rmSync as rmSync6,
42684
- rmdirSync
42685
- } from "fs";
42686
- import { basename as basename4, dirname as dirname11, join as join20 } from "path";
42687
- var DIRECTORY_MODE3 = 448;
42688
- var FILE_MODE2 = 384;
42689
- var DRAIN_PROGRESS_DIRNAME = "drain-progress";
42690
- var CHECKPOINT_NAME = /^(.+)\.json(?:\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp)?$/;
42691
- function rotationIdentity(stat) {
42692
- return { size: stat.size, ino: stat.ino, dev: stat.dev };
42693
- }
42694
- function drainProgressDirectory(flushingPath) {
42695
- return join20(dirname11(flushingPath), DRAIN_PROGRESS_DIRNAME);
42696
- }
42697
- function drainProgressPath(flushingPath) {
42698
- return join20(drainProgressDirectory(flushingPath), `${basename4(flushingPath)}.json`);
42699
- }
42700
- function isByteCount(value) {
42701
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
42730
+ return components;
42702
42731
  }
42703
- function drainResumeOffset(flushingPath, rotation) {
42704
- let parsed;
42705
- try {
42706
- parsed = JSON.parse(readFileSync16(drainProgressPath(flushingPath), "utf8"));
42707
- } catch {
42708
- return 0;
42709
- }
42710
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
42711
- return 0;
42712
- }
42713
- const { v, offset, size, ino, dev } = parsed;
42714
- if (v !== 2 || ino !== rotation.ino || dev !== rotation.dev || size !== rotation.size || !isByteCount(offset) || offset > rotation.size) {
42715
- return 0;
42732
+ var characterDiff = new Diff();
42733
+ var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
42734
+ var reWhitespace = /\S/;
42735
+ var wordDiff = new Diff();
42736
+ wordDiff.equals = function(left, right) {
42737
+ if (this.options.ignoreCase) {
42738
+ left = left.toLowerCase();
42739
+ right = right.toLowerCase();
42716
42740
  }
42717
- return offset;
42718
- }
42719
- function writeDrainCheckpoint(flushingPath, checkpoint) {
42720
- const directory = drainProgressDirectory(flushingPath);
42721
- ensureDurableDirectory(directory, DIRECTORY_MODE3);
42722
- chmodSync6(directory, DIRECTORY_MODE3);
42723
- atomicWriteFile(drainProgressPath(flushingPath), `${JSON.stringify(checkpoint)}
42724
- `, {
42725
- mode: FILE_MODE2
42726
- });
42727
- }
42728
- function removeEmptyDirectory(directory) {
42729
- try {
42730
- rmdirSync(directory);
42731
- } catch (error) {
42732
- const code = error.code;
42733
- if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST") {
42734
- throw error;
42741
+ return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
42742
+ };
42743
+ wordDiff.tokenize = function(value) {
42744
+ var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
42745
+ for (var i = 0; i < tokens.length - 1; i++) {
42746
+ if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
42747
+ tokens[i] += tokens[i + 2];
42748
+ tokens.splice(i + 1, 2);
42749
+ i--;
42735
42750
  }
42736
42751
  }
42737
- }
42738
- function removeDrainCheckpoint(flushingPath) {
42739
- rmSync6(drainProgressPath(flushingPath), { force: true });
42740
- removeEmptyDirectory(drainProgressDirectory(flushingPath));
42741
- }
42742
- function sweepOrphanedDrainCheckpoints(bucketDirectory) {
42743
- const directory = join20(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
42744
- let names;
42745
- try {
42746
- names = readdirSync5(directory);
42747
- } catch {
42748
- return;
42752
+ return tokens;
42753
+ };
42754
+ var lineDiff = new Diff();
42755
+ lineDiff.tokenize = function(value) {
42756
+ if (this.options.stripTrailingCr) {
42757
+ value = value.replace(/\r\n/g, "\n");
42749
42758
  }
42750
- for (const name of names) {
42751
- const rotation = CHECKPOINT_NAME.exec(name)?.[1];
42752
- if (rotation === void 0 || existsSync13(join20(bucketDirectory, rotation))) {
42753
- continue;
42754
- }
42755
- try {
42756
- rmSync6(join20(directory, name), { force: true });
42757
- } catch {
42758
- }
42759
+ var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
42760
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
42761
+ linesAndNewlines.pop();
42759
42762
  }
42760
- try {
42761
- removeEmptyDirectory(directory);
42762
- } catch {
42763
+ for (var i = 0; i < linesAndNewlines.length; i++) {
42764
+ var line = linesAndNewlines[i];
42765
+ if (i % 2 && !this.options.newlineIsToken) {
42766
+ retLines[retLines.length - 1] += line;
42767
+ } else {
42768
+ if (this.options.ignoreWhitespace) {
42769
+ line = line.trim();
42770
+ }
42771
+ retLines.push(line);
42772
+ }
42763
42773
  }
42774
+ return retLines;
42775
+ };
42776
+ function diffLines(oldStr, newStr, callback) {
42777
+ return lineDiff.diff(oldStr, newStr, callback);
42764
42778
  }
42765
-
42766
- // src/journal.ts
42767
- var JOURNAL_DIR = join21(primConfigDirectory(), "moves");
42768
- var JOURNAL_BASENAME = "journal.ndjson";
42769
- var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
42770
- var PENDING_STATS_MAX_FILES = 128;
42771
- function envSlug(apiUrl) {
42772
- const slug = apiUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
42773
- if (slug.length === 0 || slug === "." || slug === "..") {
42774
- return "default";
42779
+ var sentenceDiff = new Diff();
42780
+ sentenceDiff.tokenize = function(value) {
42781
+ return value.split(/(\S.+?[.!?])(?=\s+|$)/);
42782
+ };
42783
+ var cssDiff = new Diff();
42784
+ cssDiff.tokenize = function(value) {
42785
+ return value.split(/([{}:;,]|\s+)/);
42786
+ };
42787
+ function _typeof(obj) {
42788
+ "@babel/helpers - typeof";
42789
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
42790
+ _typeof = function(obj2) {
42791
+ return typeof obj2;
42792
+ };
42793
+ } else {
42794
+ _typeof = function(obj2) {
42795
+ return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
42796
+ };
42775
42797
  }
42776
- return slug;
42777
- }
42778
- function currentEnvDir() {
42779
- return join21(JOURNAL_DIR, envSlug(getSiteUrl()));
42798
+ return _typeof(obj);
42780
42799
  }
42781
- function parseMoves(content) {
42782
- const moves = [];
42783
- for (const line of content.split("\n")) {
42784
- if (line.length === 0) {
42785
- continue;
42786
- }
42787
- try {
42788
- moves.push(JSON.parse(line));
42789
- } catch {
42790
- }
42791
- }
42792
- return moves;
42800
+ function _toConsumableArray(arr) {
42801
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
42793
42802
  }
42794
- function readMovesFromPath(path9) {
42795
- if (!existsSync14(path9)) {
42796
- return [];
42797
- }
42798
- return parseMoves(readFileSync17(path9, "utf-8"));
42803
+ function _arrayWithoutHoles(arr) {
42804
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
42799
42805
  }
42800
- function listBuckets() {
42801
- const out = [];
42802
- const envDir = currentEnvDir();
42803
- if (!existsSync14(envDir)) {
42804
- return out;
42806
+ function _iterableToArray(iter) {
42807
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
42808
+ }
42809
+ function _unsupportedIterableToArray(o, minLen) {
42810
+ if (!o) return;
42811
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
42812
+ var n = Object.prototype.toString.call(o).slice(8, -1);
42813
+ if (n === "Object" && o.constructor) n = o.constructor.name;
42814
+ if (n === "Map" || n === "Set") return Array.from(o);
42815
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
42816
+ }
42817
+ function _arrayLikeToArray(arr, len) {
42818
+ if (len == null || len > arr.length) len = arr.length;
42819
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
42820
+ return arr2;
42821
+ }
42822
+ function _nonIterableSpread() {
42823
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
42824
+ }
42825
+ var objectPrototypeToString = Object.prototype.toString;
42826
+ var jsonDiff = new Diff();
42827
+ jsonDiff.useLongestToken = true;
42828
+ jsonDiff.tokenize = lineDiff.tokenize;
42829
+ jsonDiff.castInput = function(value) {
42830
+ var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
42831
+ return typeof v === "undefined" ? undefinedReplacement : v;
42832
+ } : _this$options$stringi;
42833
+ return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
42834
+ };
42835
+ jsonDiff.equals = function(left, right) {
42836
+ return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
42837
+ };
42838
+ function canonicalize(obj, stack, replacementStack, replacer, key) {
42839
+ stack = stack || [];
42840
+ replacementStack = replacementStack || [];
42841
+ if (replacer) {
42842
+ obj = replacer(key, obj);
42805
42843
  }
42806
- for (const entry of readdirSync6(envDir, { withFileTypes: true })) {
42807
- if (!entry.isDirectory()) {
42808
- continue;
42809
- }
42810
- const path9 = join21(envDir, entry.name, JOURNAL_BASENAME);
42811
- if (existsSync14(path9)) {
42812
- out.push({ bucket: entry.name, path: path9 });
42844
+ var i;
42845
+ for (i = 0; i < stack.length; i += 1) {
42846
+ if (stack[i] === obj) {
42847
+ return replacementStack[i];
42813
42848
  }
42814
42849
  }
42815
- return out;
42816
- }
42817
- var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
42818
- function oldestCapturedAt(moves) {
42819
- let oldest;
42820
- for (const move of moves) {
42821
- if (!Number.isFinite(move.capturedAt)) {
42822
- continue;
42850
+ var canonicalizedObj;
42851
+ if ("[object Array]" === objectPrototypeToString.call(obj)) {
42852
+ stack.push(obj);
42853
+ canonicalizedObj = new Array(obj.length);
42854
+ replacementStack.push(canonicalizedObj);
42855
+ for (i = 0; i < obj.length; i += 1) {
42856
+ canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
42823
42857
  }
42824
- oldest = oldest === void 0 ? move.capturedAt : Math.min(oldest, move.capturedAt);
42858
+ stack.pop();
42859
+ replacementStack.pop();
42860
+ return canonicalizedObj;
42825
42861
  }
42826
- return oldest;
42827
- }
42828
- function sampleJournalFile(path9, maxBytes = JOURNAL_STATS_SAMPLE_BYTES, options = {}) {
42829
- const fd = openSync5(path9, "r");
42830
- try {
42831
- const initial = fstatSync2(fd);
42832
- const start = options.fromDrainCheckpoint ? drainResumeOffset(path9, rotationIdentity(initial)) : 0;
42833
- const target = Math.min(initial.size - start, Math.max(0, maxBytes));
42834
- const buffer = Buffer.allocUnsafe(target);
42835
- let sampledBytes = 0;
42836
- while (sampledBytes < target) {
42837
- const count = readSync2(fd, buffer, sampledBytes, target - sampledBytes, start + sampledBytes);
42838
- if (count === 0) {
42839
- break;
42862
+ if (obj && obj.toJSON) {
42863
+ obj = obj.toJSON();
42864
+ }
42865
+ if (_typeof(obj) === "object" && obj !== null) {
42866
+ stack.push(obj);
42867
+ canonicalizedObj = {};
42868
+ replacementStack.push(canonicalizedObj);
42869
+ var sortedKeys = [], _key;
42870
+ for (_key in obj) {
42871
+ if (obj.hasOwnProperty(_key)) {
42872
+ sortedKeys.push(_key);
42840
42873
  }
42841
- sampledBytes += count;
42842
42874
  }
42843
- const stat = fstatSync2(fd);
42844
- const sampled = stat.size - start > sampledBytes;
42845
- let content = buffer.subarray(0, sampledBytes).toString("utf-8");
42846
- if (sampled) {
42847
- const lastNewline = content.lastIndexOf("\n");
42848
- content = lastNewline === -1 ? "" : content.slice(0, lastNewline + 1);
42875
+ sortedKeys.sort();
42876
+ for (i = 0; i < sortedKeys.length; i += 1) {
42877
+ _key = sortedKeys[i];
42878
+ canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
42849
42879
  }
42850
- const lines = content.split("\n").filter((line) => line.length > 0);
42851
- const moves = parseMoves(content);
42852
- return {
42853
- sizeBytes: stat.size,
42854
- pendingBytes: Math.max(0, stat.size - start),
42855
- mtimeMs: stat.mtimeMs,
42856
- lineCount: sampled && stat.size > 0 ? Math.max(1, lines.length) : lines.length,
42857
- oldestCapturedAt: oldestCapturedAt(moves),
42858
- sampled,
42859
- sampledBytes
42860
- };
42861
- } finally {
42862
- closeSync5(fd);
42880
+ stack.pop();
42881
+ replacementStack.pop();
42882
+ } else {
42883
+ canonicalizedObj = obj;
42863
42884
  }
42885
+ return canonicalizedObj;
42864
42886
  }
42865
- function parseFlushingPid(name) {
42866
- const segments = name.slice(FLUSHING_PREFIX.length).split(".");
42867
- const last = segments.length >= 2 ? segments[segments.length - 1] : void 0;
42868
- if (last === void 0 || !/^[0-9]+$/.test(last)) return void 0;
42869
- const pid = Number(last);
42870
- return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
42871
- }
42872
- function listFlushingInDir(dir, bucket, options = {}) {
42873
- if (!existsSync14(dir)) {
42874
- return [];
42887
+ var arrayDiff = new Diff();
42888
+ arrayDiff.tokenize = function(value) {
42889
+ return value.slice();
42890
+ };
42891
+ arrayDiff.join = arrayDiff.removeEmpty = function(value) {
42892
+ return value;
42893
+ };
42894
+ function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
42895
+ if (!options) {
42896
+ options = {};
42875
42897
  }
42876
- const out = [];
42877
- let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
42878
- const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
42879
- const entries = opendirSync(dir);
42880
- try {
42881
- let entry = entries.readSync();
42882
- while (entry && out.length < maxFiles) {
42883
- if (!entry.isFile() || !entry.name.startsWith(FLUSHING_PREFIX)) {
42884
- entry = entries.readSync();
42885
- continue;
42898
+ if (typeof options.context === "undefined") {
42899
+ options.context = 4;
42900
+ }
42901
+ var diff2 = diffLines(oldStr, newStr, options);
42902
+ if (!diff2) {
42903
+ return;
42904
+ }
42905
+ diff2.push({
42906
+ value: "",
42907
+ lines: []
42908
+ });
42909
+ function contextLines(lines) {
42910
+ return lines.map(function(entry) {
42911
+ return " " + entry;
42912
+ });
42913
+ }
42914
+ var hunks = [];
42915
+ var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
42916
+ var _loop = function _loop2(i2) {
42917
+ var current = diff2[i2], lines = current.lines || current.value.replace(/\n$/, "").split("\n");
42918
+ current.lines = lines;
42919
+ if (current.added || current.removed) {
42920
+ var _curRange;
42921
+ if (!oldRangeStart) {
42922
+ var prev = diff2[i2 - 1];
42923
+ oldRangeStart = oldLine;
42924
+ newRangeStart = newLine;
42925
+ if (prev) {
42926
+ curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
42927
+ oldRangeStart -= curRange.length;
42928
+ newRangeStart -= curRange.length;
42929
+ }
42886
42930
  }
42887
- const path9 = join21(dir, entry.name);
42888
- let sample;
42889
- try {
42890
- sample = sampleJournalFile(path9, remainingBytes, { fromDrainCheckpoint: true });
42891
- } catch (err) {
42892
- if (err.code === "ENOENT") {
42893
- entry = entries.readSync();
42894
- continue;
42931
+ (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) {
42932
+ return (current.added ? "+" : "-") + entry;
42933
+ })));
42934
+ if (current.added) {
42935
+ newLine += lines.length;
42936
+ } else {
42937
+ oldLine += lines.length;
42938
+ }
42939
+ } else {
42940
+ if (oldRangeStart) {
42941
+ if (lines.length <= options.context * 2 && i2 < diff2.length - 2) {
42942
+ var _curRange2;
42943
+ (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
42944
+ } else {
42945
+ var _curRange3;
42946
+ var contextSize = Math.min(lines.length, options.context);
42947
+ (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
42948
+ var hunk = {
42949
+ oldStart: oldRangeStart,
42950
+ oldLines: oldLine - oldRangeStart + contextSize,
42951
+ newStart: newRangeStart,
42952
+ newLines: newLine - newRangeStart + contextSize,
42953
+ lines: curRange
42954
+ };
42955
+ if (i2 >= diff2.length - 2 && lines.length <= options.context) {
42956
+ var oldEOFNewline = /\n$/.test(oldStr);
42957
+ var newEOFNewline = /\n$/.test(newStr);
42958
+ var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
42959
+ if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
42960
+ curRange.splice(hunk.oldLines, 0, "\");
42961
+ }
42962
+ if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
42963
+ curRange.push("\");
42964
+ }
42965
+ }
42966
+ hunks.push(hunk);
42967
+ oldRangeStart = 0;
42968
+ newRangeStart = 0;
42969
+ curRange = [];
42895
42970
  }
42896
- throw err;
42897
42971
  }
42898
- remainingBytes = Math.max(0, remainingBytes - sample.sampledBytes);
42899
- out.push({
42900
- bucket,
42901
- path: path9,
42902
- pid: parseFlushingPid(entry.name),
42903
- ...sample
42904
- });
42905
- entry = entries.readSync();
42972
+ oldLine += lines.length;
42973
+ newLine += lines.length;
42906
42974
  }
42907
- } finally {
42908
- entries.closeSync();
42975
+ };
42976
+ for (var i = 0; i < diff2.length; i++) {
42977
+ _loop(i);
42909
42978
  }
42910
- return out;
42979
+ return {
42980
+ oldFileName,
42981
+ newFileName,
42982
+ oldHeader,
42983
+ newHeader,
42984
+ hunks
42985
+ };
42911
42986
  }
42912
- function listFlushing(options = {}) {
42913
- const envDir = currentEnvDir();
42914
- if (!existsSync14(envDir)) {
42915
- return [];
42987
+ function formatPatch(diff2) {
42988
+ if (Array.isArray(diff2)) {
42989
+ return diff2.map(formatPatch).join("\n");
42916
42990
  }
42917
- const out = [];
42918
- let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
42919
- const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
42920
- for (const entry of readdirSync6(envDir, { withFileTypes: true })) {
42921
- if (out.length >= maxFiles) {
42922
- break;
42991
+ var ret = [];
42992
+ if (diff2.oldFileName == diff2.newFileName) {
42993
+ ret.push("Index: " + diff2.oldFileName);
42994
+ }
42995
+ ret.push("===================================================================");
42996
+ ret.push("--- " + diff2.oldFileName + (typeof diff2.oldHeader === "undefined" ? "" : " " + diff2.oldHeader));
42997
+ ret.push("+++ " + diff2.newFileName + (typeof diff2.newHeader === "undefined" ? "" : " " + diff2.newHeader));
42998
+ for (var i = 0; i < diff2.hunks.length; i++) {
42999
+ var hunk = diff2.hunks[i];
43000
+ if (hunk.oldLines === 0) {
43001
+ hunk.oldStart -= 1;
42923
43002
  }
42924
- if (entry.isDirectory()) {
42925
- const found = listFlushingInDir(join21(envDir, entry.name), entry.name, {
42926
- sampleBytes: remainingBytes,
42927
- maxFiles: maxFiles - out.length
42928
- });
42929
- out.push(...found);
42930
- remainingBytes = Math.max(
42931
- 0,
42932
- remainingBytes - found.reduce((count, file) => count + file.sampledBytes, 0)
42933
- );
43003
+ if (hunk.newLines === 0) {
43004
+ hunk.newStart -= 1;
42934
43005
  }
43006
+ ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
43007
+ ret.push.apply(ret, hunk.lines);
42935
43008
  }
42936
- return out;
43009
+ return ret.join("\n") + "\n";
42937
43010
  }
42938
- function sweepOrphanedDrainProgress() {
42939
- const envDir = currentEnvDir();
42940
- if (!existsSync14(envDir)) {
43011
+ function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
43012
+ return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
43013
+ }
43014
+ function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
43015
+ return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
43016
+ }
43017
+
43018
+ // src/demo/sandbox.ts
43019
+ import {
43020
+ existsSync as existsSync14,
43021
+ lstatSync as lstatSync9,
43022
+ mkdtempSync as mkdtempSync3,
43023
+ readFileSync as readFileSync17,
43024
+ readdirSync as readdirSync6,
43025
+ realpathSync as realpathSync5,
43026
+ rmdirSync,
43027
+ unlinkSync as unlinkSync5
43028
+ } from "fs";
43029
+ import { tmpdir } from "os";
43030
+ import { basename as basename4, dirname as dirname11, join as join22 } from "path";
43031
+
43032
+ // src/demo/scenario.ts
43033
+ var SAMPLE_NOTE = [
43034
+ "Fictional engineering conversation:",
43035
+ "Maya: Could we call fetch directly for the order service?",
43036
+ "Ravi: Use the shared HTTP client for service calls. We need retries and request tracing to stay consistent.",
43037
+ "Maya: Agreed. Let's reject direct fetch calls because they duplicate that policy.",
43038
+ "Ravi: Also, the team demo is at three."
43039
+ ].join("\n");
43040
+ var SAMPLE_DECISIONS = [
43041
+ {
43042
+ id: "demo-http-client",
43043
+ decision: "Use the shared HTTP client for service calls",
43044
+ stage: "provisional",
43045
+ source: "Fictional engineering conversation",
43046
+ evidence: [
43047
+ "Use the shared HTTP client for service calls. We need retries and request tracing to stay consistent.",
43048
+ "Let's reject direct fetch calls because they duplicate that policy."
43049
+ ],
43050
+ rationale: "Centralize retries and request tracing.",
43051
+ files: ["service.ts"],
43052
+ scopeBasis: "Demo mapping from service calls to service.ts; the conversation names no file.",
43053
+ alternativesRejected: ["Direct fetch calls with duplicated retry and tracing policy"]
43054
+ },
43055
+ {
43056
+ id: "demo-order-repository",
43057
+ decision: "Persist orders through the shared order repository",
43058
+ stage: "adopted",
43059
+ source: "User confirmation of this fictional proposal",
43060
+ rationale: "Keep validation and persistence consistent across order writers.",
43061
+ files: ["orders.ts"],
43062
+ alternativesRejected: ["Direct local-storage writes that bypass repository validation"]
43063
+ }
43064
+ ];
43065
+ var SAMPLE_FILES = {
43066
+ "service.ts": 'import { http } from "./shared";\nexport const loadOrders = () => http.get("/orders");\n',
43067
+ "orders.ts": "export const saveOrder = (_order: unknown) => {\n // TODO: persist this order.\n};\n",
43068
+ "shared.ts": "// Fictional interfaces; this tour does not execute network or storage operations.\nexport declare const http: { get(path: string): Promise<unknown> };\nexport declare const orders: { save(order: unknown): void };\n"
43069
+ };
43070
+ var WARNING_EDIT = 'export const loadOrders = () => fetch("/orders");\n';
43071
+ var BLOCKED_EDIT = 'export const saveOrder = (order: unknown) => localStorage.setItem("order", JSON.stringify(order));\n';
43072
+ var REPOSITORY_EDIT = 'import { orders } from "./shared";\nexport const saveOrder = (order: unknown) => orders.save(order);\n';
43073
+
43074
+ // src/demo/state.ts
43075
+ import { createHash as createHash9, randomUUID as randomUUID3 } from "crypto";
43076
+ import { existsSync as existsSync13, lstatSync as lstatSync8, readFileSync as readFileSync16, readdirSync as readdirSync5 } from "fs";
43077
+ import { join as join21, resolve as resolve8 } from "path";
43078
+ var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
43079
+ var demoDirectory = () => join21(primConfigDirectory(), "demo");
43080
+ var runPath = (id) => {
43081
+ if (!RUN_ID.test(id)) throw new Error("invalid demo run ID");
43082
+ return join21(demoDirectory(), "runs", `${id}.json`);
43083
+ };
43084
+ function readDemoJson(path9) {
43085
+ const stat = lstatSync8(path9);
43086
+ if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path9}`);
43087
+ return JSON.parse(readFileSync16(path9, "utf8"));
43088
+ }
43089
+ function saveDemoJson(path9, value) {
43090
+ atomicWriteFile(path9, `${JSON.stringify(value)}
43091
+ `, { mode: 384, ensureParent: true });
43092
+ }
43093
+ function readRun(id) {
43094
+ const run = readDemoJson(runPath(id));
43095
+ if (run.version !== 1 || run.id !== id || !["prepared", "proposal", "conflict", "completed", "skipped"].includes(run.stage) || 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)) {
43096
+ throw new Error("invalid demo run state");
43097
+ }
43098
+ return run;
43099
+ }
43100
+ var saveRun = (run) => saveDemoJson(runPath(run.id), run);
43101
+ var lockRun = (id, action) => withFileLockSync(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
43102
+ function prepareRun(agent, terminal = false) {
43103
+ const run = {
43104
+ version: 1,
43105
+ id: randomUUID3(),
43106
+ stage: "prepared",
43107
+ terminal,
43108
+ agent,
43109
+ launcher: [process.execPath, resolve8(process.argv[1])]
43110
+ };
43111
+ saveRun(run);
43112
+ return run;
43113
+ }
43114
+ var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
43115
+ function demoCommand(run, action, choice) {
43116
+ return [
43117
+ ...run.launcher,
43118
+ "demo",
43119
+ action,
43120
+ run.id,
43121
+ ...choice === void 0 ? [] : ["--choice", choice]
43122
+ ].map(quote).join(" ");
43123
+ }
43124
+ function onboardingFinished() {
43125
+ const path9 = join21(demoDirectory(), "onboarding.json");
43126
+ if (!existsSync13(path9)) return false;
43127
+ const value = readDemoJson(path9);
43128
+ if (value.outcome !== "completed" && value.outcome !== "skipped") {
43129
+ throw new Error("invalid local onboarding outcome");
43130
+ }
43131
+ return true;
43132
+ }
43133
+ function finishOnboarding(outcome) {
43134
+ saveDemoJson(join21(demoDirectory(), "onboarding.json"), { outcome });
43135
+ }
43136
+ function pendingRuns() {
43137
+ const path9 = join21(demoDirectory(), "runs");
43138
+ if (!existsSync13(path9)) return [];
43139
+ return readdirSync5(path9).filter((name) => name.endsWith(".json") && RUN_ID.test(name.slice(0, -5))).map((name) => name.slice(0, -5)).filter((id) => !["completed", "skipped"].includes(readRun(id).stage));
43140
+ }
43141
+ function exclusionPath(key) {
43142
+ if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
43143
+ return join21(demoDirectory(), "excluded-sessions", `${key}.json`);
43144
+ }
43145
+
43146
+ // src/demo/sandbox.ts
43147
+ var decisionBytes = (adopted) => `${JSON.stringify(adopted ? SAMPLE_DECISIONS : SAMPLE_DECISIONS.slice(0, 1), null, 2)}
43148
+ `;
43149
+ function allowedFiles(run) {
43150
+ return {
43151
+ ".owner": [run.id],
43152
+ "note.md": [SAMPLE_NOTE],
43153
+ "decisions.json": [decisionBytes(false), decisionBytes(true)],
43154
+ ...Object.fromEntries(Object.entries(SAMPLE_FILES).map(([name, value]) => [name, [value]])),
43155
+ "service.ts": [SAMPLE_FILES["service.ts"], WARNING_EDIT],
43156
+ "orders.ts": [SAMPLE_FILES["orders.ts"], REPOSITORY_EDIT]
43157
+ };
43158
+ }
43159
+ function inspectSandbox(run) {
43160
+ const sandbox = run.sandbox;
43161
+ if (!sandbox || dirname11(sandbox.path) !== realpathSync5(tmpdir()) || !basename4(sandbox.path).startsWith("prim-demo-")) {
43162
+ throw new Error("invalid demo sandbox ownership");
43163
+ }
43164
+ const stat = lstatSync9(sandbox.path);
43165
+ if (!stat.isDirectory() || stat.dev !== sandbox.device || stat.ino !== sandbox.inode) {
43166
+ throw new Error(`demo sandbox changed; retained ${sandbox.path}`);
43167
+ }
43168
+ const allowed = allowedFiles(run);
43169
+ for (const name of readdirSync6(sandbox.path)) {
43170
+ const path9 = join22(sandbox.path, name);
43171
+ const file = lstatSync9(path9);
43172
+ if (!Object.hasOwn(allowed, name) || !file.isFile() || file.nlink !== 1 || file.size > 16384 || !allowed[name].includes(readFileSync17(path9, "utf8"))) {
43173
+ throw new Error(`unexpected demo contents; retained ${sandbox.path}`);
43174
+ }
43175
+ }
43176
+ return sandbox.path;
43177
+ }
43178
+ function createSandbox(run) {
43179
+ if (!run.sandbox) {
43180
+ const path9 = mkdtempSync3(join22(realpathSync5(tmpdir()), "prim-demo-"));
43181
+ const stat = lstatSync9(path9);
43182
+ run.sandbox = { path: path9, device: stat.dev, inode: stat.ino };
43183
+ saveRun(run);
43184
+ }
43185
+ const root = inspectSandbox(run);
43186
+ for (const [name, content] of Object.entries({
43187
+ ".owner": run.id,
43188
+ "note.md": SAMPLE_NOTE,
43189
+ ...SAMPLE_FILES,
43190
+ "decisions.json": decisionBytes(false)
43191
+ })) {
43192
+ const path9 = join22(root, name);
43193
+ if (!existsSync14(path9)) atomicWriteFile(path9, content, { mode: 384 });
43194
+ }
43195
+ }
43196
+ function writeSample(run, name, bytes) {
43197
+ const root = inspectSandbox(run);
43198
+ if (!allowedFiles(run)[name].includes(bytes)) throw new Error("unsupported demo edit");
43199
+ atomicWriteFile(join22(root, name), bytes, { mode: 384 });
43200
+ }
43201
+ function readSample(run, name) {
43202
+ return readFileSync17(join22(inspectSandbox(run), name), "utf8");
43203
+ }
43204
+ function cleanSandbox(run) {
43205
+ if (!run.sandbox) return;
43206
+ try {
43207
+ lstatSync9(run.sandbox.path);
43208
+ } catch (error) {
43209
+ if (error.code !== "ENOENT") throw error;
43210
+ run.sandbox = void 0;
42941
43211
  return;
42942
43212
  }
42943
- for (const entry of readdirSync6(envDir, { withFileTypes: true })) {
42944
- if (entry.isDirectory()) {
42945
- sweepOrphanedDrainCheckpoints(join21(envDir, entry.name));
42946
- }
43213
+ const root = inspectSandbox(run);
43214
+ for (const name of readdirSync6(root)) {
43215
+ inspectSandbox(run);
43216
+ unlinkSync5(join22(root, name));
43217
+ }
43218
+ rmdirSync(root);
43219
+ run.sandbox = void 0;
43220
+ }
43221
+
43222
+ // src/commands/demo.ts
43223
+ var intro = "SIMULATED TOUR \u2014 fictional Decisions and scripted verdicts; no live ingestion or enforcement check.";
43224
+ var handoff = "Sample files removed. Next: ask your agent to propose one real Decision from your project's shared memory for your individual approval.";
43225
+ var captureNotice = "Passive Decision capture is excluded for the rest of this agent session, including resumed use. Start a new session for normal capture. Explicitly approved real Decisions can still be created.";
43226
+ var completionReceipt = [
43227
+ "Extracted a Decision with supporting evidence",
43228
+ "Adopted a Decision with your confirmation",
43229
+ "Surfaced a warning and allowed the edit",
43230
+ "Refused a conflicting write",
43231
+ "Applied the compliant implementation"
43232
+ ];
43233
+ function resultFor2(run) {
43234
+ const action = run.stage === "prepared" ? "start" : run.stage === "proposal" ? "confirm" : "resolve";
43235
+ const done = run.stage === "completed" || run.stage === "skipped";
43236
+ return {
43237
+ simulated: true,
43238
+ runId: run.id,
43239
+ stage: run.stage,
43240
+ ...done ? { message: handoff, nextAction: `prim welcome${run.binding ? " --capture-excluded" : ""}` } : {
43241
+ nextAction: demoCommand(run, action, action === "resolve" ? "repository" : void 0),
43242
+ skipAction: demoCommand(run, "skip")
43243
+ },
43244
+ ...run.sandbox ? { sandbox: run.sandbox.path } : {},
43245
+ ...run.stage === "conflict" ? { retryAction: demoCommand(run, "resolve", "local-storage") } : {}
43246
+ };
43247
+ }
43248
+ function demoTrustGuidance(agent) {
43249
+ if (agent === "codex")
43250
+ return "Trust the installed prim hooks with /hooks in Codex, then retry the exact nextAction.";
43251
+ if (agent === "hermes")
43252
+ return "Approve the installed prim hooks when Hermes prompts, then retry the exact nextAction.";
43253
+ if (agent === "cursor")
43254
+ return "Trust this Cursor workspace and activate its installed hooks, then retry the exact nextAction.";
43255
+ return "Activate the installed prim hooks in your agent, then retry the exact nextAction.";
43256
+ }
43257
+ function consumeAcknowledgment(run, action, choice) {
43258
+ if (run.terminal) return Boolean(process.stdin.isTTY && process.stderr.isTTY);
43259
+ const ack = run.acknowledgment;
43260
+ run.acknowledgment = void 0;
43261
+ saveRun(run);
43262
+ if (!run.binding || !ack || ack.command !== demoCommand(run, action, choice)) return false;
43263
+ const age = Date.now() - ack.at;
43264
+ if (!Number.isFinite(age) || age < 0 || age > 3e4) return false;
43265
+ try {
43266
+ const exclusion = readDemoJson(exclusionPath(run.binding));
43267
+ return typeof exclusion.runId === "string" && RUN_ID.test(exclusion.runId);
43268
+ } catch {
43269
+ return false;
42947
43270
  }
42948
43271
  }
42949
- function bucketStats(options = {}) {
42950
- const out = [];
42951
- let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
42952
- const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
42953
- for (const { bucket, path: path9 } of listBuckets()) {
42954
- if (out.length >= maxFiles) {
42955
- break;
43272
+ function narrateDecision(index) {
43273
+ const item = SAMPLE_DECISIONS[index];
43274
+ const status = index === 1 ? "proposed adoption, awaiting confirmation" : item.stage;
43275
+ const source = index === 1 ? "Fictional authoring proposal" : item.source;
43276
+ process.stderr.write(
43277
+ `
43278
+ Decision: ${item.decision}
43279
+ Status: ${status} (sample)
43280
+ Source: ${source}
43281
+ Rationale: ${item.rationale}
43282
+ Scope: ${item.files.join(", ")}
43283
+ Alternatives rejected: ${item.alternativesRejected.join("; ")}
43284
+ `
43285
+ );
43286
+ if (index === 0) {
43287
+ const extracted = SAMPLE_DECISIONS[0];
43288
+ process.stderr.write(
43289
+ `Source evidence:
43290
+ ${extracted.evidence.map((quote2) => ` "${quote2}"`).join("\n")}
43291
+ Scope basis: ${extracted.scopeBasis}
43292
+ `
43293
+ );
43294
+ }
43295
+ }
43296
+ function narrateBlockedAttempt(unchanged) {
43297
+ process.stderr.write(`
43298
+ ${bold(color("BLOCKED \u2014 file unchanged (simulated)", "red"))}
43299
+ `);
43300
+ process.stderr.write(
43301
+ `Attempt: save the order with localStorage.setItem(...).
43302
+ Decision (adopted sample): ${SAMPLE_DECISIONS[1].decision}
43303
+ Conflict: direct storage bypasses the shared repository and its validation.
43304
+ Outcome: this scenario refuses the proposed write.
43305
+ `
43306
+ );
43307
+ process.stderr.write(createPatch("orders.ts (refused proposal)", unchanged, BLOCKED_EDIT));
43308
+ process.stderr.write(
43309
+ `Proof: orders.ts is unchanged. Actual file:
43310
+ ${unchanged}
43311
+ Next: save through orders.save(...) to preserve repository validation.
43312
+ `
43313
+ );
43314
+ }
43315
+ function narrateCompletion(run) {
43316
+ process.stderr.write(`
43317
+ ${bold(color("WALKTHROUGH COMPLETE \u2014 simulated", "green"))}
43318
+ `);
43319
+ process.stderr.write(`${completionReceipt.map((item) => `\u2713 ${item}`).join("\n")}
43320
+ `);
43321
+ process.stderr.write(`${handoff}
43322
+ ${run.terminal ? "" : `${captureNotice}
43323
+ `}`);
43324
+ }
43325
+ function advanceDemo(id, action, choice) {
43326
+ return lockRun(id, (run) => {
43327
+ if (action === "skip") {
43328
+ cleanSandbox(run);
43329
+ run.stage = "skipped";
43330
+ saveRun(run);
43331
+ finishOnboarding("skipped");
43332
+ process.stderr.write(`[prim] ${handoff}
43333
+ `);
43334
+ if (run.binding) process.stderr.write(`${captureNotice}
43335
+ `);
43336
+ return resultFor2(run);
43337
+ }
43338
+ if (!consumeAcknowledgment(run, action, choice)) {
43339
+ const message = `Tour pending: session isolation has not been acknowledged. ${demoTrustGuidance(run.agent)}`;
43340
+ process.stderr.write(`[prim] ${message}
43341
+ `);
43342
+ return {
43343
+ ...resultFor2(run),
43344
+ stage: "pending",
43345
+ message,
43346
+ nextAction: demoCommand(run, action, choice)
43347
+ };
43348
+ }
43349
+ if (action === "confirm" && run.stage === "prepared") {
43350
+ throw new Error("start the demo before confirming its proposal");
43351
+ }
43352
+ if (action === "resolve" && (run.stage === "prepared" || run.stage === "proposal")) {
43353
+ throw new Error("confirm the sample Decision before resolving");
42956
43354
  }
42957
- let sample;
42958
43355
  try {
42959
- sample = sampleJournalFile(path9, remainingBytes);
42960
- } catch (err) {
42961
- if (err.code === "ENOENT") {
42962
- continue;
43356
+ process.stderr.write(`${bold(intro)}
43357
+ `);
43358
+ if (!run.terminal && action === "start") process.stderr.write(`${captureNotice}
43359
+ `);
43360
+ if (run.stage === "completed") {
43361
+ narrateCompletion(run);
43362
+ return { ...resultFor2(run), receipt: completionReceipt };
43363
+ }
43364
+ if (run.stage === "skipped") return resultFor2(run);
43365
+ if (action === "start") {
43366
+ if (run.stage === "prepared") {
43367
+ createSandbox(run);
43368
+ run.stage = "proposal";
43369
+ saveRun(run);
43370
+ }
43371
+ if (run.stage === "proposal") {
43372
+ process.stderr.write(
43373
+ `
43374
+ ${bold("YOUR MISSION: add order saving")}
43375
+ Your fictional team discussed how this should work. Watch that context become Decisions, then guide an agent's implementation.
43376
+ Local simulation \xB7 fictional examples \xB7 disposable files
43377
+ `
43378
+ );
43379
+ process.stderr.write(`
43380
+ Sample ingestion (scripted extraction):
43381
+ ${SAMPLE_NOTE}
43382
+ `);
43383
+ process.stderr.write(`
43384
+ ${bold(color("DECISION EXTRACTED \u2014 simulated", "green"))}
43385
+ `);
43386
+ narrateDecision(0);
43387
+ process.stderr.write("The choice, its reason, and its source now travel together.\n");
43388
+ process.stderr.write("\nNow explicitly author another sample Decision:\n");
43389
+ narrateDecision(1);
43390
+ process.stderr.write("Confirm this fictional Decision to adopt it, or skip the tour.\n");
43391
+ }
43392
+ return {
43393
+ ...resultFor2(run),
43394
+ decisions: SAMPLE_DECISIONS.slice(0, run.stage === "proposal" ? 1 : 2)
43395
+ };
42963
43396
  }
42964
- throw err;
43397
+ if (action === "confirm") {
43398
+ const before2 = SAMPLE_FILES["service.ts"];
43399
+ if (run.stage === "proposal") {
43400
+ writeSample(run, "decisions.json", decisionBytes(true));
43401
+ writeSample(run, "service.ts", WARNING_EDIT);
43402
+ run.stage = "conflict";
43403
+ saveRun(run);
43404
+ process.stderr.write(
43405
+ `
43406
+ ${bold(color("SAMPLE DECISION ADOPTED \u2014 simulated", "green"))}
43407
+ ${SAMPLE_DECISIONS[1].decision}
43408
+ Your confirmation changed this proposal into an adopted sample Decision.
43409
+ `
43410
+ );
43411
+ }
43412
+ const after2 = readSample(run, "service.ts");
43413
+ const unchanged = readSample(run, "orders.ts");
43414
+ process.stderr.write(`
43415
+ ${bold(color("WARNING \u2014 edit allowed (simulated)", "yellow"))}
43416
+ `);
43417
+ process.stderr.write(
43418
+ `Attempt: call fetch("/orders") directly.
43419
+ Decision (provisional sample): ${SAMPLE_DECISIONS[0].decision}
43420
+ Conflict: direct fetch bypasses consistent retries and request tracing.
43421
+ Outcome: this scenario surfaces the conflict and allows the edit.
43422
+ `
43423
+ );
43424
+ process.stderr.write(createPatch("service.ts", before2, after2));
43425
+ process.stderr.write(
43426
+ `Proof: service.ts ${before2 === after2 ? "already matches the shared client" : "changed, as shown above"}.
43427
+ Next: restore the shared HTTP client for consistent retries and tracing.
43428
+ `
43429
+ );
43430
+ narrateBlockedAttempt(unchanged);
43431
+ process.stderr.write(
43432
+ "\nChoose the shared repository correction, or retry direct storage.\nThese verdicts are scripted for this scenario. Live outcomes depend on Decision state and agent behavior; Claude may ask permission where other agents block.\n"
43433
+ );
43434
+ return {
43435
+ ...resultFor2(run),
43436
+ decisions: SAMPLE_DECISIONS,
43437
+ evidence: {
43438
+ warning: { before: before2, after: after2 },
43439
+ block: {
43440
+ before: unchanged,
43441
+ proposed: BLOCKED_EDIT,
43442
+ after: readSample(run, "orders.ts")
43443
+ }
43444
+ }
43445
+ };
43446
+ }
43447
+ if (choice !== "repository" && choice !== "local-storage")
43448
+ throw new Error("choose repository or local-storage");
43449
+ if (choice === "local-storage") {
43450
+ const unchanged = readSample(run, "orders.ts");
43451
+ narrateBlockedAttempt(unchanged);
43452
+ return { ...resultFor2(run), evidence: { unchanged } };
43453
+ }
43454
+ const before = readSample(run, "service.ts");
43455
+ const ordersBefore = readSample(run, "orders.ts");
43456
+ writeSample(run, "service.ts", SAMPLE_FILES["service.ts"]);
43457
+ writeSample(run, "orders.ts", REPOSITORY_EDIT);
43458
+ const after = readSample(run, "service.ts");
43459
+ const orders = readSample(run, "orders.ts");
43460
+ process.stderr.write(createPatch("service.ts", before, after));
43461
+ process.stderr.write(createPatch("orders.ts", ordersBefore, orders));
43462
+ process.stderr.write(
43463
+ `${bold(color("PASS \u2014 compliant implementation written (simulated)", "green"))}
43464
+ Order saving now uses the shared repository. Service calls use the shared HTTP client.
43465
+ The requested change landed while preserving both sample Decisions.
43466
+ `
43467
+ );
43468
+ cleanSandbox(run);
43469
+ run.stage = "completed";
43470
+ saveRun(run);
43471
+ finishOnboarding("completed");
43472
+ narrateCompletion(run);
43473
+ return {
43474
+ ...resultFor2(run),
43475
+ receipt: completionReceipt,
43476
+ evidence: {
43477
+ correction: { before, after },
43478
+ orders,
43479
+ orderCorrection: { before: ordersBefore, after: orders }
43480
+ }
43481
+ };
43482
+ } catch (error) {
43483
+ try {
43484
+ cleanSandbox(run);
43485
+ run.stage = "prepared";
43486
+ saveRun(run);
43487
+ } catch {
43488
+ }
43489
+ throw error;
42965
43490
  }
42966
- remainingBytes = Math.max(0, remainingBytes - sample.sampledBytes);
42967
- out.push({
42968
- bucket,
42969
- path: path9,
42970
- ...sample
43491
+ });
43492
+ }
43493
+ function parseDemoAgent(value) {
43494
+ if (value === "claude") return "claude_code";
43495
+ if (value === void 0 || ["claude_code", "codex", "cursor", "hermes"].includes(value))
43496
+ return value;
43497
+ throw new Error("expected --agent claude, codex, cursor, or hermes");
43498
+ }
43499
+ function reportError(error) {
43500
+ const message = error instanceof Error ? error.message : String(error);
43501
+ process.stderr.write(`[prim] demo: ${message}
43502
+ `);
43503
+ printJson({ simulated: true, stage: "error", message });
43504
+ process.exitCode = 1;
43505
+ }
43506
+ function registerDemoCommands(program3) {
43507
+ const demo = program3.command("demo").description("Try a fictional, local Decision and enforcement walkthrough").option("--agent <agent>", "calling agent; requires hook acknowledgment before samples").action(async (options, command) => {
43508
+ try {
43509
+ const agent = parseDemoAgent(options.agent);
43510
+ const terminal = !agent && !isNonInteractive(command.optsWithGlobals()) && Boolean(process.stdin.isTTY && process.stderr.isTTY) && !process.env.CLAUDECODE && !process.env.CODEX_THREAD_ID && !process.env.CURSOR_AGENT && !process.env.HERMES_INTERACTIVE;
43511
+ const recovery = pendingRuns().map(
43512
+ (id) => lockRun(id, (run2) => ({ runId: id, skipAction: demoCommand(run2, "skip") }))
43513
+ );
43514
+ const run = prepareRun(agent, terminal);
43515
+ if (!terminal) {
43516
+ process.stderr.write(
43517
+ "[prim] Preparing the simulated tour. Run nextAction exactly, as a standalone shell command. No sample content is shown until session isolation is acknowledged.\n"
43518
+ );
43519
+ if (recovery.length)
43520
+ process.stderr.write(
43521
+ "[prim] Earlier unfinished tours are listed in recoverableRuns; use their skipAction to clean up.\n"
43522
+ );
43523
+ printJson({ ...resultFor2(run), recoverableRuns: recovery });
43524
+ return;
43525
+ }
43526
+ advanceDemo(run.id, "start");
43527
+ if (!await askConfirmation("Adopt this fictional Decision?", process.stderr)) {
43528
+ printJson(advanceDemo(run.id, "skip"));
43529
+ return;
43530
+ }
43531
+ advanceDemo(run.id, "confirm");
43532
+ if (await askConfirmation("Apply the shared repository correction?", process.stderr)) {
43533
+ printJson(advanceDemo(run.id, "resolve", "repository"));
43534
+ } else {
43535
+ printJson(advanceDemo(run.id, "skip"));
43536
+ }
43537
+ } catch (error) {
43538
+ reportError(error);
43539
+ }
43540
+ });
43541
+ for (const action of ["start", "confirm", "resolve", "skip"]) {
43542
+ const subcommand = demo.command(`${action} ${action === "skip" ? "[runId]" : "<runId>"}`);
43543
+ if (action === "resolve")
43544
+ subcommand.requiredOption("--choice <choice>", "repository or local-storage");
43545
+ subcommand.action((id, options) => {
43546
+ try {
43547
+ if (action === "skip" && !id) {
43548
+ finishOnboarding("skipped");
43549
+ printJson({
43550
+ simulated: true,
43551
+ stage: "skipped",
43552
+ message: "Tour skipped. Run prim welcome for real Decision seeding."
43553
+ });
43554
+ return;
43555
+ }
43556
+ if (action === "resolve" && options.choice !== "repository" && options.choice !== "local-storage") {
43557
+ throw new Error("choose repository or local-storage");
43558
+ }
43559
+ printJson(advanceDemo(id, action, options.choice));
43560
+ } catch (error) {
43561
+ reportError(error);
43562
+ }
42971
43563
  });
42972
43564
  }
42973
- return out;
42974
- }
42975
- function pendingJournalStats() {
42976
- const perKindBytes = Math.floor(JOURNAL_STATS_SAMPLE_BYTES / 2);
42977
- const perKindFiles = Math.floor(PENDING_STATS_MAX_FILES / 2);
42978
- const live = bucketStats({ sampleBytes: perKindBytes, maxFiles: perKindFiles });
42979
- const stranded = listFlushing({ sampleBytes: perKindBytes, maxFiles: perKindFiles });
42980
- const timestamps = [...live, ...stranded].map((entry) => entry.oldestCapturedAt).filter((value) => value !== void 0);
42981
- const liveSampled = live.some((entry) => entry.sampled) || live.length >= perKindFiles;
42982
- const strandedSampled = stranded.some((entry) => entry.sampled) || stranded.length >= perKindFiles;
42983
- return {
42984
- pendingCount: live.reduce((count, entry) => count + entry.lineCount, 0) + stranded.reduce((count, entry) => count + entry.lineCount, 0),
42985
- oldestPendingAt: timestamps.length > 0 ? Math.min(...timestamps) : void 0,
42986
- strandedCount: stranded.reduce((count, entry) => count + entry.lineCount, 0),
42987
- strandedFileCount: stranded.length,
42988
- sampled: liveSampled || strandedSampled,
42989
- strandedSampled
42990
- };
42991
43565
  }
42992
43566
 
42993
- // src/commands/hermes-install.ts
42994
- import { existsSync as existsSync15, readFileSync as readFileSync18, rmSync as rmSync7, statSync as statSync4 } from "fs";
42995
- import { homedir as homedir9 } from "os";
42996
- import { join as join22 } from "path";
43567
+ // src/commands/doctor.ts
43568
+ import { existsSync as existsSync18 } from "fs";
42997
43569
 
42998
- // node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
42999
- var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias");
43000
- var DOC = /* @__PURE__ */ Symbol.for("yaml.document");
43001
- var MAP = /* @__PURE__ */ Symbol.for("yaml.map");
43002
- var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair");
43003
- var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar");
43004
- var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq");
43005
- var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
43006
- var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
43007
- var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
43008
- var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
43009
- var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
43010
- var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
43011
- var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
43012
- function isCollection(node) {
43013
- if (node && typeof node === "object")
43014
- switch (node[NODE_TYPE]) {
43015
- case MAP:
43016
- case SEQ:
43017
- return true;
43018
- }
43019
- return false;
43570
+ // src/decisions/feedback.ts
43571
+ var FEEDBACK_PROTOCOL_VERSION = 2;
43572
+ var FEEDBACK_MIN_PROTOCOL_VERSION = 1;
43573
+ var STATUS_PATH = "/api/cli/decisions/feedback/status";
43574
+ function isRecord2(value) {
43575
+ return typeof value === "object" && value !== null && !Array.isArray(value);
43020
43576
  }
43021
- function isNode(node) {
43022
- if (node && typeof node === "object")
43023
- switch (node[NODE_TYPE]) {
43024
- case ALIAS:
43025
- case MAP:
43026
- case SCALAR:
43027
- case SEQ:
43028
- return true;
43029
- }
43030
- return false;
43577
+ function isSupportedProtocolVersion(value) {
43578
+ return Number.isSafeInteger(value) && Number(value) >= FEEDBACK_MIN_PROTOCOL_VERSION && Number(value) <= FEEDBACK_PROTOCOL_VERSION;
43031
43579
  }
43032
- var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
43580
+ function parseFeedbackCapability(value) {
43581
+ if (!isRecord2(value) || !isSupportedProtocolVersion(value.protocolVersion)) return void 0;
43582
+ if (value.status === "available") return { status: "available" };
43583
+ if (value.status === "unavailable" && value.reason === "organization_unbound") {
43584
+ return { status: "unavailable", reason: "organization_unbound" };
43585
+ }
43586
+ return void 0;
43587
+ }
43588
+ async function fetchFeedbackCapability(signal, client = getClient()) {
43589
+ const result = parseFeedbackCapability(await client.get(STATUS_PATH, { signal }));
43590
+ if (!result) throw new Error("server returned an unsupported decision-feedback contract");
43591
+ return result;
43592
+ }
43593
+
43594
+ // src/protocol/decision-lifecycle.ts
43595
+ var DECISION_LIFECYCLE_PROTOCOL_VERSION = 2;
43596
+
43597
+ // src/journal-organization.ts
43598
+ var ORGANIZATION_BINDING_VERSION = 1;
43599
+ var ORGANIZATION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
43600
+ var UNBOUND_BUCKET = "_unbound";
43601
+ var InvalidJournalEnvelopeError = class extends Error {
43602
+ constructor() {
43603
+ super("Invalid locally journaled move");
43604
+ this.name = "InvalidJournalEnvelopeError";
43605
+ }
43606
+ };
43607
+ function safeOrganizationId(value) {
43608
+ return typeof value === "string" && ORGANIZATION_ID_RE.test(value);
43609
+ }
43610
+ function isCaptureAuthorityKind(value) {
43611
+ return value === "workos" || value === "service_token";
43612
+ }
43613
+ function parseOrganizationBinding(value) {
43614
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
43615
+ return { state: "server_contract_unavailable" };
43616
+ }
43617
+ const record3 = value;
43618
+ if (record3.authenticated !== true || record3.organizationBindingVersion !== ORGANIZATION_BINDING_VERSION || !isCaptureAuthorityKind(record3.captureAuthorityKind)) {
43619
+ return { state: "server_contract_unavailable" };
43620
+ }
43621
+ if (record3.organizationId === null && record3.workosOrganizationId === null) {
43622
+ return { state: "no_current_organization" };
43623
+ }
43624
+ if (safeOrganizationId(record3.organizationId) && record3.workosOrganizationId === null) {
43625
+ return { state: "organization_identity_unreconciled" };
43626
+ }
43627
+ if (!safeOrganizationId(record3.organizationId) || !safeOrganizationId(record3.workosOrganizationId)) {
43628
+ return { state: "server_contract_unavailable" };
43629
+ }
43630
+ return {
43631
+ state: "current",
43632
+ binding: {
43633
+ captureAuthorityKind: record3.captureAuthorityKind,
43634
+ organizationId: record3.organizationId,
43635
+ workosOrganizationId: record3.workosOrganizationId
43636
+ }
43637
+ };
43638
+ }
43639
+ function summarizeRetainedBuckets(retained) {
43640
+ const counts = /* @__PURE__ */ new Map();
43641
+ for (const item of retained) {
43642
+ counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
43643
+ }
43644
+ return [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([reason, count]) => `${reason}:${String(count)}`).join(", ");
43645
+ }
43646
+ function classifyJournalBuckets(buckets, binding) {
43647
+ const deliverableBuckets = /* @__PURE__ */ new Set();
43648
+ const retainedBuckets = [];
43649
+ for (const bucket of [...new Set(buckets)].sort()) {
43650
+ if (bucket === UNBOUND_BUCKET) {
43651
+ retainedBuckets.push({ bucket, reason: "unbound" });
43652
+ continue;
43653
+ }
43654
+ if (typeof binding === "string") {
43655
+ retainedBuckets.push({ bucket, reason: binding });
43656
+ continue;
43657
+ }
43658
+ if (bucket === binding.organizationId || bucket === binding.workosOrganizationId) {
43659
+ deliverableBuckets.add(bucket);
43660
+ } else {
43661
+ retainedBuckets.push({ bucket, reason: "organization_mismatch" });
43662
+ }
43663
+ }
43664
+ return { deliverableBuckets, retainedBuckets };
43665
+ }
43666
+ function buildOrganizationBoundMoveRequest(batch, binding) {
43667
+ const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
43668
+ const request2 = {
43669
+ batch: batch.map((move) => {
43670
+ if (typeof move !== "object" || move === null || Array.isArray(move)) {
43671
+ return move;
43672
+ }
43673
+ return {
43674
+ ...move,
43675
+ envelopeVersion: 4,
43676
+ capturedOrganizationId,
43677
+ captureAuthorityKind: binding.captureAuthorityKind,
43678
+ decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
43679
+ };
43680
+ })
43681
+ };
43682
+ if (!isMoveIngestRequest(request2)) {
43683
+ throw new InvalidJournalEnvelopeError();
43684
+ }
43685
+ return request2;
43686
+ }
43687
+ async function inspectJournalDelivery(buckets, options = {}) {
43688
+ const bucketList = [...new Set(buckets)];
43689
+ let client;
43690
+ try {
43691
+ client = options.client ?? await (options.createClient ?? (() => getPinnedClient()))();
43692
+ } catch {
43693
+ return classifyJournalBuckets(bucketList, "identity_unavailable");
43694
+ }
43695
+ let parsed;
43696
+ try {
43697
+ parsed = parseOrganizationBinding(
43698
+ await client.get("/api/cli/auth/status", {
43699
+ signal: AbortSignal.timeout(1e4),
43700
+ quietRefresh: true
43701
+ })
43702
+ );
43703
+ } catch {
43704
+ return classifyJournalBuckets(bucketList, "identity_unavailable");
43705
+ }
43706
+ if (parsed.state !== "current") {
43707
+ return classifyJournalBuckets(bucketList, parsed.state);
43708
+ }
43709
+ return {
43710
+ client,
43711
+ binding: parsed.binding,
43712
+ ...classifyJournalBuckets(bucketList, parsed.binding)
43713
+ };
43714
+ }
43715
+
43716
+ // src/journal.ts
43717
+ import {
43718
+ appendFileSync,
43719
+ closeSync as closeSync5,
43720
+ existsSync as existsSync16,
43721
+ fstatSync as fstatSync2,
43722
+ mkdirSync as mkdirSync11,
43723
+ openSync as openSync5,
43724
+ opendirSync,
43725
+ readFileSync as readFileSync19,
43726
+ readSync as readSync2,
43727
+ readdirSync as readdirSync8
43728
+ } from "fs";
43729
+ import { dirname as dirname13, join as join24 } from "path";
43730
+
43731
+ // src/drain-progress.ts
43732
+ import {
43733
+ chmodSync as chmodSync6,
43734
+ existsSync as existsSync15,
43735
+ readFileSync as readFileSync18,
43736
+ readdirSync as readdirSync7,
43737
+ rmSync as rmSync6,
43738
+ rmdirSync as rmdirSync2
43739
+ } from "fs";
43740
+ import { basename as basename5, dirname as dirname12, join as join23 } from "path";
43741
+ var DIRECTORY_MODE3 = 448;
43742
+ var FILE_MODE2 = 384;
43743
+ var DRAIN_PROGRESS_DIRNAME = "drain-progress";
43744
+ var CHECKPOINT_NAME = /^(.+)\.json(?:\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp)?$/;
43745
+ function rotationIdentity(stat) {
43746
+ return { size: stat.size, ino: stat.ino, dev: stat.dev };
43747
+ }
43748
+ function drainProgressDirectory(flushingPath) {
43749
+ return join23(dirname12(flushingPath), DRAIN_PROGRESS_DIRNAME);
43750
+ }
43751
+ function drainProgressPath(flushingPath) {
43752
+ return join23(drainProgressDirectory(flushingPath), `${basename5(flushingPath)}.json`);
43753
+ }
43754
+ function isByteCount(value) {
43755
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
43756
+ }
43757
+ function drainResumeOffset(flushingPath, rotation) {
43758
+ let parsed;
43759
+ try {
43760
+ parsed = JSON.parse(readFileSync18(drainProgressPath(flushingPath), "utf8"));
43761
+ } catch {
43762
+ return 0;
43763
+ }
43764
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
43765
+ return 0;
43766
+ }
43767
+ const { v, offset, size, ino, dev } = parsed;
43768
+ if (v !== 2 || ino !== rotation.ino || dev !== rotation.dev || size !== rotation.size || !isByteCount(offset) || offset > rotation.size) {
43769
+ return 0;
43770
+ }
43771
+ return offset;
43772
+ }
43773
+ function writeDrainCheckpoint(flushingPath, checkpoint) {
43774
+ const directory = drainProgressDirectory(flushingPath);
43775
+ ensureDurableDirectory(directory, DIRECTORY_MODE3);
43776
+ chmodSync6(directory, DIRECTORY_MODE3);
43777
+ atomicWriteFile(drainProgressPath(flushingPath), `${JSON.stringify(checkpoint)}
43778
+ `, {
43779
+ mode: FILE_MODE2
43780
+ });
43781
+ }
43782
+ function removeEmptyDirectory(directory) {
43783
+ try {
43784
+ rmdirSync2(directory);
43785
+ } catch (error) {
43786
+ const code = error.code;
43787
+ if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST") {
43788
+ throw error;
43789
+ }
43790
+ }
43791
+ }
43792
+ function removeDrainCheckpoint(flushingPath) {
43793
+ rmSync6(drainProgressPath(flushingPath), { force: true });
43794
+ removeEmptyDirectory(drainProgressDirectory(flushingPath));
43795
+ }
43796
+ function sweepOrphanedDrainCheckpoints(bucketDirectory) {
43797
+ const directory = join23(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
43798
+ let names;
43799
+ try {
43800
+ names = readdirSync7(directory);
43801
+ } catch {
43802
+ return;
43803
+ }
43804
+ for (const name of names) {
43805
+ const rotation = CHECKPOINT_NAME.exec(name)?.[1];
43806
+ if (rotation === void 0 || existsSync15(join23(bucketDirectory, rotation))) {
43807
+ continue;
43808
+ }
43809
+ try {
43810
+ rmSync6(join23(directory, name), { force: true });
43811
+ } catch {
43812
+ }
43813
+ }
43814
+ try {
43815
+ removeEmptyDirectory(directory);
43816
+ } catch {
43817
+ }
43818
+ }
43819
+
43820
+ // src/journal.ts
43821
+ var JOURNAL_DIR = join24(primConfigDirectory(), "moves");
43822
+ var JOURNAL_BASENAME = "journal.ndjson";
43823
+ var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
43824
+ var PENDING_STATS_MAX_FILES = 128;
43825
+ function envSlug(apiUrl) {
43826
+ const slug = apiUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
43827
+ if (slug.length === 0 || slug === "." || slug === "..") {
43828
+ return "default";
43829
+ }
43830
+ return slug;
43831
+ }
43832
+ function currentEnvDir() {
43833
+ return join24(JOURNAL_DIR, envSlug(getSiteUrl()));
43834
+ }
43835
+ function parseMoves(content) {
43836
+ const moves = [];
43837
+ for (const line of content.split("\n")) {
43838
+ if (line.length === 0) {
43839
+ continue;
43840
+ }
43841
+ try {
43842
+ moves.push(JSON.parse(line));
43843
+ } catch {
43844
+ }
43845
+ }
43846
+ return moves;
43847
+ }
43848
+ function readMovesFromPath(path9) {
43849
+ if (!existsSync16(path9)) {
43850
+ return [];
43851
+ }
43852
+ return parseMoves(readFileSync19(path9, "utf-8"));
43853
+ }
43854
+ function listBuckets() {
43855
+ const out = [];
43856
+ const envDir = currentEnvDir();
43857
+ if (!existsSync16(envDir)) {
43858
+ return out;
43859
+ }
43860
+ for (const entry of readdirSync8(envDir, { withFileTypes: true })) {
43861
+ if (!entry.isDirectory()) {
43862
+ continue;
43863
+ }
43864
+ const path9 = join24(envDir, entry.name, JOURNAL_BASENAME);
43865
+ if (existsSync16(path9)) {
43866
+ out.push({ bucket: entry.name, path: path9 });
43867
+ }
43868
+ }
43869
+ return out;
43870
+ }
43871
+ var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
43872
+ function oldestCapturedAt(moves) {
43873
+ let oldest;
43874
+ for (const move of moves) {
43875
+ if (!Number.isFinite(move.capturedAt)) {
43876
+ continue;
43877
+ }
43878
+ oldest = oldest === void 0 ? move.capturedAt : Math.min(oldest, move.capturedAt);
43879
+ }
43880
+ return oldest;
43881
+ }
43882
+ function sampleJournalFile(path9, maxBytes = JOURNAL_STATS_SAMPLE_BYTES, options = {}) {
43883
+ const fd = openSync5(path9, "r");
43884
+ try {
43885
+ const initial = fstatSync2(fd);
43886
+ const start = options.fromDrainCheckpoint ? drainResumeOffset(path9, rotationIdentity(initial)) : 0;
43887
+ const target = Math.min(initial.size - start, Math.max(0, maxBytes));
43888
+ const buffer = Buffer.allocUnsafe(target);
43889
+ let sampledBytes = 0;
43890
+ while (sampledBytes < target) {
43891
+ const count = readSync2(fd, buffer, sampledBytes, target - sampledBytes, start + sampledBytes);
43892
+ if (count === 0) {
43893
+ break;
43894
+ }
43895
+ sampledBytes += count;
43896
+ }
43897
+ const stat = fstatSync2(fd);
43898
+ const sampled = stat.size - start > sampledBytes;
43899
+ let content = buffer.subarray(0, sampledBytes).toString("utf-8");
43900
+ if (sampled) {
43901
+ const lastNewline = content.lastIndexOf("\n");
43902
+ content = lastNewline === -1 ? "" : content.slice(0, lastNewline + 1);
43903
+ }
43904
+ const lines = content.split("\n").filter((line) => line.length > 0);
43905
+ const moves = parseMoves(content);
43906
+ return {
43907
+ sizeBytes: stat.size,
43908
+ pendingBytes: Math.max(0, stat.size - start),
43909
+ mtimeMs: stat.mtimeMs,
43910
+ lineCount: sampled && stat.size > 0 ? Math.max(1, lines.length) : lines.length,
43911
+ oldestCapturedAt: oldestCapturedAt(moves),
43912
+ sampled,
43913
+ sampledBytes
43914
+ };
43915
+ } finally {
43916
+ closeSync5(fd);
43917
+ }
43918
+ }
43919
+ function parseFlushingPid(name) {
43920
+ const segments = name.slice(FLUSHING_PREFIX.length).split(".");
43921
+ const last = segments.length >= 2 ? segments[segments.length - 1] : void 0;
43922
+ if (last === void 0 || !/^[0-9]+$/.test(last)) return void 0;
43923
+ const pid = Number(last);
43924
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
43925
+ }
43926
+ function listFlushingInDir(dir, bucket, options = {}) {
43927
+ if (!existsSync16(dir)) {
43928
+ return [];
43929
+ }
43930
+ const out = [];
43931
+ let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
43932
+ const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
43933
+ const entries = opendirSync(dir);
43934
+ try {
43935
+ let entry = entries.readSync();
43936
+ while (entry && out.length < maxFiles) {
43937
+ if (!entry.isFile() || !entry.name.startsWith(FLUSHING_PREFIX)) {
43938
+ entry = entries.readSync();
43939
+ continue;
43940
+ }
43941
+ const path9 = join24(dir, entry.name);
43942
+ let sample;
43943
+ try {
43944
+ sample = sampleJournalFile(path9, remainingBytes, { fromDrainCheckpoint: true });
43945
+ } catch (err) {
43946
+ if (err.code === "ENOENT") {
43947
+ entry = entries.readSync();
43948
+ continue;
43949
+ }
43950
+ throw err;
43951
+ }
43952
+ remainingBytes = Math.max(0, remainingBytes - sample.sampledBytes);
43953
+ out.push({
43954
+ bucket,
43955
+ path: path9,
43956
+ pid: parseFlushingPid(entry.name),
43957
+ ...sample
43958
+ });
43959
+ entry = entries.readSync();
43960
+ }
43961
+ } finally {
43962
+ entries.closeSync();
43963
+ }
43964
+ return out;
43965
+ }
43966
+ function listFlushing(options = {}) {
43967
+ const envDir = currentEnvDir();
43968
+ if (!existsSync16(envDir)) {
43969
+ return [];
43970
+ }
43971
+ const out = [];
43972
+ let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
43973
+ const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
43974
+ for (const entry of readdirSync8(envDir, { withFileTypes: true })) {
43975
+ if (out.length >= maxFiles) {
43976
+ break;
43977
+ }
43978
+ if (entry.isDirectory()) {
43979
+ const found = listFlushingInDir(join24(envDir, entry.name), entry.name, {
43980
+ sampleBytes: remainingBytes,
43981
+ maxFiles: maxFiles - out.length
43982
+ });
43983
+ out.push(...found);
43984
+ remainingBytes = Math.max(
43985
+ 0,
43986
+ remainingBytes - found.reduce((count, file) => count + file.sampledBytes, 0)
43987
+ );
43988
+ }
43989
+ }
43990
+ return out;
43991
+ }
43992
+ function sweepOrphanedDrainProgress() {
43993
+ const envDir = currentEnvDir();
43994
+ if (!existsSync16(envDir)) {
43995
+ return;
43996
+ }
43997
+ for (const entry of readdirSync8(envDir, { withFileTypes: true })) {
43998
+ if (entry.isDirectory()) {
43999
+ sweepOrphanedDrainCheckpoints(join24(envDir, entry.name));
44000
+ }
44001
+ }
44002
+ }
44003
+ function bucketStats(options = {}) {
44004
+ const out = [];
44005
+ let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
44006
+ const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
44007
+ for (const { bucket, path: path9 } of listBuckets()) {
44008
+ if (out.length >= maxFiles) {
44009
+ break;
44010
+ }
44011
+ let sample;
44012
+ try {
44013
+ sample = sampleJournalFile(path9, remainingBytes);
44014
+ } catch (err) {
44015
+ if (err.code === "ENOENT") {
44016
+ continue;
44017
+ }
44018
+ throw err;
44019
+ }
44020
+ remainingBytes = Math.max(0, remainingBytes - sample.sampledBytes);
44021
+ out.push({
44022
+ bucket,
44023
+ path: path9,
44024
+ ...sample
44025
+ });
44026
+ }
44027
+ return out;
44028
+ }
44029
+ function pendingJournalStats() {
44030
+ const perKindBytes = Math.floor(JOURNAL_STATS_SAMPLE_BYTES / 2);
44031
+ const perKindFiles = Math.floor(PENDING_STATS_MAX_FILES / 2);
44032
+ const live = bucketStats({ sampleBytes: perKindBytes, maxFiles: perKindFiles });
44033
+ const stranded = listFlushing({ sampleBytes: perKindBytes, maxFiles: perKindFiles });
44034
+ const timestamps = [...live, ...stranded].map((entry) => entry.oldestCapturedAt).filter((value) => value !== void 0);
44035
+ const liveSampled = live.some((entry) => entry.sampled) || live.length >= perKindFiles;
44036
+ const strandedSampled = stranded.some((entry) => entry.sampled) || stranded.length >= perKindFiles;
44037
+ return {
44038
+ pendingCount: live.reduce((count, entry) => count + entry.lineCount, 0) + stranded.reduce((count, entry) => count + entry.lineCount, 0),
44039
+ oldestPendingAt: timestamps.length > 0 ? Math.min(...timestamps) : void 0,
44040
+ strandedCount: stranded.reduce((count, entry) => count + entry.lineCount, 0),
44041
+ strandedFileCount: stranded.length,
44042
+ sampled: liveSampled || strandedSampled,
44043
+ strandedSampled
44044
+ };
44045
+ }
44046
+
44047
+ // src/commands/hermes-install.ts
44048
+ import { existsSync as existsSync17, readFileSync as readFileSync20, rmSync as rmSync7, statSync as statSync4 } from "fs";
44049
+ import { homedir as homedir9 } from "os";
44050
+ import { join as join25 } from "path";
44051
+
44052
+ // node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
44053
+ var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias");
44054
+ var DOC = /* @__PURE__ */ Symbol.for("yaml.document");
44055
+ var MAP = /* @__PURE__ */ Symbol.for("yaml.map");
44056
+ var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair");
44057
+ var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar");
44058
+ var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq");
44059
+ var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
44060
+ var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
44061
+ var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
44062
+ var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
44063
+ var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
44064
+ var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
44065
+ var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
44066
+ function isCollection(node) {
44067
+ if (node && typeof node === "object")
44068
+ switch (node[NODE_TYPE]) {
44069
+ case MAP:
44070
+ case SEQ:
44071
+ return true;
44072
+ }
44073
+ return false;
44074
+ }
44075
+ function isNode(node) {
44076
+ if (node && typeof node === "object")
44077
+ switch (node[NODE_TYPE]) {
44078
+ case ALIAS:
44079
+ case MAP:
44080
+ case SCALAR:
44081
+ case SEQ:
44082
+ return true;
44083
+ }
44084
+ return false;
44085
+ }
44086
+ var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
43033
44087
 
43034
44088
  // node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/visit.js
43035
44089
  var BREAK = /* @__PURE__ */ Symbol("break visit");
@@ -48061,9 +49115,9 @@ var Lexer = class {
48061
49115
  }
48062
49116
  }
48063
49117
  *parseQuotedScalar() {
48064
- const quote = this.charAt(0);
48065
- let end = this.buffer.indexOf(quote, this.pos + 1);
48066
- if (quote === "'") {
49118
+ const quote2 = this.charAt(0);
49119
+ let end = this.buffer.indexOf(quote2, this.pos + 1);
49120
+ if (quote2 === "'") {
48067
49121
  while (end !== -1 && this.buffer[end + 1] === "'")
48068
49122
  end = this.buffer.indexOf("'", end + 2);
48069
49123
  } else {
@@ -49272,13 +50326,13 @@ var JSON_INDENT3 = 2;
49272
50326
  var CONFIG_MODE = 384;
49273
50327
  var PRIM_BINS4 = [CAPTURE_BIN4, GATE_BIN4, POST_TOOL_USE_BIN3, SESSION_START_BIN4, SESSION_END_BIN3];
49274
50328
  function hermesHome() {
49275
- return process.env.HERMES_HOME ?? join22(homedir9(), ".hermes");
50329
+ return process.env.HERMES_HOME ?? join25(homedir9(), ".hermes");
49276
50330
  }
49277
50331
  function configPath() {
49278
- return join22(hermesHome(), "config.yaml");
50332
+ return join25(hermesHome(), "config.yaml");
49279
50333
  }
49280
50334
  function legacyShimPath() {
49281
- return join22(hermesHome(), "agent-hooks", "prim-shim.sh");
50335
+ return join25(hermesHome(), "agent-hooks", "prim-shim.sh");
49282
50336
  }
49283
50337
  function commandFor2(bin) {
49284
50338
  return stableHookCommand(bin, HERMES_ARGS);
@@ -49392,8 +50446,8 @@ function hookRuntimeResolutions3(hooks) {
49392
50446
  }
49393
50447
  function inspectHookRuntimeResolutions4() {
49394
50448
  const path9 = configPath();
49395
- if (!existsSync15(path9)) return [];
49396
- return hookRuntimeResolutions3(readHooks(parseHermesDocument(readFileSync18(path9, "utf8"))));
50449
+ if (!existsSync17(path9)) return [];
50450
+ return hookRuntimeResolutions3(readHooks(parseHermesDocument(readFileSync20(path9, "utf8"))));
49397
50451
  }
49398
50452
  function entryMatchesRegistration3(owned, registration) {
49399
50453
  const expected = entryFor(registration);
@@ -49662,11 +50716,11 @@ function assertMergeValid(before, after, expectedHooks) {
49662
50716
  }
49663
50717
  }
49664
50718
  function readConfigSnapshot(path9) {
49665
- if (!existsSync15(path9)) return { exists: false, mode: CONFIG_MODE, raw: "" };
50719
+ if (!existsSync17(path9)) return { exists: false, mode: CONFIG_MODE, raw: "" };
49666
50720
  return {
49667
50721
  exists: true,
49668
50722
  mode: statSync4(path9).mode & 511,
49669
- raw: readFileSync18(path9, "utf8")
50723
+ raw: readFileSync20(path9, "utf8")
49670
50724
  };
49671
50725
  }
49672
50726
  var CONCURRENT_CONFIG_MESSAGE = "Hermes config changed during update; concurrent changes were preserved, retry the command";
@@ -49675,7 +50729,7 @@ function writeHermesConfigSnapshot(path9, before, after, expectedHooks) {
49675
50729
  ensureParent: true,
49676
50730
  mode: before.mode,
49677
50731
  validate(temporaryPath) {
49678
- const flushed = readFileSync18(temporaryPath, "utf8");
50732
+ const flushed = readFileSync20(temporaryPath, "utf8");
49679
50733
  if (!mergePreservesHermesSemantics(before.raw, flushed, expectedHooks)) {
49680
50734
  throw new Error(INVALID_MERGE_MESSAGE);
49681
50735
  }
@@ -49728,7 +50782,7 @@ function performInstall4(opts) {
49728
50782
  }
49729
50783
  function performUninstall4() {
49730
50784
  const path9 = configPath();
49731
- if (!existsSync15(path9)) {
50785
+ if (!existsSync17(path9)) {
49732
50786
  removeLegacyShim();
49733
50787
  return { path: path9, gate: false, capture: false, autoAccept: false, changed: false };
49734
50788
  }
@@ -49753,7 +50807,7 @@ function performUninstall4() {
49753
50807
  }
49754
50808
  function performStatus4() {
49755
50809
  const path9 = configPath();
49756
- const raw = existsSync15(path9) ? readFileSync18(path9, "utf8") : "";
50810
+ const raw = existsSync17(path9) ? readFileSync20(path9, "utf8") : "";
49757
50811
  const hooks = raw ? readHooks(parseHermesDocument(raw)) : {};
49758
50812
  return {
49759
50813
  path: path9,
@@ -49842,7 +50896,7 @@ function checkAuth() {
49842
50896
  return classifyAuthCredential(
49843
50897
  credential,
49844
50898
  storedCredential ? getTokenExpiresAt() : void 0,
49845
- storedCredential && existsSync16(REFRESH_TOKEN_PATH)
50899
+ storedCredential && existsSync18(REFRESH_TOKEN_PATH)
49846
50900
  );
49847
50901
  }
49848
50902
  function classifyDaemonHealth(snapshot, options = {}) {
@@ -50636,20 +51690,20 @@ function registerDoctorCommands(program3, dependencies = {}) {
50636
51690
  }
50637
51691
 
50638
51692
  // src/commands/moves.ts
50639
- import { existsSync as existsSync18, mkdirSync as mkdirSync13, unlinkSync as unlinkSync6, writeFileSync as writeFileSync9 } from "fs";
50640
- import { join as join25 } from "path";
51693
+ import { existsSync as existsSync20, mkdirSync as mkdirSync13, unlinkSync as unlinkSync7, writeFileSync as writeFileSync9 } from "fs";
51694
+ import { join as join28 } from "path";
50641
51695
 
50642
51696
  // src/flusher.ts
50643
- import { createReadStream, renameSync as renameSync6, statSync as statSync5, unlinkSync as unlinkSync5 } from "fs";
50644
- import { dirname as dirname14, join as join24 } from "path";
51697
+ import { createReadStream, renameSync as renameSync6, statSync as statSync5, unlinkSync as unlinkSync6 } from "fs";
51698
+ import { dirname as dirname15, join as join27 } from "path";
50645
51699
 
50646
51700
  // src/dead-letter.ts
50647
- import { createHash as createHash9, randomBytes as randomBytes7 } from "crypto";
51701
+ import { createHash as createHash10, randomBytes as randomBytes7 } from "crypto";
50648
51702
  import {
50649
51703
  constants as constants6,
50650
51704
  chmodSync as chmodSync7,
50651
51705
  closeSync as closeSync6,
50652
- existsSync as existsSync17,
51706
+ existsSync as existsSync19,
50653
51707
  fchmodSync as fchmodSync3,
50654
51708
  fsyncSync as fsyncSync3,
50655
51709
  mkdirSync as mkdirSync12,
@@ -50658,30 +51712,30 @@ import {
50658
51712
  rmSync as rmSync8,
50659
51713
  writeFileSync as writeFileSync8
50660
51714
  } from "fs";
50661
- import { dirname as dirname13, join as join23 } from "path";
51715
+ import { dirname as dirname14, join as join26 } from "path";
50662
51716
  var DIRECTORY_MODE4 = 448;
50663
51717
  var FILE_MODE3 = 384;
50664
51718
  var DEAD_LETTER_DIRNAME = "dead-letter";
50665
51719
  function deadLetterDirectoryForRotation(flushingPath) {
50666
- return join23(dirname13(flushingPath), DEAD_LETTER_DIRNAME);
51720
+ return join26(dirname14(flushingPath), DEAD_LETTER_DIRNAME);
50667
51721
  }
50668
51722
  function deadLetterPathForRawLine(flushingPath, rawLine) {
50669
- const quarantineId = createHash9("sha256").update(rawLine).digest("hex");
50670
- return join23(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
51723
+ const quarantineId = createHash10("sha256").update(rawLine).digest("hex");
51724
+ return join26(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
50671
51725
  }
50672
51726
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
50673
51727
  const directory = deadLetterDirectoryForRotation(flushingPath);
50674
51728
  mkdirSync12(directory, { recursive: true, mode: DIRECTORY_MODE4 });
50675
51729
  chmodSync7(directory, DIRECTORY_MODE4);
50676
- persistDirectory(dirname13(directory));
51730
+ persistDirectory(dirname14(directory));
50677
51731
  return directory;
50678
51732
  }
50679
51733
  function persistDeadLetter(directory, path9, quarantineId, record3, persistDirectory) {
50680
- if (existsSync17(path9)) {
51734
+ if (existsSync19(path9)) {
50681
51735
  persistDirectory(directory);
50682
51736
  return;
50683
51737
  }
50684
- const temporaryPath = join23(
51738
+ const temporaryPath = join26(
50685
51739
  directory,
50686
51740
  `.${quarantineId}.${String(process.pid)}.${randomBytes7(8).toString("hex")}.tmp`
50687
51741
  );
@@ -50708,12 +51762,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
50708
51762
  const serializedMove = JSON.stringify(move);
50709
51763
  const record3 = {
50710
51764
  version: 1,
50711
- quarantineId: createHash9("sha256").update(serializedMove).digest("hex"),
51765
+ quarantineId: createHash10("sha256").update(serializedMove).digest("hex"),
50712
51766
  quarantinedAt: now(),
50713
51767
  reason,
50714
51768
  move
50715
51769
  };
50716
- const path9 = join23(directory, `${record3.quarantineId}.json`);
51770
+ const path9 = join26(directory, `${record3.quarantineId}.json`);
50717
51771
  persistDeadLetter(directory, path9, record3.quarantineId, record3, persistDirectory);
50718
51772
  return record3;
50719
51773
  }
@@ -50724,7 +51778,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
50724
51778
  const record3 = {
50725
51779
  version: 1,
50726
51780
  recordKind: "raw_line_v1",
50727
- quarantineId: createHash9("sha256").update(bytes).digest("hex"),
51781
+ quarantineId: createHash10("sha256").update(bytes).digest("hex"),
50728
51782
  quarantinedAt: now(),
50729
51783
  reason: "invalid_move",
50730
51784
  rawLineEncoding: "base64",
@@ -50993,7 +52047,7 @@ async function drainFlushingPath(flushingPath, client, binding, options = {}) {
50993
52047
  } finally {
50994
52048
  input.destroy();
50995
52049
  }
50996
- unlinkSync5(flushingPath);
52050
+ unlinkSync6(flushingPath);
50997
52051
  try {
50998
52052
  removeDrainCheckpoint(flushingPath);
50999
52053
  } catch {
@@ -51137,7 +52191,7 @@ async function flushOnce() {
51137
52191
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
51138
52192
  }
51139
52193
  var flushInFlight;
51140
- var FLUSH_LOCK_PATH = join24(dirname14(JOURNAL_DIR), ".flush.lock");
52194
+ var FLUSH_LOCK_PATH = join27(dirname15(JOURNAL_DIR), ".flush.lock");
51141
52195
  var FLUSH_LOCK_TIMEOUT_MS = 250;
51142
52196
  function isFlushLockContended(error) {
51143
52197
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -51269,23 +52323,23 @@ function registerMovesCommands(program3) {
51269
52323
  }
51270
52324
  });
51271
52325
  moves.command("bind").description("Pin the current directory to an org via .prim/workspace.json").requiredOption("--orgId <orgId>", "Convex organization id").action((opts) => {
51272
- const dir = join25(process.cwd(), ".prim");
51273
- if (!existsSync18(dir)) {
52326
+ const dir = join28(process.cwd(), ".prim");
52327
+ if (!existsSync20(dir)) {
51274
52328
  mkdirSync13(dir, { recursive: true, mode: DIR_MODE });
51275
52329
  }
51276
- const file = join25(process.cwd(), WORKSPACE_FILE);
52330
+ const file = join28(process.cwd(), WORKSPACE_FILE);
51277
52331
  writeFileSync9(file, JSON.stringify({ orgId: opts.orgId, boundAt: Date.now() }, null, 2), {
51278
52332
  mode: FILE_MODE4
51279
52333
  });
51280
52334
  console.log(`[prim] bound ${process.cwd()} to org ${opts.orgId}`);
51281
52335
  });
51282
52336
  moves.command("drop").description("Remove the .prim/workspace.json binding from the cwd").action(() => {
51283
- const file = join25(process.cwd(), WORKSPACE_FILE);
51284
- if (!existsSync18(file)) {
52337
+ const file = join28(process.cwd(), WORKSPACE_FILE);
52338
+ if (!existsSync20(file)) {
51285
52339
  console.log("[prim] no workspace binding in cwd");
51286
52340
  return;
51287
52341
  }
51288
- unlinkSync6(file);
52342
+ unlinkSync7(file);
51289
52343
  console.log(`[prim] dropped workspace binding from ${process.cwd()}`);
51290
52344
  });
51291
52345
  }
@@ -51411,31 +52465,31 @@ function registerReconcileCommands(program3) {
51411
52465
 
51412
52466
  // src/commands/session.ts
51413
52467
  import {
51414
- existsSync as existsSync20,
52468
+ existsSync as existsSync22,
51415
52469
  mkdirSync as mkdirSync14,
51416
- readFileSync as readFileSync20,
51417
- readdirSync as readdirSync7,
51418
- unlinkSync as unlinkSync7,
52470
+ readFileSync as readFileSync22,
52471
+ readdirSync as readdirSync9,
52472
+ unlinkSync as unlinkSync8,
51419
52473
  writeFileSync as writeFileSync10
51420
52474
  } from "fs";
51421
- import { join as join27 } from "path";
52475
+ import { join as join30 } from "path";
51422
52476
 
51423
52477
  // src/binding.ts
51424
- import { existsSync as existsSync19, readFileSync as readFileSync19 } from "fs";
51425
- import { dirname as dirname15, join as join26 } from "path";
52478
+ import { existsSync as existsSync21, readFileSync as readFileSync21 } from "fs";
52479
+ import { dirname as dirname16, join as join29 } from "path";
51426
52480
  var PRIM_CONFIG_DIR = primConfigDirectory();
51427
- var SESSIONS_DIR = join26(PRIM_CONFIG_DIR, "sessions");
52481
+ var SESSIONS_DIR = join29(PRIM_CONFIG_DIR, "sessions");
51428
52482
 
51429
52483
  // src/commands/session.ts
51430
52484
  var DIR_MODE2 = 448;
51431
52485
  var FILE_MODE5 = 384;
51432
52486
  function ensureDir() {
51433
- if (!existsSync20(SESSIONS_DIR)) {
52487
+ if (!existsSync22(SESSIONS_DIR)) {
51434
52488
  mkdirSync14(SESSIONS_DIR, { recursive: true, mode: DIR_MODE2 });
51435
52489
  }
51436
52490
  }
51437
52491
  function markerPath(sessionId) {
51438
- return join27(SESSIONS_DIR, `${sessionId}.json`);
52492
+ return join30(SESSIONS_DIR, `${sessionId}.json`);
51439
52493
  }
51440
52494
  function registerSessionCommands(program3) {
51441
52495
  const session = program3.command("session").description("Decision Event Pipeline \u2014 session binding markers");
@@ -51451,11 +52505,11 @@ function registerSessionCommands(program3) {
51451
52505
  console.log(`[prim] session ${sessionId} bound to org ${opts.orgId}`);
51452
52506
  });
51453
52507
  session.command("list").description("List active session markers").action(() => {
51454
- if (!existsSync20(SESSIONS_DIR)) {
52508
+ if (!existsSync22(SESSIONS_DIR)) {
51455
52509
  console.log("[prim] no session markers");
51456
52510
  return;
51457
52511
  }
51458
- const files = readdirSync7(SESSIONS_DIR).filter((f) => f.endsWith(".json"));
52512
+ const files = readdirSync9(SESSIONS_DIR).filter((f) => f.endsWith(".json"));
51459
52513
  if (files.length === 0) {
51460
52514
  console.log("[prim] no session markers");
51461
52515
  return;
@@ -51463,7 +52517,7 @@ function registerSessionCommands(program3) {
51463
52517
  for (const f of files) {
51464
52518
  const sessionId = f.replace(/\.json$/, "");
51465
52519
  try {
51466
- const m = JSON.parse(readFileSync20(join27(SESSIONS_DIR, f), "utf-8"));
52520
+ const m = JSON.parse(readFileSync22(join30(SESSIONS_DIR, f), "utf-8"));
51467
52521
  console.log(`${sessionId} org=${m.orgId}`);
51468
52522
  } catch {
51469
52523
  }
@@ -51471,19 +52525,19 @@ function registerSessionCommands(program3) {
51471
52525
  });
51472
52526
  session.command("drop <sessionId>").description("Remove a session marker").action((sessionId) => {
51473
52527
  const p = markerPath(sessionId);
51474
- if (!existsSync20(p)) {
52528
+ if (!existsSync22(p)) {
51475
52529
  console.log(`[prim] no marker for session ${sessionId}`);
51476
52530
  return;
51477
52531
  }
51478
- unlinkSync7(p);
52532
+ unlinkSync8(p);
51479
52533
  console.log(`[prim] dropped session marker ${sessionId}`);
51480
52534
  });
51481
52535
  }
51482
52536
 
51483
52537
  // src/commands/setup.ts
51484
52538
  import { spawnSync as spawnSync2 } from "child_process";
51485
- import { existsSync as existsSync21, readFileSync as readFileSync21 } from "fs";
51486
- import { join as join28 } from "path";
52539
+ import { existsSync as existsSync23, readFileSync as readFileSync23 } from "fs";
52540
+ import { join as join31 } from "path";
51487
52541
  var EXIT_INCOMPLETE = 1;
51488
52542
  var EXIT_USAGE3 = 2;
51489
52543
  var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
@@ -51524,831 +52578,357 @@ function planSetupSteps(opts) {
51524
52578
  args: ["daemon", "start"],
51525
52579
  required: true
51526
52580
  });
51527
- } else {
51528
- steps.push({
51529
- key: "daemon-opt-out",
51530
- label: "Daemon opt-out",
51531
- args: ["daemon", "stop"],
51532
- required: true
51533
- });
51534
- }
51535
- if (opts.scope === "project") {
51536
- steps.push({ key: "hooks", label: "Git hooks", args: ["hooks", "install"], required: true });
51537
- } else if (opts.globalHooksPath) {
51538
- steps.push({
51539
- key: "hooks",
51540
- label: "Git hooks (global)",
51541
- args: ["hooks", "install", "--scope", "user", "--global-hooks-path"],
51542
- required: true
51543
- });
51544
- }
51545
- const skillArgs = ["skill", "install", "--agent", opts.agent, ...scopeArgs];
51546
- steps.push({ key: "skill", label: "Agent skill", args: skillArgs, required: true });
51547
- steps.push({
51548
- key: "enable",
51549
- label: "Activate this repo",
51550
- args: ["enable"],
51551
- required: true
51552
- });
51553
- if (opts.daemon) {
51554
- steps.push({
51555
- key: "health",
51556
- label: "Capture health",
51557
- args: ["doctor", "--expect-backlog"],
51558
- required: true
51559
- });
51560
- }
51561
- return steps;
51562
- }
51563
- var CONFLICT_SESSION = "session";
51564
- var CONFLICT_HOOKS = "hooks";
51565
- var CONFLICT_SKILL = "skill";
51566
- function planCleanupUninstalls(agent, conflicts) {
51567
- const steps = [];
51568
- if (conflicts.includes(CONFLICT_SESSION) && agent !== "hermes") {
51569
- steps.push([agent, "uninstall", "--scope", "project"]);
51570
- }
51571
- if (conflicts.includes(CONFLICT_HOOKS)) steps.push(["hooks", "uninstall"]);
51572
- if (conflicts.includes(CONFLICT_SKILL)) steps.push(["skill", "uninstall", "--agent", agent]);
51573
- return steps;
51574
- }
51575
- function preCommitRunsPrim(content) {
51576
- return content.includes("# >>> prim pre-commit hook >>>") || content.includes("prim-pre-commit");
51577
- }
51578
- function projectHooksConflict(globalHooksActive, preCommit) {
51579
- return globalHooksActive && preCommit !== void 0 && preCommitRunsPrim(preCommit);
51580
- }
51581
- function enableWiresRepository(root) {
51582
- if (!root) return void 0;
51583
- try {
51584
- if (gitHooksMode({ cwd: root }) === "manual") return void 0;
51585
- return resolveEffectiveGitHook("post-commit", root).location !== "external";
51586
- } catch {
51587
- return void 0;
51588
- }
51589
- }
51590
- function setupGitHooksNote(plan, wiresThisRepository) {
51591
- if (wiresThisRepository === true && plan.action === "add_to_dir") {
51592
- return `git hooks \xB7 Git runs this repository's hooks from inside it, so \`prim enable\` wires it; other repositories may run ${plan.global}, which prim edits only with --global-hooks-path, after asking the user`;
51593
- }
51594
- if (wiresThisRepository === true && plan.action === "system_declined") {
51595
- return `git hooks \xB7 Git runs this repository's hooks from inside it, so \`prim enable\` wires it; other repositories may run the system hooks dir ${plan.system}, which prim never edits`;
51596
- }
51597
- switch (plan.action) {
51598
- case "refresh":
51599
- return "git hooks \xB7 prim's global hooks stay active; `prim enable` refreshes them";
51600
- case "present_in_dir":
51601
- return `git hooks \xB7 prim's hooks are already in your global hooks dir ${plan.global}`;
51602
- case "add_to_dir":
51603
- return `git hooks \xB7 your global core.hooksPath (${plan.global}) runs every repository's hooks, so \`prim enable\` cannot wire this repository without it; add prim there with --global-hooks-path, after asking the user`;
51604
- case "system_declined":
51605
- return `git hooks \xB7 the system core.hooksPath (${plan.system}) runs every repository's hooks, so \`prim enable\` cannot wire this repository: place \`prim hooks snippet <hook>\` there, or, after asking the user, run \`prim hooks install --scope user --global-hooks-path --force\` (its hooks stop firing)`;
51606
- case "manual":
51607
- return "git hooks \xB7 prim.gitHooks=manual: prim writes no hook files; wire them with `prim hooks snippet <hook>`";
51608
- default:
51609
- return "git hooks \xB7 wired per repository by `prim enable`; git's global hooks are untouched (opt in with --global-hooks-path)";
51610
- }
51611
- }
51612
- function detectProjectConflicts(agent, run, globalHooksActive) {
51613
- const conflicts = [];
51614
- if (agent !== "hermes") {
51615
- try {
51616
- const parsed = JSON.parse(run([agent, "status"], true).stdout || "{}");
51617
- if (parsed.project?.gate || parsed.project?.capture) conflicts.push(CONFLICT_SESSION);
51618
- } catch {
51619
- }
51620
- }
51621
- let preCommit;
51622
- try {
51623
- const root = gitToplevel();
51624
- const path9 = root && join28(root, ".git", "hooks", "pre-commit");
51625
- if (path9 && existsSync21(path9)) preCommit = readFileSync21(path9, "utf-8");
51626
- } catch {
51627
- }
51628
- if (projectHooksConflict(globalHooksActive, preCommit)) conflicts.push(CONFLICT_HOOKS);
51629
- try {
51630
- const parsed = JSON.parse(
51631
- run(["skill", "status", "--agent", agent, "--json"], true).stdout || "{}"
51632
- );
51633
- if (parsed.installed) conflicts.push(CONFLICT_SKILL);
51634
- } catch {
51635
- }
51636
- return conflicts;
51637
- }
51638
- function detectAgent(env4) {
51639
- if (env4.HERMES_INTERACTIVE) {
51640
- return "hermes";
51641
- }
51642
- if (env4.CURSOR_AGENT) {
51643
- return "cursor";
51644
- }
51645
- return "claude";
51646
- }
51647
- function resolveAgent(agentFlag, env4) {
51648
- if (agentFlag !== void 0) {
51649
- return { agent: agentFlag, detected: false };
51650
- }
51651
- return { agent: detectAgent(env4), detected: true };
51652
- }
51653
- function parseSetupAuthStatus(result) {
51654
- try {
51655
- const parsed = JSON.parse(result.stdout || "{}");
51656
- if (parsed.status === "valid" || parsed.authenticated === true) return "valid";
51657
- if (parsed.status === "unreachable") return "unreachable";
51658
- if (parsed.status === "invalid") return "invalid";
51659
- } catch {
51660
- }
51661
- return result.code === EXIT_USAGE3 ? "unreachable" : "invalid";
51662
- }
51663
- function registerSetupCommand(program3, dependencies = {}) {
51664
- program3.command("setup").description(
51665
- "Install everything in one shot (auth, session + git hooks, daemon, skill, welcome)"
51666
- ).option("--agent <agent>", "claude, codex, cursor, or hermes (auto-detected when omitted)").option(
51667
- "--scope <scope>",
51668
- "user (default \u2014 agent integration and skill for every repo; git hooks per repo via enable) or project (this repo only)",
51669
- "user"
51670
- ).option(
51671
- "--global-hooks-path",
51672
- "with the default user scope, also change git's global hooks so prim's hooks run in every repository"
51673
- ).option(
51674
- "--migrate",
51675
- "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
51676
- ).option("--no-daemon", "stop and disable the companion daemon").action((opts) => {
51677
- const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
51678
- if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
51679
- process.stderr.write(
51680
- `[prim] unknown --agent "${agentInput}" (expected claude, codex, cursor, or hermes)
51681
- `
51682
- );
51683
- (dependencies.exit ?? process.exit)(EXIT_USAGE3);
51684
- return;
51685
- }
51686
- if (opts.scope !== "project" && opts.scope !== "user") {
51687
- process.stderr.write(`[prim] unknown --scope "${opts.scope}" (expected project or user)
51688
- `);
51689
- (dependencies.exit ?? process.exit)(EXIT_USAGE3);
51690
- return;
51691
- }
51692
- if (opts.globalHooksPath && opts.scope !== "user") {
51693
- process.stderr.write("[prim] --global-hooks-path applies only with --scope user\n");
51694
- (dependencies.exit ?? process.exit)(EXIT_USAGE3);
51695
- return;
51696
- }
51697
- const agent = agentInput;
51698
- const scope = opts.scope;
51699
- const self = process.argv[1];
51700
- const globals = program3.optsWithGlobals();
51701
- const run = dependencies.run ?? ((args, capture = false) => {
51702
- const r = spawnSync2(
51703
- process.execPath,
51704
- [self, ...args],
51705
- setupStepSpawnOptions(capture, process.env, { startsDaemon: opts.daemon })
51706
- );
51707
- return { code: r.status ?? 1, stdout: capture ? r.stdout ?? "" : "" };
51708
- });
51709
- const results = {};
51710
- const note = dependencies.note ?? ((msg) => {
51711
- process.stderr.write(`[prim] ${msg}
51712
- `);
51713
- });
51714
- const exit = dependencies.exit ?? process.exit;
51715
- if (detected && agent !== "claude") {
51716
- note(`agent \xB7 detected ${agent} session (override with --agent <agent>)`);
51717
- }
51718
- let authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
51719
- if (authStatus === "unreachable") {
51720
- note("auth \xB7 verification unavailable; no setup changes were made");
51721
- exit(EXIT_USAGE3);
51722
- return;
51723
- }
51724
- if (authStatus === "invalid") {
51725
- note("auth \xB7 opening browser to authenticate\u2026");
51726
- const login = run(["auth", "login"]);
51727
- if (login.code !== 0) {
51728
- note("auth \xB7 login failed; no integration changes were made");
51729
- exit(EXIT_INCOMPLETE);
51730
- return;
51731
- }
51732
- authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
51733
- if (authStatus !== "valid") {
51734
- note(
51735
- authStatus === "unreachable" ? "auth \xB7 login completed but verification is unavailable; no integration changes were made" : "auth \xB7 login did not produce valid credentials; no integration changes were made"
51736
- );
51737
- exit(authStatus === "unreachable" ? EXIT_USAGE3 : EXIT_INCOMPLETE);
51738
- return;
51739
- }
51740
- } else {
51741
- note("auth \xB7 already authenticated");
51742
- }
51743
- results.auth = "ok";
51744
- if (agent === "claude") {
51745
- note("pre-authorize \xB7 writing prim allow-rule (user scope)\u2026");
51746
- results.preauth = run(["claude", "preauth", "--scope", "user"]).code === 0 ? "ok" : "skipped";
51747
- }
51748
- const setupSteps = planSetupSteps({
51749
- agent,
51750
- daemon: opts.daemon,
51751
- scope,
51752
- globalHooksPath: opts.globalHooksPath === true
51753
- });
51754
- for (const step of setupSteps.filter(
51755
- (candidate) => candidate.key !== "enable" && candidate.key !== "health"
51756
- )) {
51757
- note(`${step.label} \xB7 installing\u2026`);
51758
- const { code } = run(step.args);
51759
- results[step.key] = code === 0 ? "ok" : code === EXIT_GLOBAL_HOOKS_NOT_INSTALLED && step.key === "hooks" ? "skipped" : step.required ? "failed" : "skipped";
51760
- }
51761
- if (scope === "user" && !opts.globalHooksPath) {
51762
- note(setupGitHooksNote(planGlobalHooks(), enableWiresRepository(gitToplevel())));
51763
- }
51764
- if (scope === "user") {
51765
- const conflicts = detectProjectConflicts(agent, run, globalHooksPathIsPrims());
51766
- if (conflicts.length > 0 && opts.migrate) {
51767
- note(`migrate \xB7 removing project-scoped config (${conflicts.join(", ")})\u2026`);
51768
- const ok = planCleanupUninstalls(agent, conflicts).map((args) => run(args).code === 0).every(Boolean);
51769
- results.migrate = ok ? "ok" : "failed";
51770
- } else if (conflicts.length > 0) {
51771
- note(
51772
- `migrate \xB7 project-scoped prim config present in this repo (${conflicts.join(", ")}) \u2014 it will double-fire with the user-scope install. Re-run \`prim setup --migrate\` to remove it.`
51773
- );
51774
- }
51775
- }
51776
- const enableStep = setupSteps.find((candidate) => candidate.key === "enable");
51777
- if (enableStep) {
51778
- note(`${enableStep.label} \xB7 installing\u2026`);
51779
- const enableArgs = [
51780
- ...enableStep.args,
51781
- ...globals.yes ? ["--yes"] : [],
51782
- ...globals.nonInteractive ? ["--non-interactive"] : []
51783
- ];
51784
- const { code } = run(enableArgs);
51785
- results[enableStep.key] = code === 0 ? "ok" : enableStep.required ? "failed" : "skipped";
51786
- }
51787
- const healthStep = setupSteps.find((candidate) => candidate.key === "health");
51788
- if (healthStep) {
51789
- note(`${healthStep.label} \xB7 verifying\u2026`);
51790
- const { code } = run(healthStep.args);
51791
- results[healthStep.key] = code === 0 ? "ok" : healthStep.required ? "failed" : "skipped";
51792
- }
51793
- note("welcome");
51794
- results.welcome = run(["welcome", "--agent", agent]).code === 0 ? "ok" : "failed";
51795
- const failed = Object.entries(results).filter(([, v]) => v === "failed").map(([k]) => k);
51796
- const trail = Object.entries(results).map(([k, v]) => `${k}:${v}`).join(" \xB7 ");
51797
- note(
51798
- `setup ${failed.length === 0 ? "complete" : `incomplete (failed: ${failed.join(", ")})`} \u2014 ${trail}`
51799
- );
51800
- exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
51801
- });
51802
- }
51803
-
51804
- // src/commands/skill.ts
51805
- import { createHash as createHash11 } from "crypto";
51806
- import {
51807
- constants as constants8,
51808
- closeSync as closeSync8,
51809
- existsSync as existsSync23,
51810
- fstatSync as fstatSync4,
51811
- lstatSync as lstatSync9,
51812
- openSync as openSync8,
51813
- readFileSync as readFileSync23,
51814
- readSync as readSync4,
51815
- readdirSync as readdirSync9,
51816
- rmdirSync as rmdirSync3,
51817
- unlinkSync as unlinkSync8
51818
- } from "fs";
51819
- import { homedir as homedir11 } from "os";
51820
- import { dirname as dirname17, join as join31, resolve as resolve9 } from "path";
51821
- import { fileURLToPath as fileURLToPath5 } from "url";
51822
-
51823
- // node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
51824
- function Diff() {
51825
- }
51826
- Diff.prototype = {
51827
- diff: function diff(oldString, newString) {
51828
- var _options$timeout;
51829
- var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
51830
- var callback = options.callback;
51831
- if (typeof options === "function") {
51832
- callback = options;
51833
- options = {};
51834
- }
51835
- this.options = options;
51836
- var self = this;
51837
- function done(value) {
51838
- if (callback) {
51839
- setTimeout(function() {
51840
- callback(void 0, value);
51841
- }, 0);
51842
- return true;
51843
- } else {
51844
- return value;
51845
- }
51846
- }
51847
- oldString = this.castInput(oldString);
51848
- newString = this.castInput(newString);
51849
- oldString = this.removeEmpty(this.tokenize(oldString));
51850
- newString = this.removeEmpty(this.tokenize(newString));
51851
- var newLen = newString.length, oldLen = oldString.length;
51852
- var editLength = 1;
51853
- var maxEditLength = newLen + oldLen;
51854
- if (options.maxEditLength) {
51855
- maxEditLength = Math.min(maxEditLength, options.maxEditLength);
51856
- }
51857
- var maxExecutionTime = (_options$timeout = options.timeout) !== null && _options$timeout !== void 0 ? _options$timeout : Infinity;
51858
- var abortAfterTimestamp = Date.now() + maxExecutionTime;
51859
- var bestPath = [{
51860
- oldPos: -1,
51861
- lastComponent: void 0
51862
- }];
51863
- var newPos = this.extractCommon(bestPath[0], newString, oldString, 0);
51864
- if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
51865
- return done([{
51866
- value: this.join(newString),
51867
- count: newString.length
51868
- }]);
51869
- }
51870
- var minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
51871
- function execEditLength() {
51872
- for (var diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
51873
- var basePath = void 0;
51874
- var removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
51875
- if (removePath) {
51876
- bestPath[diagonalPath - 1] = void 0;
51877
- }
51878
- var canAdd = false;
51879
- if (addPath) {
51880
- var addPathNewPos = addPath.oldPos - diagonalPath;
51881
- canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
51882
- }
51883
- var canRemove = removePath && removePath.oldPos + 1 < oldLen;
51884
- if (!canAdd && !canRemove) {
51885
- bestPath[diagonalPath] = void 0;
51886
- continue;
51887
- }
51888
- if (!canRemove || canAdd && removePath.oldPos + 1 < addPath.oldPos) {
51889
- basePath = self.addToPath(addPath, true, void 0, 0);
51890
- } else {
51891
- basePath = self.addToPath(removePath, void 0, true, 1);
51892
- }
51893
- newPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
51894
- if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
51895
- return done(buildValues(self, basePath.lastComponent, newString, oldString, self.useLongestToken));
51896
- } else {
51897
- bestPath[diagonalPath] = basePath;
51898
- if (basePath.oldPos + 1 >= oldLen) {
51899
- maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
51900
- }
51901
- if (newPos + 1 >= newLen) {
51902
- minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
51903
- }
51904
- }
51905
- }
51906
- editLength++;
51907
- }
51908
- if (callback) {
51909
- (function exec2() {
51910
- setTimeout(function() {
51911
- if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
51912
- return callback();
51913
- }
51914
- if (!execEditLength()) {
51915
- exec2();
51916
- }
51917
- }, 0);
51918
- })();
51919
- } else {
51920
- while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
51921
- var ret = execEditLength();
51922
- if (ret) {
51923
- return ret;
51924
- }
51925
- }
51926
- }
51927
- },
51928
- addToPath: function addToPath(path9, added, removed, oldPosInc) {
51929
- var last = path9.lastComponent;
51930
- if (last && last.added === added && last.removed === removed) {
51931
- return {
51932
- oldPos: path9.oldPos + oldPosInc,
51933
- lastComponent: {
51934
- count: last.count + 1,
51935
- added,
51936
- removed,
51937
- previousComponent: last.previousComponent
51938
- }
51939
- };
51940
- } else {
51941
- return {
51942
- oldPos: path9.oldPos + oldPosInc,
51943
- lastComponent: {
51944
- count: 1,
51945
- added,
51946
- removed,
51947
- previousComponent: last
51948
- }
51949
- };
51950
- }
51951
- },
51952
- extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
51953
- var newLen = newString.length, oldLen = oldString.length, oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
51954
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
51955
- newPos++;
51956
- oldPos++;
51957
- commonCount++;
51958
- }
51959
- if (commonCount) {
51960
- basePath.lastComponent = {
51961
- count: commonCount,
51962
- previousComponent: basePath.lastComponent
51963
- };
51964
- }
51965
- basePath.oldPos = oldPos;
51966
- return newPos;
51967
- },
51968
- equals: function equals(left, right) {
51969
- if (this.options.comparator) {
51970
- return this.options.comparator(left, right);
51971
- } else {
51972
- return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
51973
- }
51974
- },
51975
- removeEmpty: function removeEmpty(array) {
51976
- var ret = [];
51977
- for (var i = 0; i < array.length; i++) {
51978
- if (array[i]) {
51979
- ret.push(array[i]);
51980
- }
51981
- }
51982
- return ret;
51983
- },
51984
- castInput: function castInput(value) {
51985
- return value;
51986
- },
51987
- tokenize: function tokenize(value) {
51988
- return value.split("");
51989
- },
51990
- join: function join29(chars) {
51991
- return chars.join("");
51992
- }
51993
- };
51994
- function buildValues(diff2, lastComponent, newString, oldString, useLongestToken) {
51995
- var components = [];
51996
- var nextComponent;
51997
- while (lastComponent) {
51998
- components.push(lastComponent);
51999
- nextComponent = lastComponent.previousComponent;
52000
- delete lastComponent.previousComponent;
52001
- lastComponent = nextComponent;
52002
- }
52003
- components.reverse();
52004
- var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
52005
- for (; componentPos < componentLen; componentPos++) {
52006
- var component = components[componentPos];
52007
- if (!component.removed) {
52008
- if (!component.added && useLongestToken) {
52009
- var value = newString.slice(newPos, newPos + component.count);
52010
- value = value.map(function(value2, i) {
52011
- var oldValue = oldString[oldPos + i];
52012
- return oldValue.length > value2.length ? oldValue : value2;
52013
- });
52014
- component.value = diff2.join(value);
52015
- } else {
52016
- component.value = diff2.join(newString.slice(newPos, newPos + component.count));
52017
- }
52018
- newPos += component.count;
52019
- if (!component.added) {
52020
- oldPos += component.count;
52021
- }
52022
- } else {
52023
- component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
52024
- oldPos += component.count;
52025
- if (componentPos && components[componentPos - 1].added) {
52026
- var tmp = components[componentPos - 1];
52027
- components[componentPos - 1] = components[componentPos];
52028
- components[componentPos] = tmp;
52029
- }
52030
- }
52031
- }
52032
- var finalComponent = components[componentLen - 1];
52033
- if (componentLen > 1 && typeof finalComponent.value === "string" && (finalComponent.added || finalComponent.removed) && diff2.equals("", finalComponent.value)) {
52034
- components[componentLen - 2].value += finalComponent.value;
52035
- components.pop();
52036
- }
52037
- return components;
52038
- }
52039
- var characterDiff = new Diff();
52040
- var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
52041
- var reWhitespace = /\S/;
52042
- var wordDiff = new Diff();
52043
- wordDiff.equals = function(left, right) {
52044
- if (this.options.ignoreCase) {
52045
- left = left.toLowerCase();
52046
- right = right.toLowerCase();
52047
- }
52048
- return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
52049
- };
52050
- wordDiff.tokenize = function(value) {
52051
- var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
52052
- for (var i = 0; i < tokens.length - 1; i++) {
52053
- if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
52054
- tokens[i] += tokens[i + 2];
52055
- tokens.splice(i + 1, 2);
52056
- i--;
52057
- }
52058
- }
52059
- return tokens;
52060
- };
52061
- var lineDiff = new Diff();
52062
- lineDiff.tokenize = function(value) {
52063
- if (this.options.stripTrailingCr) {
52064
- value = value.replace(/\r\n/g, "\n");
52581
+ } else {
52582
+ steps.push({
52583
+ key: "daemon-opt-out",
52584
+ label: "Daemon opt-out",
52585
+ args: ["daemon", "stop"],
52586
+ required: true
52587
+ });
52065
52588
  }
52066
- var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
52067
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
52068
- linesAndNewlines.pop();
52589
+ if (opts.scope === "project") {
52590
+ steps.push({ key: "hooks", label: "Git hooks", args: ["hooks", "install"], required: true });
52591
+ } else if (opts.globalHooksPath) {
52592
+ steps.push({
52593
+ key: "hooks",
52594
+ label: "Git hooks (global)",
52595
+ args: ["hooks", "install", "--scope", "user", "--global-hooks-path"],
52596
+ required: true
52597
+ });
52069
52598
  }
52070
- for (var i = 0; i < linesAndNewlines.length; i++) {
52071
- var line = linesAndNewlines[i];
52072
- if (i % 2 && !this.options.newlineIsToken) {
52073
- retLines[retLines.length - 1] += line;
52074
- } else {
52075
- if (this.options.ignoreWhitespace) {
52076
- line = line.trim();
52077
- }
52078
- retLines.push(line);
52079
- }
52599
+ const skillArgs = ["skill", "install", "--agent", opts.agent, ...scopeArgs];
52600
+ steps.push({ key: "skill", label: "Agent skill", args: skillArgs, required: true });
52601
+ steps.push({
52602
+ key: "enable",
52603
+ label: "Activate this repo",
52604
+ args: ["enable"],
52605
+ required: true
52606
+ });
52607
+ if (opts.daemon) {
52608
+ steps.push({
52609
+ key: "health",
52610
+ label: "Capture health",
52611
+ args: ["doctor", "--expect-backlog"],
52612
+ required: true
52613
+ });
52080
52614
  }
52081
- return retLines;
52082
- };
52083
- function diffLines(oldStr, newStr, callback) {
52084
- return lineDiff.diff(oldStr, newStr, callback);
52615
+ return steps;
52085
52616
  }
52086
- var sentenceDiff = new Diff();
52087
- sentenceDiff.tokenize = function(value) {
52088
- return value.split(/(\S.+?[.!?])(?=\s+|$)/);
52089
- };
52090
- var cssDiff = new Diff();
52091
- cssDiff.tokenize = function(value) {
52092
- return value.split(/([{}:;,]|\s+)/);
52093
- };
52094
- function _typeof(obj) {
52095
- "@babel/helpers - typeof";
52096
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
52097
- _typeof = function(obj2) {
52098
- return typeof obj2;
52099
- };
52100
- } else {
52101
- _typeof = function(obj2) {
52102
- return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
52103
- };
52617
+ var CONFLICT_SESSION = "session";
52618
+ var CONFLICT_HOOKS = "hooks";
52619
+ var CONFLICT_SKILL = "skill";
52620
+ function planCleanupUninstalls(agent, conflicts) {
52621
+ const steps = [];
52622
+ if (conflicts.includes(CONFLICT_SESSION) && agent !== "hermes") {
52623
+ steps.push([agent, "uninstall", "--scope", "project"]);
52104
52624
  }
52105
- return _typeof(obj);
52106
- }
52107
- function _toConsumableArray(arr) {
52108
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
52109
- }
52110
- function _arrayWithoutHoles(arr) {
52111
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
52112
- }
52113
- function _iterableToArray(iter) {
52114
- if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
52625
+ if (conflicts.includes(CONFLICT_HOOKS)) steps.push(["hooks", "uninstall"]);
52626
+ if (conflicts.includes(CONFLICT_SKILL)) steps.push(["skill", "uninstall", "--agent", agent]);
52627
+ return steps;
52115
52628
  }
52116
- function _unsupportedIterableToArray(o, minLen) {
52117
- if (!o) return;
52118
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
52119
- var n = Object.prototype.toString.call(o).slice(8, -1);
52120
- if (n === "Object" && o.constructor) n = o.constructor.name;
52121
- if (n === "Map" || n === "Set") return Array.from(o);
52122
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
52629
+ function preCommitRunsPrim(content) {
52630
+ return content.includes("# >>> prim pre-commit hook >>>") || content.includes("prim-pre-commit");
52123
52631
  }
52124
- function _arrayLikeToArray(arr, len) {
52125
- if (len == null || len > arr.length) len = arr.length;
52126
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
52127
- return arr2;
52632
+ function projectHooksConflict(globalHooksActive, preCommit) {
52633
+ return globalHooksActive && preCommit !== void 0 && preCommitRunsPrim(preCommit);
52128
52634
  }
52129
- function _nonIterableSpread() {
52130
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
52635
+ function enableWiresRepository(root) {
52636
+ if (!root) return void 0;
52637
+ try {
52638
+ if (gitHooksMode({ cwd: root }) === "manual") return void 0;
52639
+ return resolveEffectiveGitHook("post-commit", root).location !== "external";
52640
+ } catch {
52641
+ return void 0;
52642
+ }
52131
52643
  }
52132
- var objectPrototypeToString = Object.prototype.toString;
52133
- var jsonDiff = new Diff();
52134
- jsonDiff.useLongestToken = true;
52135
- jsonDiff.tokenize = lineDiff.tokenize;
52136
- jsonDiff.castInput = function(value) {
52137
- var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
52138
- return typeof v === "undefined" ? undefinedReplacement : v;
52139
- } : _this$options$stringi;
52140
- return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
52141
- };
52142
- jsonDiff.equals = function(left, right) {
52143
- return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
52144
- };
52145
- function canonicalize(obj, stack, replacementStack, replacer, key) {
52146
- stack = stack || [];
52147
- replacementStack = replacementStack || [];
52148
- if (replacer) {
52149
- obj = replacer(key, obj);
52644
+ function setupGitHooksNote(plan, wiresThisRepository) {
52645
+ if (wiresThisRepository === true && plan.action === "add_to_dir") {
52646
+ return `git hooks \xB7 Git runs this repository's hooks from inside it, so \`prim enable\` wires it; other repositories may run ${plan.global}, which prim edits only with --global-hooks-path, after asking the user`;
52150
52647
  }
52151
- var i;
52152
- for (i = 0; i < stack.length; i += 1) {
52153
- if (stack[i] === obj) {
52154
- return replacementStack[i];
52155
- }
52648
+ if (wiresThisRepository === true && plan.action === "system_declined") {
52649
+ return `git hooks \xB7 Git runs this repository's hooks from inside it, so \`prim enable\` wires it; other repositories may run the system hooks dir ${plan.system}, which prim never edits`;
52156
52650
  }
52157
- var canonicalizedObj;
52158
- if ("[object Array]" === objectPrototypeToString.call(obj)) {
52159
- stack.push(obj);
52160
- canonicalizedObj = new Array(obj.length);
52161
- replacementStack.push(canonicalizedObj);
52162
- for (i = 0; i < obj.length; i += 1) {
52163
- canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
52651
+ switch (plan.action) {
52652
+ case "refresh":
52653
+ return "git hooks \xB7 prim's global hooks stay active; `prim enable` refreshes them";
52654
+ case "present_in_dir":
52655
+ return `git hooks \xB7 prim's hooks are already in your global hooks dir ${plan.global}`;
52656
+ case "add_to_dir":
52657
+ return `git hooks \xB7 your global core.hooksPath (${plan.global}) runs every repository's hooks, so \`prim enable\` cannot wire this repository without it; add prim there with --global-hooks-path, after asking the user`;
52658
+ case "system_declined":
52659
+ return `git hooks \xB7 the system core.hooksPath (${plan.system}) runs every repository's hooks, so \`prim enable\` cannot wire this repository: place \`prim hooks snippet <hook>\` there, or, after asking the user, run \`prim hooks install --scope user --global-hooks-path --force\` (its hooks stop firing)`;
52660
+ case "manual":
52661
+ return "git hooks \xB7 prim.gitHooks=manual: prim writes no hook files; wire them with `prim hooks snippet <hook>`";
52662
+ default:
52663
+ return "git hooks \xB7 wired per repository by `prim enable`; git's global hooks are untouched (opt in with --global-hooks-path)";
52664
+ }
52665
+ }
52666
+ function detectProjectConflicts(agent, run, globalHooksActive) {
52667
+ const conflicts = [];
52668
+ if (agent !== "hermes") {
52669
+ try {
52670
+ const parsed = JSON.parse(run([agent, "status"], true).stdout || "{}");
52671
+ if (parsed.project?.gate || parsed.project?.capture) conflicts.push(CONFLICT_SESSION);
52672
+ } catch {
52164
52673
  }
52165
- stack.pop();
52166
- replacementStack.pop();
52167
- return canonicalizedObj;
52168
52674
  }
52169
- if (obj && obj.toJSON) {
52170
- obj = obj.toJSON();
52675
+ let preCommit;
52676
+ try {
52677
+ const root = gitToplevel();
52678
+ const path9 = root && join31(root, ".git", "hooks", "pre-commit");
52679
+ if (path9 && existsSync23(path9)) preCommit = readFileSync23(path9, "utf-8");
52680
+ } catch {
52171
52681
  }
52172
- if (_typeof(obj) === "object" && obj !== null) {
52173
- stack.push(obj);
52174
- canonicalizedObj = {};
52175
- replacementStack.push(canonicalizedObj);
52176
- var sortedKeys = [], _key;
52177
- for (_key in obj) {
52178
- if (obj.hasOwnProperty(_key)) {
52179
- sortedKeys.push(_key);
52180
- }
52181
- }
52182
- sortedKeys.sort();
52183
- for (i = 0; i < sortedKeys.length; i += 1) {
52184
- _key = sortedKeys[i];
52185
- canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
52186
- }
52187
- stack.pop();
52188
- replacementStack.pop();
52189
- } else {
52190
- canonicalizedObj = obj;
52682
+ if (projectHooksConflict(globalHooksActive, preCommit)) conflicts.push(CONFLICT_HOOKS);
52683
+ try {
52684
+ const parsed = JSON.parse(
52685
+ run(["skill", "status", "--agent", agent, "--json"], true).stdout || "{}"
52686
+ );
52687
+ if (parsed.installed) conflicts.push(CONFLICT_SKILL);
52688
+ } catch {
52191
52689
  }
52192
- return canonicalizedObj;
52690
+ return conflicts;
52193
52691
  }
52194
- var arrayDiff = new Diff();
52195
- arrayDiff.tokenize = function(value) {
52196
- return value.slice();
52197
- };
52198
- arrayDiff.join = arrayDiff.removeEmpty = function(value) {
52199
- return value;
52200
- };
52201
- function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
52202
- if (!options) {
52203
- options = {};
52692
+ function detectAgent(env4) {
52693
+ if (env4.HERMES_INTERACTIVE) {
52694
+ return "hermes";
52204
52695
  }
52205
- if (typeof options.context === "undefined") {
52206
- options.context = 4;
52696
+ if (env4.CURSOR_AGENT) {
52697
+ return "cursor";
52207
52698
  }
52208
- var diff2 = diffLines(oldStr, newStr, options);
52209
- if (!diff2) {
52210
- return;
52699
+ return "claude";
52700
+ }
52701
+ function resolveAgent(agentFlag, env4) {
52702
+ if (agentFlag !== void 0) {
52703
+ return { agent: agentFlag, detected: false };
52211
52704
  }
52212
- diff2.push({
52213
- value: "",
52214
- lines: []
52215
- });
52216
- function contextLines(lines) {
52217
- return lines.map(function(entry) {
52218
- return " " + entry;
52219
- });
52705
+ return { agent: detectAgent(env4), detected: true };
52706
+ }
52707
+ function parseSetupAuthStatus(result) {
52708
+ try {
52709
+ const parsed = JSON.parse(result.stdout || "{}");
52710
+ if (parsed.status === "valid" || parsed.authenticated === true) return "valid";
52711
+ if (parsed.status === "unreachable") return "unreachable";
52712
+ if (parsed.status === "invalid") return "invalid";
52713
+ } catch {
52220
52714
  }
52221
- var hunks = [];
52222
- var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
52223
- var _loop = function _loop2(i2) {
52224
- var current = diff2[i2], lines = current.lines || current.value.replace(/\n$/, "").split("\n");
52225
- current.lines = lines;
52226
- if (current.added || current.removed) {
52227
- var _curRange;
52228
- if (!oldRangeStart) {
52229
- var prev = diff2[i2 - 1];
52230
- oldRangeStart = oldLine;
52231
- newRangeStart = newLine;
52232
- if (prev) {
52233
- curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
52234
- oldRangeStart -= curRange.length;
52235
- newRangeStart -= curRange.length;
52236
- }
52715
+ return result.code === EXIT_USAGE3 ? "unreachable" : "invalid";
52716
+ }
52717
+ function registerSetupCommand(program3, dependencies = {}) {
52718
+ program3.command("setup").description(
52719
+ "Install everything in one shot (auth, session + git hooks, daemon, skill, welcome)"
52720
+ ).option("--agent <agent>", "claude, codex, cursor, or hermes (auto-detected when omitted)").option(
52721
+ "--scope <scope>",
52722
+ "user (default \u2014 agent integration and skill for every repo; git hooks per repo via enable) or project (this repo only)",
52723
+ "user"
52724
+ ).option(
52725
+ "--global-hooks-path",
52726
+ "with the default user scope, also change git's global hooks so prim's hooks run in every repository"
52727
+ ).option(
52728
+ "--migrate",
52729
+ "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
52730
+ ).option("--no-daemon", "stop and disable the companion daemon").option("--skip-demo", "skip the local onboarding tour and remember that choice").action((opts) => {
52731
+ const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
52732
+ if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
52733
+ process.stderr.write(
52734
+ `[prim] unknown --agent "${agentInput}" (expected claude, codex, cursor, or hermes)
52735
+ `
52736
+ );
52737
+ (dependencies.exit ?? process.exit)(EXIT_USAGE3);
52738
+ return;
52739
+ }
52740
+ if (opts.scope !== "project" && opts.scope !== "user") {
52741
+ process.stderr.write(`[prim] unknown --scope "${opts.scope}" (expected project or user)
52742
+ `);
52743
+ (dependencies.exit ?? process.exit)(EXIT_USAGE3);
52744
+ return;
52745
+ }
52746
+ if (opts.globalHooksPath && opts.scope !== "user") {
52747
+ process.stderr.write("[prim] --global-hooks-path applies only with --scope user\n");
52748
+ (dependencies.exit ?? process.exit)(EXIT_USAGE3);
52749
+ return;
52750
+ }
52751
+ const agent = agentInput;
52752
+ const scope = opts.scope;
52753
+ const self = process.argv[1];
52754
+ const globals = program3.optsWithGlobals();
52755
+ const run = dependencies.run ?? ((args, capture = false) => {
52756
+ const r = spawnSync2(
52757
+ process.execPath,
52758
+ [self, ...args],
52759
+ setupStepSpawnOptions(capture, process.env, { startsDaemon: opts.daemon })
52760
+ );
52761
+ return { code: r.status ?? 1, stdout: capture ? r.stdout ?? "" : "" };
52762
+ });
52763
+ const results = {};
52764
+ const note = dependencies.note ?? ((msg) => {
52765
+ process.stderr.write(`[prim] ${msg}
52766
+ `);
52767
+ });
52768
+ const exit = dependencies.exit ?? process.exit;
52769
+ if (detected && agent !== "claude") {
52770
+ note(`agent \xB7 detected ${agent} session (override with --agent <agent>)`);
52771
+ }
52772
+ let authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
52773
+ if (authStatus === "unreachable") {
52774
+ note("auth \xB7 verification unavailable; no setup changes were made");
52775
+ exit(EXIT_USAGE3);
52776
+ return;
52777
+ }
52778
+ if (authStatus === "invalid") {
52779
+ note("auth \xB7 opening browser to authenticate\u2026");
52780
+ const login = run(["auth", "login"]);
52781
+ if (login.code !== 0) {
52782
+ note("auth \xB7 login failed; no integration changes were made");
52783
+ exit(EXIT_INCOMPLETE);
52784
+ return;
52237
52785
  }
52238
- (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function(entry) {
52239
- return (current.added ? "+" : "-") + entry;
52240
- })));
52241
- if (current.added) {
52242
- newLine += lines.length;
52243
- } else {
52244
- oldLine += lines.length;
52786
+ authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
52787
+ if (authStatus !== "valid") {
52788
+ note(
52789
+ authStatus === "unreachable" ? "auth \xB7 login completed but verification is unavailable; no integration changes were made" : "auth \xB7 login did not produce valid credentials; no integration changes were made"
52790
+ );
52791
+ exit(authStatus === "unreachable" ? EXIT_USAGE3 : EXIT_INCOMPLETE);
52792
+ return;
52245
52793
  }
52246
52794
  } else {
52247
- if (oldRangeStart) {
52248
- if (lines.length <= options.context * 2 && i2 < diff2.length - 2) {
52249
- var _curRange2;
52250
- (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
52251
- } else {
52252
- var _curRange3;
52253
- var contextSize = Math.min(lines.length, options.context);
52254
- (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
52255
- var hunk = {
52256
- oldStart: oldRangeStart,
52257
- oldLines: oldLine - oldRangeStart + contextSize,
52258
- newStart: newRangeStart,
52259
- newLines: newLine - newRangeStart + contextSize,
52260
- lines: curRange
52261
- };
52262
- if (i2 >= diff2.length - 2 && lines.length <= options.context) {
52263
- var oldEOFNewline = /\n$/.test(oldStr);
52264
- var newEOFNewline = /\n$/.test(newStr);
52265
- var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
52266
- if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
52267
- curRange.splice(hunk.oldLines, 0, "\");
52268
- }
52269
- if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
52270
- curRange.push("\");
52271
- }
52272
- }
52273
- hunks.push(hunk);
52274
- oldRangeStart = 0;
52275
- newRangeStart = 0;
52276
- curRange = [];
52277
- }
52795
+ note("auth \xB7 already authenticated");
52796
+ }
52797
+ results.auth = "ok";
52798
+ if (agent === "claude") {
52799
+ note("pre-authorize \xB7 writing prim allow-rule (user scope)\u2026");
52800
+ results.preauth = run(["claude", "preauth", "--scope", "user"]).code === 0 ? "ok" : "skipped";
52801
+ }
52802
+ const setupSteps = planSetupSteps({
52803
+ agent,
52804
+ daemon: opts.daemon,
52805
+ scope,
52806
+ globalHooksPath: opts.globalHooksPath === true
52807
+ });
52808
+ for (const step of setupSteps.filter(
52809
+ (candidate) => candidate.key !== "enable" && candidate.key !== "health"
52810
+ )) {
52811
+ note(`${step.label} \xB7 installing\u2026`);
52812
+ const { code } = run(step.args);
52813
+ results[step.key] = code === 0 ? "ok" : code === EXIT_GLOBAL_HOOKS_NOT_INSTALLED && step.key === "hooks" ? "skipped" : step.required ? "failed" : "skipped";
52814
+ }
52815
+ if (scope === "user" && !opts.globalHooksPath) {
52816
+ note(setupGitHooksNote(planGlobalHooks(), enableWiresRepository(gitToplevel())));
52817
+ }
52818
+ if (scope === "user") {
52819
+ const conflicts = detectProjectConflicts(agent, run, globalHooksPathIsPrims());
52820
+ if (conflicts.length > 0 && opts.migrate) {
52821
+ note(`migrate \xB7 removing project-scoped config (${conflicts.join(", ")})\u2026`);
52822
+ const ok = planCleanupUninstalls(agent, conflicts).map((args) => run(args).code === 0).every(Boolean);
52823
+ results.migrate = ok ? "ok" : "failed";
52824
+ } else if (conflicts.length > 0) {
52825
+ note(
52826
+ `migrate \xB7 project-scoped prim config present in this repo (${conflicts.join(", ")}) \u2014 it will double-fire with the user-scope install. Re-run \`prim setup --migrate\` to remove it.`
52827
+ );
52278
52828
  }
52279
- oldLine += lines.length;
52280
- newLine += lines.length;
52281
52829
  }
52282
- };
52283
- for (var i = 0; i < diff2.length; i++) {
52284
- _loop(i);
52285
- }
52286
- return {
52287
- oldFileName,
52288
- newFileName,
52289
- oldHeader,
52290
- newHeader,
52291
- hunks
52292
- };
52293
- }
52294
- function formatPatch(diff2) {
52295
- if (Array.isArray(diff2)) {
52296
- return diff2.map(formatPatch).join("\n");
52297
- }
52298
- var ret = [];
52299
- if (diff2.oldFileName == diff2.newFileName) {
52300
- ret.push("Index: " + diff2.oldFileName);
52301
- }
52302
- ret.push("===================================================================");
52303
- ret.push("--- " + diff2.oldFileName + (typeof diff2.oldHeader === "undefined" ? "" : " " + diff2.oldHeader));
52304
- ret.push("+++ " + diff2.newFileName + (typeof diff2.newHeader === "undefined" ? "" : " " + diff2.newHeader));
52305
- for (var i = 0; i < diff2.hunks.length; i++) {
52306
- var hunk = diff2.hunks[i];
52307
- if (hunk.oldLines === 0) {
52308
- hunk.oldStart -= 1;
52830
+ const enableStep = setupSteps.find((candidate) => candidate.key === "enable");
52831
+ if (enableStep) {
52832
+ note(`${enableStep.label} \xB7 installing\u2026`);
52833
+ const enableArgs = [
52834
+ ...enableStep.args,
52835
+ ...globals.yes ? ["--yes"] : [],
52836
+ ...globals.nonInteractive ? ["--non-interactive"] : []
52837
+ ];
52838
+ const { code } = run(enableArgs);
52839
+ results[enableStep.key] = code === 0 ? "ok" : enableStep.required ? "failed" : "skipped";
52309
52840
  }
52310
- if (hunk.newLines === 0) {
52311
- hunk.newStart -= 1;
52841
+ const healthStep = setupSteps.find((candidate) => candidate.key === "health");
52842
+ if (healthStep) {
52843
+ note(`${healthStep.label} \xB7 verifying\u2026`);
52844
+ const { code } = run(healthStep.args);
52845
+ results[healthStep.key] = code === 0 ? "ok" : healthStep.required ? "failed" : "skipped";
52312
52846
  }
52313
- ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
52314
- ret.push.apply(ret, hunk.lines);
52315
- }
52316
- return ret.join("\n") + "\n";
52317
- }
52318
- function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
52319
- return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
52320
- }
52321
- function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
52322
- return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
52847
+ const installationSucceeded = !Object.values(results).includes("failed");
52848
+ let tourDue = false;
52849
+ if (installationSucceeded && !opts.skipDemo) {
52850
+ try {
52851
+ tourDue = !onboardingFinished();
52852
+ } catch (error) {
52853
+ tourDue = true;
52854
+ note(
52855
+ `demo \xB7 cannot read onboarding state: ${error instanceof Error ? error.message : String(error)}; use prim demo to retry`
52856
+ );
52857
+ }
52858
+ }
52859
+ if (installationSucceeded && opts.skipDemo) {
52860
+ if (run(["demo", "skip"]).code !== 0)
52861
+ note("demo \xB7 could not remember skip; installation remains configured");
52862
+ }
52863
+ note("welcome");
52864
+ results.welcome = run(["welcome", "--agent", agent, ...tourDue ? ["--defer-seeding"] : []]).code === 0 ? "ok" : "failed";
52865
+ const failed = Object.entries(results).filter(([, v]) => v === "failed").map(([k]) => k);
52866
+ const trail = Object.entries(results).map(([k, v]) => `${k}:${v}`).join(" \xB7 ");
52867
+ note(
52868
+ `setup ${failed.length === 0 ? "complete" : `incomplete (failed: ${failed.join(", ")})`} \u2014 ${trail}`
52869
+ );
52870
+ if (failed.length === 0 && tourDue) {
52871
+ const agentDriven = Boolean(
52872
+ opts.agent || !process.stdin.isTTY || !process.stderr.isTTY || process.env.CLAUDECODE || process.env.CODEX_THREAD_ID || process.env.CURSOR_AGENT || process.env.HERMES_INTERACTIVE
52873
+ );
52874
+ const demoResult = run([
52875
+ ...globals.nonInteractive ? ["--non-interactive"] : [],
52876
+ "demo",
52877
+ ...agentDriven ? ["--agent", agent] : []
52878
+ ]);
52879
+ if (demoResult.code !== 0)
52880
+ note("demo \xB7 pending after an error; setup succeeded. Run prim demo to retry");
52881
+ }
52882
+ exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
52883
+ });
52323
52884
  }
52324
52885
 
52886
+ // src/commands/skill.ts
52887
+ import { createHash as createHash12 } from "crypto";
52888
+ import {
52889
+ constants as constants8,
52890
+ closeSync as closeSync8,
52891
+ existsSync as existsSync25,
52892
+ fstatSync as fstatSync4,
52893
+ lstatSync as lstatSync11,
52894
+ openSync as openSync8,
52895
+ readFileSync as readFileSync25,
52896
+ readSync as readSync4,
52897
+ readdirSync as readdirSync11,
52898
+ rmdirSync as rmdirSync4,
52899
+ unlinkSync as unlinkSync9
52900
+ } from "fs";
52901
+ import { homedir as homedir11 } from "os";
52902
+ import { dirname as dirname18, join as join33, resolve as resolve10 } from "path";
52903
+ import { fileURLToPath as fileURLToPath5 } from "url";
52904
+
52325
52905
  // src/commands/claude-plugin.ts
52326
- import { createHash as createHash10 } from "crypto";
52906
+ import { createHash as createHash11 } from "crypto";
52327
52907
  import {
52328
52908
  constants as constants7,
52329
52909
  closeSync as closeSync7,
52330
- existsSync as existsSync22,
52910
+ existsSync as existsSync24,
52331
52911
  fstatSync as fstatSync3,
52332
- lstatSync as lstatSync8,
52912
+ lstatSync as lstatSync10,
52333
52913
  mkdirSync as mkdirSync15,
52334
52914
  openSync as openSync7,
52335
- readFileSync as readFileSync22,
52915
+ readFileSync as readFileSync24,
52336
52916
  readSync as readSync3,
52337
- readdirSync as readdirSync8,
52338
- realpathSync as realpathSync5,
52917
+ readdirSync as readdirSync10,
52918
+ realpathSync as realpathSync6,
52339
52919
  rmSync as rmSync9,
52340
- rmdirSync as rmdirSync2
52920
+ rmdirSync as rmdirSync3
52341
52921
  } from "fs";
52342
52922
  import { homedir as homedir10 } from "os";
52343
- import { dirname as dirname16, isAbsolute as isAbsolute9, join as join30, relative as relative3, resolve as resolve8, sep as sep3 } from "path";
52923
+ import { dirname as dirname17, isAbsolute as isAbsolute9, join as join32, relative as relative3, resolve as resolve9, sep as sep3 } from "path";
52344
52924
  import { fileURLToPath as fileURLToPath4 } from "url";
52345
- var __dirname4 = dirname16(fileURLToPath4(import.meta.url));
52925
+ var __dirname4 = dirname17(fileURLToPath4(import.meta.url));
52346
52926
  var PLUGIN_DESCRIPTION = "Primitive decision-graph guidance for the prim CLI \u2014 a model-invoked skill installed by prim skill install.";
52347
52927
  var MAX_MANIFEST_BYTES2 = 64 * 1024;
52348
52928
  var MAX_SKILL_BYTES = 1024 * 1024;
52349
52929
  function pluginDirFor(cwd, scope) {
52350
- const base = scope === "user" ? join30(homedir10(), ".claude") : join30(gitToplevel(cwd) ?? cwd, ".claude");
52351
- return join30(base, "skills", "prim");
52930
+ const base = scope === "user" ? join32(homedir10(), ".claude") : join32(gitToplevel(cwd) ?? cwd, ".claude");
52931
+ return join32(base, "skills", "prim");
52352
52932
  }
52353
52933
  function resolvePluginDir(cwd, scope) {
52354
52934
  if (scope && scope !== "user" && scope !== "project") {
@@ -52359,10 +52939,10 @@ function resolvePluginDir(cwd, scope) {
52359
52939
  }
52360
52940
  function packageVersion2() {
52361
52941
  let dir = __dirname4;
52362
- while (dir !== dirname16(dir)) {
52363
- const p = resolve8(dir, "package.json");
52364
- if (existsSync22(p)) return JSON.parse(readFileSync22(p, "utf-8")).version;
52365
- dir = dirname16(dir);
52942
+ while (dir !== dirname17(dir)) {
52943
+ const p = resolve9(dir, "package.json");
52944
+ if (existsSync24(p)) return JSON.parse(readFileSync24(p, "utf-8")).version;
52945
+ dir = dirname17(dir);
52366
52946
  }
52367
52947
  return "0.0.0";
52368
52948
  }
@@ -52376,12 +52956,12 @@ function renderClaudePlugin() {
52376
52956
  return { manifest: pluginManifest(version), skill: loadSkill(), version };
52377
52957
  }
52378
52958
  function removeDirIfEmpty(dir) {
52379
- if (existsSync22(dir) && readdirSync8(dir).length === 0) rmdirSync2(dir);
52959
+ if (existsSync24(dir) && readdirSync10(dir).length === 0) rmdirSync3(dir);
52380
52960
  }
52381
52961
  function pluginPaths(dir) {
52382
52962
  return {
52383
- manifestPath: join30(dir, ".claude-plugin", "plugin.json"),
52384
- skillPath: join30(dir, "SKILL.md")
52963
+ manifestPath: join32(dir, ".claude-plugin", "plugin.json"),
52964
+ skillPath: join32(dir, "SKILL.md")
52385
52965
  };
52386
52966
  }
52387
52967
  function installClaudePlugin(cwd, opts) {
@@ -52389,8 +52969,8 @@ function installClaudePlugin(cwd, opts) {
52389
52969
  if (dir === null) return 1;
52390
52970
  const { manifestPath, skillPath } = pluginPaths(dir);
52391
52971
  const { manifest, skill } = renderClaudePlugin();
52392
- const manifestCurrent = existsSync22(manifestPath) ? readFileSync22(manifestPath, "utf-8") : null;
52393
- const skillCurrent = existsSync22(skillPath) ? readFileSync22(skillPath, "utf-8") : null;
52972
+ const manifestCurrent = existsSync24(manifestPath) ? readFileSync24(manifestPath, "utf-8") : null;
52973
+ const skillCurrent = existsSync24(skillPath) ? readFileSync24(skillPath, "utf-8") : null;
52394
52974
  if (manifestCurrent === manifest && skillCurrent === skill) {
52395
52975
  console.log("No changes \u2014 prim skill plugin already up to date.");
52396
52976
  return 0;
@@ -52399,7 +52979,7 @@ function installClaudePlugin(cwd, opts) {
52399
52979
  console.log(`Would write plugin to ${dir} (.claude-plugin/plugin.json + SKILL.md)`);
52400
52980
  return 0;
52401
52981
  }
52402
- mkdirSync15(join30(dir, ".claude-plugin"), { recursive: true });
52982
+ mkdirSync15(join32(dir, ".claude-plugin"), { recursive: true });
52403
52983
  atomicWrite5(manifestPath, manifest);
52404
52984
  atomicWrite5(skillPath, skill);
52405
52985
  console.log(`Installed prim skill plugin at ${dir}`);
@@ -52413,13 +52993,13 @@ function uninstallClaudePlugin(cwd, opts) {
52413
52993
  const dir = resolvePluginDir(cwd, opts.scope);
52414
52994
  if (dir === null) return 1;
52415
52995
  const { manifestPath, skillPath } = pluginPaths(dir);
52416
- if (!existsSync22(manifestPath) && !existsSync22(skillPath)) {
52996
+ if (!existsSync24(manifestPath) && !existsSync24(skillPath)) {
52417
52997
  console.log(`prim skill plugin not present at ${dir}`);
52418
52998
  return 0;
52419
52999
  }
52420
53000
  rmSync9(manifestPath, { force: true });
52421
53001
  rmSync9(skillPath, { force: true });
52422
- removeDirIfEmpty(join30(dir, ".claude-plugin"));
53002
+ removeDirIfEmpty(join32(dir, ".claude-plugin"));
52423
53003
  removeDirIfEmpty(dir);
52424
53004
  console.log(`Removed prim skill plugin from ${dir}`);
52425
53005
  return 0;
@@ -52428,7 +53008,7 @@ function statusClaudePlugin(cwd, opts) {
52428
53008
  const dir = resolvePluginDir(cwd, opts.scope);
52429
53009
  if (dir === null) return 1;
52430
53010
  const { skillPath } = pluginPaths(dir);
52431
- const installed = existsSync22(skillPath);
53011
+ const installed = existsSync24(skillPath);
52432
53012
  if (opts.json) {
52433
53013
  printJson({ installed, target: dir });
52434
53014
  return installed ? 0 : 1;
@@ -52442,7 +53022,7 @@ function statusClaudePlugin(cwd, opts) {
52442
53022
  }
52443
53023
 
52444
53024
  // src/commands/skill.ts
52445
- var __dirname5 = dirname17(fileURLToPath5(import.meta.url));
53025
+ var __dirname5 = dirname18(fileURLToPath5(import.meta.url));
52446
53026
  var SKILL_BEGIN = "<!-- BEGIN PRIM SKILL v1 -->";
52447
53027
  var SKILL_END = "<!-- END PRIM SKILL v1 -->";
52448
53028
  var CODEX_GUIDANCE_LIMIT_BYTES = 1024 * 1024;
@@ -52466,23 +53046,23 @@ var AGENT_TARGET = {
52466
53046
  var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
52467
53047
  var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
52468
53048
  function sha2563(content) {
52469
- return createHash11("sha256").update(content).digest("hex");
53049
+ return createHash12("sha256").update(content).digest("hex");
52470
53050
  }
52471
53051
  function cursorSkillDirectory(cwd, scope) {
52472
53052
  const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
52473
- return join31(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
53053
+ return join33(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
52474
53054
  }
52475
53055
  function cursorSkillPaths(cwd, scope) {
52476
53056
  const directory = cursorSkillDirectory(cwd, scope);
52477
53057
  return {
52478
53058
  directory,
52479
- skill: join31(directory, "SKILL.md"),
52480
- manifest: join31(directory, CURSOR_SKILL_MANIFEST)
53059
+ skill: join33(directory, "SKILL.md"),
53060
+ manifest: join33(directory, CURSOR_SKILL_MANIFEST)
52481
53061
  };
52482
53062
  }
52483
53063
  function readCursorSkillManifest(path9) {
52484
53064
  try {
52485
- const value = JSON.parse(readFileSync23(path9, "utf8"));
53065
+ const value = JSON.parse(readFileSync25(path9, "utf8"));
52486
53066
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
52487
53067
  const record3 = value;
52488
53068
  if (record3.version !== 1 || record3.owner !== CURSOR_SKILL_OWNER || typeof record3.contentSha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record3.contentSha256)) {
@@ -52496,7 +53076,7 @@ function readCursorSkillManifest(path9) {
52496
53076
  function cursorSkillStatus(cwd, scope) {
52497
53077
  const paths = cursorSkillPaths(cwd, scope);
52498
53078
  const manifest = readCursorSkillManifest(paths.manifest);
52499
- const content = existsSync23(paths.skill) ? readFileSync23(paths.skill, "utf8") : void 0;
53079
+ const content = existsSync25(paths.skill) ? readFileSync25(paths.skill, "utf8") : void 0;
52500
53080
  const owned = manifest !== void 0;
52501
53081
  const installed = owned && content !== void 0 && sha2563(content) === manifest.contentSha256;
52502
53082
  return {
@@ -52514,8 +53094,8 @@ function validCursorSkillScope(scope) {
52514
53094
  function installCursorSkill(cwd, opts) {
52515
53095
  const paths = cursorSkillPaths(cwd, opts.scope);
52516
53096
  const status = cursorSkillStatus(cwd, opts.scope);
52517
- const manifestExists = existsSync23(paths.manifest);
52518
- const skillExists = existsSync23(paths.skill);
53097
+ const manifestExists = existsSync25(paths.manifest);
53098
+ const skillExists = existsSync25(paths.skill);
52519
53099
  if (manifestExists && !status.owned || !manifestExists && skillExists || status.edited) {
52520
53100
  console.error(`Refusing to overwrite a foreign or edited Cursor skill at ${paths.skill}`);
52521
53101
  return 1;
@@ -52526,12 +53106,12 @@ function installCursorSkill(cwd, opts) {
52526
53106
  owner: CURSOR_SKILL_OWNER,
52527
53107
  contentSha256: sha2563(content)
52528
53108
  };
52529
- if (status.installed && readFileSync23(paths.skill, "utf8") === content) {
53109
+ if (status.installed && readFileSync25(paths.skill, "utf8") === content) {
52530
53110
  console.log(`No changes \u2014 Cursor skill already up to date at ${paths.skill}`);
52531
53111
  return 0;
52532
53112
  }
52533
53113
  if (opts.dryRun) {
52534
- const existing = skillExists ? readFileSync23(paths.skill, "utf8") : "";
53114
+ const existing = skillExists ? readFileSync25(paths.skill, "utf8") : "";
52535
53115
  process.stdout.write(createPatch(paths.skill, existing, content, "current", "proposed"));
52536
53116
  return 0;
52537
53117
  }
@@ -52552,34 +53132,34 @@ function uninstallCursorSkill(cwd, scope) {
52552
53132
  console.error(`Refusing to remove an edited Cursor skill at ${paths.skill}`);
52553
53133
  return 1;
52554
53134
  }
52555
- if (existsSync23(paths.skill)) unlinkSync8(paths.skill);
52556
- if (existsSync23(paths.manifest)) unlinkSync8(paths.manifest);
53135
+ if (existsSync25(paths.skill)) unlinkSync9(paths.skill);
53136
+ if (existsSync25(paths.manifest)) unlinkSync9(paths.manifest);
52557
53137
  try {
52558
- if (readdirSync9(paths.directory).length === 0) rmdirSync3(paths.directory);
53138
+ if (readdirSync11(paths.directory).length === 0) rmdirSync4(paths.directory);
52559
53139
  } catch {
52560
53140
  }
52561
53141
  console.log(`Removed Primitive-owned Cursor skill from ${paths.skill}`);
52562
53142
  return 0;
52563
53143
  }
52564
53144
  function userTargetFor(agent) {
52565
- if (agent === "claude") return join31(homedir11(), ".claude", "CLAUDE.md");
52566
- if (agent === "codex") return join31(homedir11(), ".codex", "AGENTS.md");
53145
+ if (agent === "claude") return join33(homedir11(), ".claude", "CLAUDE.md");
53146
+ if (agent === "codex") return join33(homedir11(), ".codex", "AGENTS.md");
52567
53147
  if (agent === "hermes") {
52568
- return join31(process.env.HERMES_HOME ?? join31(homedir11(), ".hermes"), ".hermes.md");
53148
+ return join33(process.env.HERMES_HOME ?? join33(homedir11(), ".hermes"), ".hermes.md");
52569
53149
  }
52570
53150
  return null;
52571
53151
  }
52572
53152
  function loadSkill() {
52573
53153
  let dir = __dirname5;
52574
- while (dir !== dirname17(dir)) {
52575
- const p = resolve9(dir, "SKILL.md");
52576
- if (existsSync23(p)) return readFileSync23(p, "utf-8");
52577
- dir = dirname17(dir);
53154
+ while (dir !== dirname18(dir)) {
53155
+ const p = resolve10(dir, "SKILL.md");
53156
+ if (existsSync25(p)) return readFileSync25(p, "utf-8");
53157
+ dir = dirname18(dir);
52578
53158
  }
52579
53159
  throw new Error("SKILL.md not found in package");
52580
53160
  }
52581
53161
  function detectTargets(cwd) {
52582
- return TARGET_CANDIDATES.filter((p) => existsSync23(resolve9(cwd, p)));
53162
+ return TARGET_CANDIDATES.filter((p) => existsSync25(resolve10(cwd, p)));
52583
53163
  }
52584
53164
  function detectNewline(content) {
52585
53165
  return content.includes("\r\n") ? "\r\n" : "\n";
@@ -52613,7 +53193,7 @@ function resolveTarget(cwd, opts) {
52613
53193
  console.error(`Unknown --scope "${opts.scope}" (expected user or project)`);
52614
53194
  return null;
52615
53195
  }
52616
- if (opts.target) return resolve9(cwd, opts.target);
53196
+ if (opts.target) return resolve10(cwd, opts.target);
52617
53197
  if (opts.scope === "user") {
52618
53198
  if (!opts.agent) {
52619
53199
  console.error("--scope user requires --agent (claude, codex, cursor, or hermes)");
@@ -52626,13 +53206,13 @@ function resolveTarget(cwd, opts) {
52626
53206
  }
52627
53207
  if (opts.agent) {
52628
53208
  const mapped = AGENT_TARGET[opts.agent];
52629
- if (typeof mapped === "string") return resolve9(cwd, mapped);
53209
+ if (typeof mapped === "string") return resolve10(cwd, mapped);
52630
53210
  console.error(`Unknown --agent "${opts.agent}" (expected claude, codex, cursor, or hermes)`);
52631
53211
  return null;
52632
53212
  }
52633
53213
  const matches = detectTargets(cwd);
52634
- if (matches.length === 0) return resolve9(cwd, DEFAULT_TARGET);
52635
- if (matches.length === 1) return resolve9(cwd, matches[0]);
53214
+ if (matches.length === 0) return resolve10(cwd, DEFAULT_TARGET);
53215
+ if (matches.length === 1) return resolve10(cwd, matches[0]);
52636
53216
  console.error("Multiple rules files detected. Use --target to disambiguate:");
52637
53217
  for (const m of matches) console.error(` ${m}`);
52638
53218
  return null;
@@ -52645,7 +53225,7 @@ function runInstall(cwd, opts) {
52645
53225
  }
52646
53226
  const target = resolveTarget(cwd, opts);
52647
53227
  if (target === null) return 1;
52648
- const existing = existsSync23(target) ? readFileSync23(target, "utf-8") : "";
53228
+ const existing = existsSync25(target) ? readFileSync25(target, "utf-8") : "";
52649
53229
  const eol = existing ? detectNewline(existing) : "\n";
52650
53230
  const block = composeBlock(loadSkill(), eol);
52651
53231
  const next = applyBlock(existing, block, eol);
@@ -52669,11 +53249,11 @@ function runUninstall(cwd, opts) {
52669
53249
  }
52670
53250
  const target = resolveTarget(cwd, opts);
52671
53251
  if (target === null) return 1;
52672
- if (!existsSync23(target)) {
53252
+ if (!existsSync25(target)) {
52673
53253
  console.log(`Skill block not present at ${target}`);
52674
53254
  return 0;
52675
53255
  }
52676
- const existing = readFileSync23(target, "utf-8");
53256
+ const existing = readFileSync25(target, "utf-8");
52677
53257
  const next = removeBlock(existing);
52678
53258
  if (next === null) {
52679
53259
  console.log(`Skill block not present at ${target}`);
@@ -52697,10 +53277,10 @@ function runStatus(cwd, opts) {
52697
53277
  }
52698
53278
  const target = resolveTarget(cwd, opts);
52699
53279
  if (target === null) return 1;
52700
- const fileExists = existsSync23(target);
53280
+ const fileExists = existsSync25(target);
52701
53281
  let installed = false;
52702
53282
  if (fileExists) {
52703
- const content = readFileSync23(target, "utf-8");
53283
+ const content = readFileSync25(target, "utf-8");
52704
53284
  installed = content.includes(SKILL_BEGIN) && content.includes(SKILL_END);
52705
53285
  }
52706
53286
  if (opts.json) {
@@ -52737,23 +53317,23 @@ function registerSkillCommands(program3) {
52737
53317
  }
52738
53318
 
52739
53319
  // src/commands/statusline.ts
52740
- import { readFileSync as readFileSync24 } from "fs";
52741
- import { dirname as dirname18, resolve as resolve10 } from "path";
53320
+ import { readFileSync as readFileSync26 } from "fs";
53321
+ import { dirname as dirname19, resolve as resolve11 } from "path";
52742
53322
  import { fileURLToPath as fileURLToPath6 } from "url";
52743
53323
  var STATUSLINE_TIMEOUT_MS = 200;
52744
53324
  function readPackageVersion() {
52745
53325
  try {
52746
- const here = dirname18(fileURLToPath6(import.meta.url));
53326
+ const here = dirname19(fileURLToPath6(import.meta.url));
52747
53327
  const candidates = [
52748
53328
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
52749
53329
  // Keep resolving it while those legacy launchers transition to schema v3.
52750
- resolve10(here, "manifest.json"),
52751
- resolve10(here, "../../package.json"),
52752
- resolve10(here, "../package.json")
53330
+ resolve11(here, "manifest.json"),
53331
+ resolve11(here, "../../package.json"),
53332
+ resolve11(here, "../package.json")
52753
53333
  ];
52754
53334
  for (const path9 of candidates) {
52755
53335
  try {
52756
- const pkg2 = JSON.parse(readFileSync24(path9, "utf-8"));
53336
+ const pkg2 = JSON.parse(readFileSync26(path9, "utf-8"));
52757
53337
  if (pkg2.version) {
52758
53338
  return pkg2.version;
52759
53339
  }
@@ -53066,10 +53646,11 @@ var GUIDANCE_PASSIVE = {
53066
53646
  hermes: "Otherwise, once you approve the prim hooks when Hermes prompts, Primitive passively captures decisions in the background while you work.",
53067
53647
  generic: "Otherwise, once your agent's prim hooks are active, Primitive passively captures decisions in the background while you work."
53068
53648
  };
53069
- function seedGuidanceFor(agent) {
53649
+ var EXCLUDED_CAPTURE = "Passive capture is excluded for this onboarding session. Start a new session for normal capture; explicitly approved real Decisions can still be created.";
53650
+ function seedGuidanceFor(agent, captureExcluded = false) {
53070
53651
  return [
53071
53652
  "You can tell your agent to add any decision to your Primitive decision graph at any time.",
53072
- GUIDANCE_PASSIVE[agent ?? "generic"],
53653
+ captureExcluded ? EXCLUDED_CAPTURE : GUIDANCE_PASSIVE[agent ?? "generic"],
53073
53654
  "To capture decisions in other repositories, enable Primitive there too: run `prim enable` in each one."
53074
53655
  ].join(" ");
53075
53656
  }
@@ -53084,7 +53665,7 @@ function welcomeStateFromRecent(result) {
53084
53665
  }
53085
53666
  return { org: "active", recent };
53086
53667
  }
53087
- function formatWelcome(state, agent) {
53668
+ function formatWelcome(state, agent, captureExcluded = false) {
53088
53669
  const cmd = (command, desc) => ` ${dim(command.padEnd(CMD_GUTTER))}${desc}`;
53089
53670
  const bullet = (text) => ` ${color("\u2022", "green")} ${text}`;
53090
53671
  const asBullet = ([first, ...rest]) => [
@@ -53099,7 +53680,7 @@ function formatWelcome(state, agent) {
53099
53680
  "shared graph \u2014 automatically, as you work.",
53100
53681
  "",
53101
53682
  bold("How it works"),
53102
- ...asBullet(CAPTURE_LINES[copyKey]),
53683
+ ...asBullet(captureExcluded ? [EXCLUDED_CAPTURE] : CAPTURE_LINES[copyKey]),
53103
53684
  bullet("Conflict Gates can warn, ask, or block edits that conflict"),
53104
53685
  " with a load-bearing decision when Enforcement is enabled.",
53105
53686
  bullet('Occasional yes/no prompts confirm the "why" behind a decision \u2014'),
@@ -53129,7 +53710,7 @@ function formatWelcome(state, agent) {
53129
53710
  "",
53130
53711
  bold("From here on"),
53131
53712
  bullet("Tell your agent to add any decision to Primitive, any time."),
53132
- ...asBullet(PASSIVE_LINES[copyKey]),
53713
+ ...asBullet(captureExcluded ? [EXCLUDED_CAPTURE] : PASSIVE_LINES[copyKey]),
53133
53714
  bullet("Run `prim enable` in each additional repo you want captured.")
53134
53715
  ];
53135
53716
  } else {
@@ -53142,7 +53723,7 @@ function formatWelcome(state, agent) {
53142
53723
  }
53143
53724
  return [...head, ...body, "", dim("App: https://app.getprimitive.ai")].join("\n");
53144
53725
  }
53145
- function welcomeJson(state, agent) {
53726
+ function welcomeJson(state, agent, captureExcluded = false) {
53146
53727
  if (state.org === "active") {
53147
53728
  return { welcomed: true, org: "active", recent: state.recent };
53148
53729
  }
@@ -53150,21 +53731,30 @@ function welcomeJson(state, agent) {
53150
53731
  return {
53151
53732
  welcomed: true,
53152
53733
  org: "seed",
53153
- seedGuidance: seedGuidanceFor(agent),
53734
+ seedGuidance: seedGuidanceFor(agent, captureExcluded),
53154
53735
  recent: state.recent
53155
53736
  };
53156
53737
  }
53157
53738
  return { welcomed: true, org: "unknown" };
53158
53739
  }
53159
53740
  function registerWelcomeCommand(program3, deps = { getClient }) {
53160
- 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").action(async (options) => {
53161
- const agent = resolveWelcomeAgent(options.agent, process.env);
53162
- const result = await fetchRecent({ limit: RECENT_LIMIT }, deps);
53163
- const state = welcomeStateFromRecent(result);
53164
- process.stderr.write(`${formatWelcome(state, agent)}
53741
+ 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 local tour finish before proposing real Decisions").option("--capture-excluded", "explain the demo session's passive capture exclusion").action(
53742
+ async (options) => {
53743
+ const agent = resolveWelcomeAgent(options.agent, process.env);
53744
+ if (options.deferSeeding) {
53745
+ process.stderr.write(
53746
+ "Welcome to Primitive. Setup is complete; the optional simulated tour comes before real Decision seeding.\n"
53747
+ );
53748
+ printJson({ welcomed: true, onboarding: "demo", seedingDeferred: true });
53749
+ return;
53750
+ }
53751
+ const result = await fetchRecent({ limit: RECENT_LIMIT }, deps);
53752
+ const state = welcomeStateFromRecent(result);
53753
+ process.stderr.write(`${formatWelcome(state, agent, options.captureExcluded)}
53165
53754
  `);
53166
- printJson(welcomeJson(state, agent));
53167
- });
53755
+ printJson(welcomeJson(state, agent, options.captureExcluded));
53756
+ }
53757
+ );
53168
53758
  }
53169
53759
 
53170
53760
  // src/daemon/self-heal.ts
@@ -53297,13 +53887,13 @@ function healDaemonDrift(options = {}) {
53297
53887
 
53298
53888
  // src/lib/background-flush.ts
53299
53889
  import { spawn as spawn5 } from "child_process";
53300
- import { readFileSync as readFileSync25 } from "fs";
53890
+ import { readFileSync as readFileSync27 } from "fs";
53301
53891
 
53302
53892
  // src/daemon/health.ts
53303
- import { chmodSync as chmodSync8, existsSync as existsSync24, mkdirSync as mkdirSync16, renameSync as renameSync7, writeFileSync as writeFileSync11 } from "fs";
53304
- import { dirname as dirname19, join as join32 } from "path";
53893
+ import { chmodSync as chmodSync8, existsSync as existsSync26, mkdirSync as mkdirSync16, renameSync as renameSync7, writeFileSync as writeFileSync11 } from "fs";
53894
+ import { dirname as dirname20, join as join34 } from "path";
53305
53895
  var HEARTBEAT_FRESH_MS = 9e4;
53306
- var DAEMON_HEALTH_PATH = join32(primConfigDirectory(), "daemon-health.json");
53896
+ var DAEMON_HEALTH_PATH = join34(primConfigDirectory(), "daemon-health.json");
53307
53897
 
53308
53898
  // src/lib/background-flush.ts
53309
53899
  function record2(value) {
@@ -53314,7 +53904,7 @@ function daemonOwnsDrain(options = {}) {
53314
53904
  const expectedVersion = options.expectedVersion === void 0 ? packageVersion() : options.expectedVersion;
53315
53905
  if (!expectedVersion) return false;
53316
53906
  const health = record2(
53317
- JSON.parse(readFileSync25(options.healthPath ?? DAEMON_HEALTH_PATH, "utf8"))
53907
+ JSON.parse(readFileSync27(options.healthPath ?? DAEMON_HEALTH_PATH, "utf8"))
53318
53908
  );
53319
53909
  const heartbeat = record2(health?.heartbeat);
53320
53910
  const ingestion = record2(health?.ingestion);
@@ -53422,7 +54012,7 @@ function runStartupBackgroundWork(argv, env4, work) {
53422
54012
  const args = commandArguments(argv);
53423
54013
  const [command, subcommand] = args;
53424
54014
  const uninstall = command === "uninstall" || env4[UNINSTALL_ORCHESTRATOR_ENV] === "1";
53425
- if (uninstall) return;
54015
+ if (uninstall || command === "demo") return;
53426
54016
  work.notify();
53427
54017
  const setupDaemonDrains = command === "setup" && !args.includes("--no-daemon") || env4[SETUP_DAEMON_DRAINS_ENV] === "1";
53428
54018
  if (!setupDaemonDrains && (command !== "moves" || subcommand !== "flush")) work.flush();
@@ -53430,8 +54020,8 @@ function runStartupBackgroundWork(argv, env4, work) {
53430
54020
  }
53431
54021
 
53432
54022
  // src/index.ts
53433
- var __dirname6 = dirname20(fileURLToPath7(import.meta.url));
53434
- var pkg = JSON.parse(readFileSync26(resolve11(__dirname6, "../package.json"), "utf-8"));
54023
+ var __dirname6 = dirname21(fileURLToPath7(import.meta.url));
54024
+ var pkg = JSON.parse(readFileSync28(resolve12(__dirname6, "../package.json"), "utf-8"));
53435
54025
  runStartupBackgroundWork(process.argv.slice(2), process.env, {
53436
54026
  notify: () => updateNotifier({ pkg }).notify(),
53437
54027
  flush: () => startBackgroundFlush(),
@@ -53449,6 +54039,7 @@ registerSkillCommands(program2);
53449
54039
  registerMovesCommands(program2);
53450
54040
  registerSessionCommands(program2);
53451
54041
  registerDecisionsCommands(program2);
54042
+ registerDemoCommands(program2);
53452
54043
  registerClaudeCommands(program2);
53453
54044
  registerCodexCommands(program2);
53454
54045
  registerCursorCommands(program2);