@primitive.ai/prim 0.1.0-alpha.115 → 0.1.0-alpha.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +43 -0
  2. package/SKILL.md +5 -3
  3. package/dist/{chunk-IZXLH3R5.js → chunk-3TIKBQHV.js} +2584 -821
  4. package/dist/{chunk-NH3VC7YO.js → chunk-4OEJ2ONG.js} +1 -1
  5. package/dist/{chunk-DWAXFXDG.js → chunk-4SN5BCIG.js} +1 -1
  6. package/dist/{chunk-3KKEV7VI.js → chunk-6IRAGUYK.js} +1 -1
  7. package/dist/chunk-CXMLAWC2.js +96 -0
  8. package/dist/chunk-D3ZDZZYS.js +449 -0
  9. package/dist/{chunk-RUUSUF43.js → chunk-I3J344DF.js} +231 -94
  10. package/dist/{chunk-7DVEH7FO.js → chunk-JKJ22ONL.js} +1 -1
  11. package/dist/{chunk-PO5QAYD7.js → chunk-JKO6PZWQ.js} +119 -24
  12. package/dist/{chunk-BXLH4LDU.js → chunk-LEUZDTNT.js} +1 -1
  13. package/dist/{chunk-PJW6JZMH.js → chunk-LLKJAET2.js} +1 -1
  14. package/dist/{chunk-IMYELJIV.js → chunk-RLBASQJD.js} +3 -3
  15. package/dist/{chunk-RTULPLS7.js → chunk-S55JKCHQ.js} +1 -1
  16. package/dist/daemon/server.js +2583 -822
  17. package/dist/hook-runtime/daemon/server.js +2583 -822
  18. package/dist/hook-runtime/hooks/post-commit.js +2581 -820
  19. package/dist/hook-runtime/hooks/post-rewrite.js +2581 -820
  20. package/dist/hook-runtime/hooks/post-tool-use.js +2689 -921
  21. package/dist/hook-runtime/hooks/pre-tool-use.js +2922 -985
  22. package/dist/hook-runtime/hooks/prim-hook.js +2682 -914
  23. package/dist/hook-runtime/hooks/session-end.js +19 -12
  24. package/dist/hook-runtime/hooks/session-start.js +2828 -1060
  25. package/dist/hook-runtime/index.js +22900 -12209
  26. package/dist/hooks/post-commit.js +3 -3
  27. package/dist/hooks/post-rewrite.js +3 -3
  28. package/dist/hooks/post-tool-use.js +11 -11
  29. package/dist/hooks/pre-tool-use.js +78 -316
  30. package/dist/hooks/prim-hook.js +10 -10
  31. package/dist/hooks/session-end.js +2 -2
  32. package/dist/hooks/session-start.js +6 -6
  33. package/dist/index.js +66 -15
  34. package/package.json +4 -1
  35. package/dist/chunk-JDIAPBY7.js +0 -233
@@ -7,7 +7,7 @@ import {
7
7
  kickDaemonEnsure,
8
8
  refreshClaudePlugins,
9
9
  warmBinCache
10
- } from "../chunk-7DVEH7FO.js";
10
+ } from "../chunk-JKJ22ONL.js";
11
11
  import {
12
12
  buildHookOutput,
13
13
  handoffHookOutput
@@ -28,11 +28,11 @@ import {
28
28
  } from "../chunk-EZXEWFDG.js";
29
29
  import {
30
30
  prepareCodexContext
31
- } from "../chunk-PJW6JZMH.js";
32
- import "../chunk-DWAXFXDG.js";
31
+ } from "../chunk-LLKJAET2.js";
32
+ import "../chunk-4SN5BCIG.js";
33
33
  import {
34
34
  fetchAndCacheCollectScope
35
- } from "../chunk-IZXLH3R5.js";
35
+ } from "../chunk-3TIKBQHV.js";
36
36
  import {
37
37
  getSiteUrl,
38
38
  isSessionEnded
@@ -42,10 +42,10 @@ import {
42
42
  parseAgent,
43
43
  readHookStdin,
44
44
  shouldSuppressImportedCursorHandler
45
- } from "../chunk-NH3VC7YO.js";
45
+ } from "../chunk-4OEJ2ONG.js";
46
46
  import {
47
47
  MANAGED_GIT_HOOK_NAMES
48
- } from "../chunk-PO5QAYD7.js";
48
+ } from "../chunk-JKO6PZWQ.js";
49
49
  import {
50
50
  daemonRequest
51
51
  } from "../chunk-J5HBSRAV.js";
package/dist/index.js CHANGED
@@ -19,15 +19,20 @@ import {
19
19
  resolveRepositoryBinding,
20
20
  uninstallGitHookAtPath,
21
21
  uninstallProjectGitHook
22
- } from "./chunk-7DVEH7FO.js";
22
+ } from "./chunk-JKJ22ONL.js";
23
23
  import {
24
24
  requireDurableIngestAcknowledgement
25
- } from "./chunk-BXLH4LDU.js";
25
+ } from "./chunk-LEUZDTNT.js";
26
26
  import {
27
27
  checkAffectedDecisions,
28
28
  daemonOrDirectGet,
29
29
  formatDecisionsWarning
30
30
  } from "./chunk-NEQI2VLM.js";
31
+ import {
32
+ hasCompleteCoverage,
33
+ requestPreflight,
34
+ waitForPreflight
35
+ } from "./chunk-D3ZDZZYS.js";
31
36
  import {
32
37
  fetchFeedbackCapability
33
38
  } from "./chunk-FTW4ZCBA.js";
@@ -75,7 +80,7 @@ import {
75
80
  readDemoJson,
76
81
  readRun,
77
82
  saveRun
78
- } from "./chunk-JDIAPBY7.js";
83
+ } from "./chunk-I3J344DF.js";
79
84
  import {
80
85
  MS_PER_SECOND,
81
86
  deliveryBacklogState,
@@ -84,7 +89,8 @@ import {
84
89
  formatStatusline,
85
90
  formatTeammates,
86
91
  repositoryBindingDiagnosticLabel
87
- } from "./chunk-DWAXFXDG.js";
92
+ } from "./chunk-4SN5BCIG.js";
93
+ import "./chunk-6IRAGUYK.js";
88
94
  import {
89
95
  bold,
90
96
  boundedHealthError,
@@ -109,7 +115,7 @@ import {
109
115
  isMoveIngestRequest,
110
116
  isReconcileResolutionResponse,
111
117
  stripAnsi
112
- } from "./chunk-IZXLH3R5.js";
118
+ } from "./chunk-3TIKBQHV.js";
113
119
  import {
114
120
  CliManagementResponseError,
115
121
  HttpError,
@@ -135,6 +141,7 @@ import {
135
141
  ensureRegistration,
136
142
  entryHasCommand,
137
143
  hookRuntimePaths,
144
+ inspectFailureProtection,
138
145
  inspectGitHookEntrypoint,
139
146
  inspectHookRuntime,
140
147
  inspectHookRuntimeResolutions,
@@ -148,10 +155,11 @@ import {
148
155
  registerClaudeCommands,
149
156
  registerCursorCommands,
150
157
  removeHookRuntime,
158
+ reportFailureProtection,
151
159
  stableNodePath,
152
160
  stageHookRuntime,
153
161
  stripCommand
154
- } from "./chunk-PO5QAYD7.js";
162
+ } from "./chunk-JKO6PZWQ.js";
155
163
  import {
156
164
  daemonIsLive,
157
165
  daemonRequest
@@ -2314,7 +2322,7 @@ function inspectHookRuntimeResolutions3() {
2314
2322
  ];
2315
2323
  }
2316
2324
  function entryMatchesRegistration(owned, registration) {
2317
- return owned.event === registration.event && owned.entry.matcher === registration.matcher && owned.entry.hooks?.length === 1 && owned.entry.hooks[0].type === "command" && owned.entry.hooks[0].command === registration.command;
2325
+ return owned.event === registration.event && owned.entry.matcher === registration.matcher && owned.entry.hooks?.length === 1 && owned.entry.hooks[0].type === "command" && owned.entry.hooks[0].command === registration.command && owned.entry.hooks[0].timeout === registration.timeout && owned.entry.hooks[0].onFailure === registration.onFailure && (registration.bin !== GATE_BIN || owned.entry.hooks[0].async !== true);
2318
2326
  }
2319
2327
  function hasCompleteHookRegistration(settings) {
2320
2328
  const owned = ownedRegistrationEntries(settings);
@@ -2397,6 +2405,7 @@ function registerCodexCommands(program2) {
2397
2405
  ).option("--force", "Replace any drifted prim hook entries").action(async (opts) => {
2398
2406
  const scope = resolveScope(opts.scope);
2399
2407
  const result = performInstall(scope, opts.force ?? false);
2408
+ const failureProtection = reportFailureProtection("codex");
2400
2409
  if (result.changed) {
2401
2410
  console.error(`[prim] Codex integration installed (${scope} scope) at ${result.path}`);
2402
2411
  } else {
@@ -2405,7 +2414,7 @@ function registerCodexCommands(program2) {
2405
2414
  console.error(TRUST_NOTICE);
2406
2415
  const host = await inspectCodexHost(Boolean(process.env.CODEX_THREAD_ID));
2407
2416
  console.error(`[prim] ${codexHostGuidance(host)}`);
2408
- console.log(JSON.stringify({ ...result, host }, null, JSON_INDENT));
2417
+ console.log(JSON.stringify({ ...result, host, failureProtection }, null, JSON_INDENT));
2409
2418
  });
2410
2419
  codex.command("refresh").description("Reload installed hooks in the calling Codex session without changing trust").action(async () => {
2411
2420
  const host = await inspectCodexHost(true);
@@ -2429,6 +2438,7 @@ function registerCodexCommands(program2) {
2429
2438
  });
2430
2439
  codex.command("status").description("Report whether each prim surface (gate, capture) is installed per scope").action(async () => {
2431
2440
  const result = performStatus3();
2441
+ const failureProtection = result.user.gate || result.project.gate ? reportFailureProtection("codex") : void 0;
2432
2442
  const host = await inspectCodexHost();
2433
2443
  const readiness = {
2434
2444
  configured: result.user.complete || result.project.complete,
@@ -2448,7 +2458,7 @@ ${line("project", result.project)}`);
2448
2458
  console.error(
2449
2459
  "[prim] Configuration is not proof of hook execution or capture. Use the pending tour\u2019s diagnosticAction to check isolation."
2450
2460
  );
2451
- console.log(JSON.stringify({ ...result, readiness }, null, JSON_INDENT));
2461
+ console.log(JSON.stringify({ ...result, readiness, failureProtection }, null, JSON_INDENT));
2452
2462
  });
2453
2463
  }
2454
2464
 
@@ -6347,6 +6357,28 @@ function locationScopeFromOptions(options) {
6347
6357
  }
6348
6358
  function registerDecisionsCommands(program2) {
6349
6359
  const decisions = program2.command("decisions").description("Inspect the project Decision Graph");
6360
+ const preflight = decisions.command("preflight").description("Inspect or resume a paused Decision check");
6361
+ preflight.command("status <checkId>").description("Show the current state without restarting work").action(async (checkId) => {
6362
+ const result = await requestPreflight({ protocolVersion: 4, operation: "status", checkId });
6363
+ printJson(result);
6364
+ console.error(`[prim] Decision check ${result.state}: ${terminalSafeLine(result.message)}`);
6365
+ if (!hasCompleteCoverage(result)) process.exitCode = EXIT_FAILURE2;
6366
+ });
6367
+ preflight.command("resume <checkId>").description("Resume evaluation and wait up to 240 seconds; then retry the original tool call").action(async (checkId) => {
6368
+ const result = await waitForPreflight(
6369
+ { protocolVersion: 4, operation: "resume", checkId },
6370
+ {
6371
+ onProgress: ({ evaluationCoverage: coverage }) => console.error(
6372
+ `[prim] Checking Decisions: ${coverage.evaluatedCount + coverage.bypassedCount}/${coverage.candidateCount}${coverage.discoveryComplete ? "" : "+"} covered.`
6373
+ )
6374
+ }
6375
+ );
6376
+ printJson(result);
6377
+ console.error(
6378
+ `[prim] Decision check ${result.state}: ${terminalSafeLine(result.message)}${hasCompleteCoverage(result) ? "; retry the original tool call" : "; operation remains paused"}`
6379
+ );
6380
+ if (!hasCompleteCoverage(result)) process.exitCode = EXIT_FAILURE2;
6381
+ });
6350
6382
  decisions.command("check").description("Look up active decisions scoped to file paths in the connected repository").requiredOption(
6351
6383
  "--files <files>",
6352
6384
  "Comma-separated repository-relative paths to check against the Decision Graph (repeatable)",
@@ -7565,7 +7597,7 @@ var CAPTURE_EVENTS = [
7565
7597
  "on_session_end",
7566
7598
  "subagent_stop"
7567
7599
  ];
7568
- var GATE_TIMEOUT_SECONDS = 10;
7600
+ var GATE_TIMEOUT_SECONDS = 300;
7569
7601
  var REGISTRATIONS = [
7570
7602
  ...CAPTURE_EVENTS.map((event) => ({ event, bin: CAPTURE_BIN2 })),
7571
7603
  { event: "pre_tool_call", matcher: EDIT_MATCHER, bin: GATE_BIN2, timeout: GATE_TIMEOUT_SECONDS },
@@ -7587,6 +7619,7 @@ function entryFor(reg) {
7587
7619
  if (reg.timeout !== void 0) {
7588
7620
  entry.timeout = reg.timeout;
7589
7621
  }
7622
+ if (reg.bin === GATE_BIN2) entry.fail_closed = true;
7590
7623
  return entry;
7591
7624
  }
7592
7625
  function stripBin(list, bin) {
@@ -7595,9 +7628,9 @@ function stripBin(list, bin) {
7595
7628
  function ensureReg(list, reg, force) {
7596
7629
  const entry = entryFor(reg);
7597
7630
  const present2 = list.some(
7598
- (e) => e.command === entry.command && (e.matcher ?? "") === (entry.matcher ?? "") && (e.timeout ?? null) === (entry.timeout ?? null)
7631
+ (e) => e.command === entry.command && (e.matcher ?? "") === (entry.matcher ?? "") && (e.timeout ?? null) === (entry.timeout ?? null) && e.fail_closed === entry.fail_closed
7599
7632
  );
7600
- if (present2 && !force) {
7633
+ if (present2 && !force && (reg.bin !== GATE_BIN2 || list.filter((e) => commandUsesBin(e.command, reg.bin)).length === 1)) {
7601
7634
  return list;
7602
7635
  }
7603
7636
  return [...stripBin(list, reg.bin), entry];
@@ -7664,7 +7697,7 @@ function inspectHookRuntimeResolutions4() {
7664
7697
  }
7665
7698
  function entryMatchesRegistration2(owned, registration) {
7666
7699
  const expected = entryFor(registration);
7667
- return owned.event === registration.event && owned.entry.command === expected.command && (owned.entry.matcher ?? "") === (expected.matcher ?? "") && (owned.entry.timeout ?? null) === (expected.timeout ?? null);
7700
+ return owned.event === registration.event && owned.entry.command === expected.command && (owned.entry.matcher ?? "") === (expected.matcher ?? "") && (owned.entry.timeout ?? null) === (expected.timeout ?? null) && owned.entry.fail_closed === expected.fail_closed;
7668
7701
  }
7669
7702
  function hasCompleteHookRegistration2(hooks) {
7670
7703
  const owned = ownedRegistrationEntries2(hooks);
@@ -8048,11 +8081,12 @@ function registerHermesCommands(program2) {
8048
8081
  force: opts.force ?? false,
8049
8082
  autoAccept: opts.autoAccept ?? false
8050
8083
  });
8084
+ const failureProtection = reportFailureProtection("hermes");
8051
8085
  console.error(
8052
8086
  result.changed ? `[prim] Hermes integration installed at ${result.path}` : `[prim] Hermes integration already present at ${result.path} (no changes)`
8053
8087
  );
8054
8088
  console.error(TRUST_NOTICE2);
8055
- console.log(JSON.stringify(result, null, JSON_INDENT2));
8089
+ console.log(JSON.stringify({ ...result, failureProtection }, null, JSON_INDENT2));
8056
8090
  });
8057
8091
  hermes.command("uninstall").description("Remove all prim hooks from Hermes's ~/.hermes/config.yaml").action(() => {
8058
8092
  const result = performUninstall2();
@@ -8063,11 +8097,12 @@ function registerHermesCommands(program2) {
8063
8097
  });
8064
8098
  hermes.command("status").description("Report whether each prim surface (gate, capture) is installed").action(() => {
8065
8099
  const result = performStatus4();
8100
+ const failureProtection = result.gate ? reportFailureProtection("hermes") : void 0;
8066
8101
  const mark = (b) => b ? "\u2713" : "\u2717";
8067
8102
  console.error(
8068
8103
  `[prim] hermes: gate ${mark(result.gate)} \xB7 capture ${mark(result.capture)} (${result.path})`
8069
8104
  );
8070
- console.log(JSON.stringify(result, null, JSON_INDENT2));
8105
+ console.log(JSON.stringify({ ...result, failureProtection }, null, JSON_INDENT2));
8071
8106
  });
8072
8107
  }
8073
8108
 
@@ -8848,6 +8883,21 @@ async function checkFeedbackCapability() {
8848
8883
  return { name: "feedback-api", status: "warn", detail: message.slice(0, 80) };
8849
8884
  }
8850
8885
  }
8886
+ function checkPreflightHosts() {
8887
+ const hosts = [];
8888
+ if (Object.values(performStatus()).some((scope) => scope.gate)) hosts.push("claude");
8889
+ if (Object.values(performStatus3()).some((scope) => scope.gate)) hosts.push("codex");
8890
+ if (Object.values(performStatus2()).some((scope) => scope.gate)) hosts.push("cursor");
8891
+ if (performStatus4().gate) hosts.push("hermes");
8892
+ return hosts.map((host) => {
8893
+ const protection = inspectFailureProtection(host);
8894
+ return {
8895
+ name: `${host} gate failure protection`,
8896
+ status: protection.status === "supported" ? "ok" : protection.status === "limited" ? "warn" : "fail",
8897
+ detail: protection.detail
8898
+ };
8899
+ });
8900
+ }
8851
8901
  async function independentChecks() {
8852
8902
  const backend = await checkBackend();
8853
8903
  const firing = inspectFiringHere();
@@ -8858,6 +8908,7 @@ async function independentChecks() {
8858
8908
  checkFeedbackHooks(),
8859
8909
  ...await checkAgentHooks(),
8860
8910
  checkHookRuntime(),
8911
+ ...checkPreflightHosts(),
8861
8912
  await checkRepositoryBinding(),
8862
8913
  checkManagedHook("pre-commit"),
8863
8914
  checkManagedHook("post-commit", firing),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@primitive.ai/prim",
3
- "version": "0.1.0-alpha.115",
3
+ "version": "0.1.0-alpha.116",
4
4
  "description": "CLI for Primitive's decision graph — passive decision capture, conflict gate, and team presence",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -68,6 +68,9 @@
68
68
  "typecheck": "tsc --noEmit",
69
69
  "check:reconcile-golden": "node scripts/check-reconcile-golden.mjs",
70
70
  "test": "vitest run",
71
+ "test:preflight-host": "node scripts/check-codex-preflight-host.mjs",
72
+ "test:preflight-host:claude": "node scripts/check-claude-preflight-host.mjs",
73
+ "test:preflight-v4": "node scripts/check-preflight-v4-e2e.mjs",
71
74
  "test:watch": "vitest",
72
75
  "test:coverage": "vitest run --coverage",
73
76
  "check:shell-targets-golden": "node scripts/check-shell-targets-golden.mjs"
@@ -1,233 +0,0 @@
1
- import {
2
- isDemoStatusResponse
3
- } from "./chunk-IZXLH3R5.js";
4
- import {
5
- inspectHookRuntime
6
- } from "./chunk-PO5QAYD7.js";
7
- import {
8
- atomicWriteFile,
9
- primConfigDirectory,
10
- withFileLock,
11
- withFileLockSync
12
- } from "./chunk-XG7S3LIL.js";
13
-
14
- // src/demo/state.ts
15
- import { createHash, randomUUID } from "crypto";
16
- import { existsSync, lstatSync, readFileSync, readdirSync } from "fs";
17
- import { join, resolve } from "path";
18
- 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;
19
- var demoDirectory = () => join(primConfigDirectory(), "demo");
20
- var runPath = (id) => {
21
- if (!RUN_ID.test(id)) throw new Error("invalid demo run ID");
22
- return join(demoDirectory(), "runs", `${id}.json`);
23
- };
24
- function readDemoJson(path) {
25
- const stat = lstatSync(path);
26
- if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
27
- return JSON.parse(readFileSync(path, "utf8"));
28
- }
29
- function saveDemoJson(path, value) {
30
- atomicWriteFile(path, `${JSON.stringify(value)}
31
- `, { mode: 384, ensureParent: true });
32
- }
33
- function readRun(id) {
34
- const run = readDemoJson(runPath(id));
35
- if (![1, 2].includes(run.version) || run.id !== id || ![
36
- "prepared",
37
- "proposal",
38
- "conflict",
39
- "prompt",
40
- "approved",
41
- "applied",
42
- "cleanup",
43
- "completed",
44
- "skipped"
45
- ].includes(run.stage) || run.needsStatus !== void 0 && typeof run.needsStatus !== "boolean" || run.server !== void 0 && !isDemoStatusResponse(run.server) || run.receipt !== void 0 && (!Number.isSafeInteger(run.receipt.revision) || run.receipt.revision < 0 || !/^[a-f0-9]{64}$/u.test(run.receipt.appliedDigest)) || typeof run.terminal !== "boolean" || !Array.isArray(run.launcher) || run.launcher.length !== 2 || run.launcher.some((value) => typeof value !== "string" || !value.startsWith("/")) || run.agent !== void 0 && !["claude_code", "codex", "cursor", "hermes"].includes(run.agent)) {
46
- throw new Error("invalid demo run state");
47
- }
48
- return run;
49
- }
50
- var saveRun = (run) => saveDemoJson(runPath(run.id), run);
51
- var lockRun = (id, action) => withFileLockSync(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
52
- function prepareRun(agent, terminal = false) {
53
- const run = {
54
- version: 2,
55
- id: randomUUID(),
56
- stage: "prepared",
57
- terminal,
58
- agent,
59
- preparationKey: preparationKey(agent),
60
- launcher: [process.execPath, resolve(process.argv[1])]
61
- };
62
- saveRun(run);
63
- return run;
64
- }
65
- function preparationKey(agent) {
66
- return agent === "codex" && process.env.CODEX_THREAD_ID ? sessionKey(agent, `${process.env.CODEX_THREAD_ID}\0${process.cwd()}`) : void 0;
67
- }
68
- var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
69
- function demoCommand(run, action, choice, reason) {
70
- return [
71
- ...run.launcher,
72
- "demo",
73
- action,
74
- run.id,
75
- ...choice === void 0 ? [] : ["--choice", choice],
76
- ...reason === void 0 ? [] : ["--reason", reason]
77
- ].map(quote).join(" ");
78
- }
79
- function demoWelcomeCommand(run) {
80
- return [
81
- process.execPath,
82
- resolve(process.argv[1]),
83
- "welcome",
84
- "--after-demo",
85
- ...run.agent ? ["--agent", run.agent === "claude_code" ? "claude" : run.agent] : [],
86
- ...run.binding ? ["--capture-excluded"] : []
87
- ].map(quote).join(" ");
88
- }
89
- function demoDiagnosticCommand(run) {
90
- return [process.execPath, resolve(process.argv[1]), "demo", "status", run.id].map(quote).join(" ");
91
- }
92
- function demoResumeCommand(run) {
93
- return [process.execPath, resolve(process.argv[1]), "demo", "resume", run.id].map(quote).join(" ");
94
- }
95
- function onboardingFinished() {
96
- const path = join(demoDirectory(), "onboarding.json");
97
- if (!existsSync(path)) return false;
98
- const value = readDemoJson(path);
99
- if (value.outcome !== "completed" && value.outcome !== "skipped") {
100
- throw new Error("invalid local onboarding outcome");
101
- }
102
- return true;
103
- }
104
- function finishOnboarding(outcome) {
105
- saveDemoJson(join(demoDirectory(), "onboarding.json"), { outcome });
106
- }
107
- function pendingRuns() {
108
- const path = join(demoDirectory(), "runs");
109
- if (!existsSync(path)) return [];
110
- return readdirSync(path).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));
111
- }
112
- function sessionKey(agent, session) {
113
- return createHash("sha256").update(`${agent}\0${session}`).digest("hex");
114
- }
115
- function exclusionPath(key) {
116
- if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
117
- return join(demoDirectory(), "excluded-sessions", `${key}.json`);
118
- }
119
- function sessionExcluded(agent, session) {
120
- if (typeof session !== "string" || !session) return false;
121
- const path = exclusionPath(sessionKey(agent, session));
122
- if (!existsSync(path)) return false;
123
- const record = readDemoJson(path);
124
- if (typeof record.runId !== "string" || !RUN_ID.test(record.runId)) {
125
- throw new Error("invalid demo capture exclusion");
126
- }
127
- return true;
128
- }
129
- var lockRunAsync = (id, action) => withFileLock(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
130
- function demoArgv(command) {
131
- const result = [];
132
- let i = 0;
133
- while (i < command.length) {
134
- if (command[i++] !== "'") return;
135
- let value = "";
136
- let closed = false;
137
- while (i < command.length) {
138
- if (command.slice(i, i + 4) === "'\\''") {
139
- value += "'";
140
- i += 4;
141
- } else if (command[i] === "'") {
142
- i++;
143
- closed = true;
144
- break;
145
- } else {
146
- value += command[i++];
147
- }
148
- }
149
- if (!closed) return;
150
- result.push(value);
151
- if (i === command.length) return result;
152
- if (command[i++] !== " " || i === command.length) return;
153
- }
154
- }
155
-
156
- // src/demo/diagnostics.ts
157
- import { existsSync as existsSync2 } from "fs";
158
- import { join as join2 } from "path";
159
- var observationPath = (id) => join2(demoDirectory(), "observations", `${id}.json`);
160
- function observeRun(id, observation) {
161
- try {
162
- saveDemoJson(observationPath(id), observation);
163
- } catch {
164
- process.stderr.write(
165
- "[prim] demo isolation diagnostic could not be saved; check access to Primitive's configuration directory.\n"
166
- );
167
- }
168
- }
169
- function isolationDiagnostics(run) {
170
- let observation;
171
- let observationError;
172
- try {
173
- if (existsSync2(observationPath(run.id))) {
174
- const value = readDemoJson(observationPath(run.id));
175
- if (!value || !Number.isFinite(value.at) || !["claude_code", "codex", "cursor", "hermes"].includes(value.agent ?? "") || ![
176
- "acknowledged",
177
- "tool-mismatch",
178
- "command-mismatch",
179
- "session-mismatch",
180
- "session-missing",
181
- "write-failed"
182
- ].includes(value.result ?? "") || value.runtimeVersion !== void 0 && !/^[a-zA-Z0-9.+-]{1,80}$/u.test(value.runtimeVersion) || value.session !== void 0 && !/^[a-f0-9]{64}$/u.test(value.session) || value.errorCode !== void 0 && !/^[A-Z0-9_]{1,32}$/u.test(value.errorCode))
183
- throw new Error("invalid demo observation");
184
- observation = value;
185
- }
186
- } catch {
187
- observationError = "unreadable";
188
- }
189
- const expected = run.agent === "codex" && process.env.CODEX_THREAD_ID ? sessionKey(run.agent, process.env.CODEX_THREAD_ID) : void 0;
190
- return {
191
- runtime: inspectHookRuntime(),
192
- expectedEvent: "PreToolUse",
193
- expectedTool: run.agent === "cursor" ? "Shell" : run.agent === "hermes" ? "terminal" : "Bash",
194
- hookObservation: observation ? {
195
- at: observation.at,
196
- agent: observation.agent,
197
- runtimeVersion: observation.runtimeVersion ?? "unknown",
198
- result: observation.result,
199
- ageMs: Math.max(0, Date.now() - observation.at),
200
- sessionMatches: expected ? observation.session === expected : "unknown",
201
- ...observation.errorCode ? { errorCode: observation.errorCode } : {}
202
- } : null,
203
- ...observationError ? { observationError } : {},
204
- trust: "unknown",
205
- capture: run.binding ? "excluded-for-bound-session" : "not-verified"
206
- };
207
- }
208
-
209
- export {
210
- RUN_ID,
211
- runPath,
212
- readDemoJson,
213
- saveDemoJson,
214
- readRun,
215
- saveRun,
216
- lockRun,
217
- prepareRun,
218
- preparationKey,
219
- demoCommand,
220
- demoWelcomeCommand,
221
- demoDiagnosticCommand,
222
- demoResumeCommand,
223
- onboardingFinished,
224
- finishOnboarding,
225
- pendingRuns,
226
- sessionKey,
227
- exclusionPath,
228
- sessionExcluded,
229
- lockRunAsync,
230
- demoArgv,
231
- observeRun,
232
- isolationDiagnostics
233
- };