@primitive.ai/prim 0.1.0-alpha.108 → 0.1.0-alpha.109

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.
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  resolveRepositoryBinding,
20
20
  uninstallGitHookAtPath,
21
21
  uninstallProjectGitHook
22
- } from "./chunk-2EKPBZNA.js";
22
+ } from "./chunk-IQZA65NV.js";
23
23
  import {
24
24
  requireDurableIngestAcknowledgement
25
25
  } from "./chunk-EQYIPUFX.js";
@@ -2114,8 +2114,128 @@ function registerActivationCommands(program2) {
2114
2114
  }
2115
2115
 
2116
2116
  // src/commands/codex-install.ts
2117
+ import { homedir as homedir3 } from "os";
2118
+ import { join as join3 } from "path";
2119
+
2120
+ // src/lib/codex-host.ts
2121
+ import { lstatSync as lstatSync2, realpathSync } from "fs";
2122
+ import { connect } from "net";
2117
2123
  import { homedir as homedir2 } from "os";
2118
- import { join as join2 } from "path";
2124
+ import { isAbsolute, join as join2 } from "path";
2125
+ import WebSocket from "ws";
2126
+ var TIMEOUT_MS = 3e3;
2127
+ var MAX_RESPONSE_BYTES = 1024 * 1024;
2128
+ var BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use", "prim-session-start"];
2129
+ async function inspectCodexHost(reload = false) {
2130
+ const unavailable = (reason) => ({
2131
+ connection: "unavailable",
2132
+ trust: "unknown",
2133
+ reload: reload ? "unavailable" : "not-requested",
2134
+ reason
2135
+ });
2136
+ const root = process.env.CODEX_HOME ?? join2(homedir2(), ".codex");
2137
+ if (!isAbsolute(root)) return unavailable("invalid-codex-home");
2138
+ let socketPath = join2(root, "app-server-control", "app-server-control.sock");
2139
+ try {
2140
+ const alias = lstatSync2(socketPath);
2141
+ if (process.getuid && alias.uid !== process.getuid()) return unavailable("unsafe-host-socket");
2142
+ socketPath = realpathSync(socketPath);
2143
+ const stat = lstatSync2(socketPath);
2144
+ if (!stat.isSocket() || process.getuid && stat.uid !== process.getuid())
2145
+ return unavailable("unsafe-host-socket");
2146
+ } catch {
2147
+ return unavailable("host-socket-unavailable");
2148
+ }
2149
+ return new Promise((resolve6) => {
2150
+ let finished = false;
2151
+ let refreshed = false;
2152
+ let requestId = 0;
2153
+ let method = "initialize";
2154
+ const socket = new WebSocket("ws://localhost/", {
2155
+ createConnection: () => connect(socketPath),
2156
+ handshakeTimeout: TIMEOUT_MS,
2157
+ maxPayload: MAX_RESPONSE_BYTES,
2158
+ perMessageDeflate: false
2159
+ });
2160
+ const finish = (value) => {
2161
+ if (finished) return;
2162
+ finished = true;
2163
+ clearTimeout(timer);
2164
+ socket.terminate();
2165
+ resolve6(value);
2166
+ };
2167
+ const fail = (reason) => finish({ ...unavailable(reason), ...refreshed ? { reload: "refreshed" } : {} });
2168
+ const timer = setTimeout(() => fail("host-timeout"), TIMEOUT_MS);
2169
+ const request = (next, params) => {
2170
+ method = next;
2171
+ socket.send(JSON.stringify({ id: ++requestId, method, params }));
2172
+ };
2173
+ const listHooks = () => request("hooks/list", { cwds: [process.cwd()] });
2174
+ socket.on("error", () => fail("host-connection-failed"));
2175
+ socket.on("close", () => fail("host-disconnected"));
2176
+ socket.on("open", () => {
2177
+ request("initialize", {
2178
+ clientInfo: { name: "primitive-hooks", version: "1" },
2179
+ capabilities: { experimentalApi: true }
2180
+ });
2181
+ });
2182
+ socket.on("message", (raw) => {
2183
+ try {
2184
+ const message = JSON.parse(raw.toString());
2185
+ if (message.id !== requestId) return;
2186
+ if (message.error || !message.result) return fail("host-request-failed");
2187
+ const result = message.result;
2188
+ if (method === "initialize") {
2189
+ socket.send(JSON.stringify({ method: "initialized" }));
2190
+ if (reload) request("thread/loaded/list", {});
2191
+ else listHooks();
2192
+ } else if (method === "thread/loaded/list") {
2193
+ const session = process.env.CODEX_THREAD_ID;
2194
+ if (!session || !Array.isArray(result.data) || !result.data.includes(session))
2195
+ return fail("calling-session-not-loaded");
2196
+ request("config/batchWrite", { edits: [], reloadUserConfig: true });
2197
+ } else if (method === "config/batchWrite") {
2198
+ refreshed = true;
2199
+ listHooks();
2200
+ } else if (method === "hooks/list") {
2201
+ const entry = result.data?.find((item) => item.cwd === process.cwd());
2202
+ if (!entry || !Array.isArray(entry.hooks) || entry.errors?.length)
2203
+ return fail("host-hook-catalog-unavailable");
2204
+ const owned = entry.hooks.filter(
2205
+ (hook) => typeof hook.command === "string" && hookCommandResolutions([hook.command], BINS).length > 0
2206
+ );
2207
+ const trust = owned.length === 0 ? "unknown" : owned.some((hook) => hook.enabled !== true) ? "disabled" : owned.some(
2208
+ (hook) => ["untrusted", "modified"].includes(hook.trustStatus ?? "")
2209
+ ) ? "review-required" : owned.every(
2210
+ (hook) => ["trusted", "managed"].includes(hook.trustStatus ?? "")
2211
+ ) ? "trusted" : "unknown";
2212
+ finish({
2213
+ connection: "available",
2214
+ trust,
2215
+ reload: refreshed ? "refreshed" : "not-requested"
2216
+ });
2217
+ }
2218
+ } catch {
2219
+ fail("invalid-host-response");
2220
+ }
2221
+ });
2222
+ });
2223
+ }
2224
+ function codexHostGuidance(host) {
2225
+ if (host.trust === "review-required")
2226
+ return "Open /hooks in Codex and review the Primitive hooks marked for review, then resume this tour.";
2227
+ if (host.trust === "disabled")
2228
+ return "Primitive hooks are disabled in Codex. Open /hooks to enable them if intended, then resume this tour.";
2229
+ if (host.reload === "refreshed" && host.trust === "trusted")
2230
+ return "Codex reloaded its trusted Primitive hooks. Resume this tour; its next real PreToolUse event must still verify isolation.";
2231
+ if (host.reload === "unavailable")
2232
+ return "The running Codex session could not be refreshed. Exit and resume this same Codex session to load the installed hooks; review them only if Codex prompts. Then resume this tour, without rerunning setup.";
2233
+ if (host.trust === "trusted")
2234
+ return "Codex reports Primitive hooks trusted. Run prim codex refresh in this same agent session, then resume this tour. Do not ask for trust again.";
2235
+ return "Codex hook readiness is unknown. Inspect /hooks for errors or a review request. If already enabled and trusted, refresh the running session before resuming this tour.";
2236
+ }
2237
+
2238
+ // src/commands/codex-install.ts
2119
2239
  var CAPTURE_BIN = "prim-hook";
2120
2240
  var GATE_BIN = "prim-pre-tool-use";
2121
2241
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -2139,10 +2259,10 @@ var CODEX_REGISTRATIONS = [
2139
2259
  makeRegistration("PostToolUse", CODEX_POST_TOOL_MATCHER, POST_TOOL_USE_BIN, CODEX_ARGS),
2140
2260
  makeRegistration("SessionStart", "*", SESSION_START_BIN, CODEX_ARGS)
2141
2261
  ];
2142
- var USER_SCOPE_PATH = join2(homedir2(), ".codex", "hooks.json");
2143
- var projectScopePath = () => join2(projectRoot(), ".codex", "hooks.json");
2262
+ var userScopePath = () => join3(process.env.CODEX_HOME ?? join3(homedir3(), ".codex"), "hooks.json");
2263
+ var projectScopePath = () => join3(projectRoot(), ".codex", "hooks.json");
2144
2264
  function settingsPathFor(scope) {
2145
- return scope === "user" ? USER_SCOPE_PATH : projectScopePath();
2265
+ return scope === "user" ? userScopePath() : projectScopePath();
2146
2266
  }
2147
2267
  function applyInstall(settings, options = {}) {
2148
2268
  const hooks = { ...settings.hooks ?? {} };
@@ -2188,7 +2308,7 @@ function hookRuntimeResolutions(settings) {
2188
2308
  }
2189
2309
  function inspectHookRuntimeResolutions3() {
2190
2310
  return [
2191
- ...hookRuntimeResolutions(readSettings(USER_SCOPE_PATH)),
2311
+ ...hookRuntimeResolutions(readSettings(userScopePath())),
2192
2312
  ...hookRuntimeResolutions(readSettings(projectScopePath()))
2193
2313
  ];
2194
2314
  }
@@ -2245,13 +2365,13 @@ function performStatus3() {
2245
2365
  complete: hasCompleteHookRegistration(settings)
2246
2366
  };
2247
2367
  };
2248
- return { user: statusFor(USER_SCOPE_PATH), project: statusFor(projectScopePath()) };
2368
+ return { user: statusFor(userScopePath()), project: statusFor(projectScopePath()) };
2249
2369
  }
2250
2370
  function uncoveredWorktreeHooks(status) {
2251
2371
  if (status.user.present || status.project.present) return null;
2252
2372
  const main = mainWorktreeRoot();
2253
2373
  if (main === null) return null;
2254
- const path = join2(main, ".codex", "hooks.json");
2374
+ const path = join3(main, ".codex", "hooks.json");
2255
2375
  return hasAnyHookRegistration(readSettings(path)) ? path : null;
2256
2376
  }
2257
2377
  function uncoveredWorktreeAdvice(path) {
@@ -2267,13 +2387,13 @@ function resolveScope(input) {
2267
2387
  console.error(`[prim] unknown --scope "${input}" (expected: user or project)`);
2268
2388
  process.exit(1);
2269
2389
  }
2270
- var TRUST_NOTICE = "[prim] Codex hooks installed. The tour's nextAction checks whether this session can run them. If pending, inspect /hooks; approve only if a trust action is offered. Active hooks need no additional approval.";
2390
+ var TRUST_NOTICE = "[prim] Codex hooks installed. The tour's nextAction verifies actual hook execution before revealing the story.";
2271
2391
  function registerCodexCommands(program2) {
2272
2392
  const codex = program2.command("codex").description("Manage the prim Codex integration (capture, gate, ingest, presence)");
2273
2393
  codex.command("install").description("Register the prim hooks in Codex's hooks.json (user scope by default)").option(
2274
2394
  "--scope <scope>",
2275
2395
  "user (default, ~/.codex/hooks.json) or project (this checkout's .codex/hooks.json)"
2276
- ).option("--force", "Replace any drifted prim hook entries").action((opts) => {
2396
+ ).option("--force", "Replace any drifted prim hook entries").action(async (opts) => {
2277
2397
  const scope = resolveScope(opts.scope);
2278
2398
  const result = performInstall(scope, opts.force ?? false);
2279
2399
  if (result.changed) {
@@ -2282,7 +2402,16 @@ function registerCodexCommands(program2) {
2282
2402
  console.error(`[prim] Codex integration already present at ${result.path} (no changes)`);
2283
2403
  }
2284
2404
  console.error(TRUST_NOTICE);
2285
- console.log(JSON.stringify(result, null, JSON_INDENT));
2405
+ const host = await inspectCodexHost(Boolean(process.env.CODEX_THREAD_ID));
2406
+ console.error(`[prim] ${codexHostGuidance(host)}`);
2407
+ console.log(JSON.stringify({ ...result, host }, null, JSON_INDENT));
2408
+ });
2409
+ codex.command("refresh").description("Reload installed hooks in the calling Codex session without changing trust").action(async () => {
2410
+ const host = await inspectCodexHost(true);
2411
+ const guidance = codexHostGuidance(host);
2412
+ console.error(`[prim] ${guidance}`);
2413
+ console.log(JSON.stringify({ host, guidance }));
2414
+ if (host.reload !== "refreshed") process.exitCode = 1;
2286
2415
  });
2287
2416
  codex.command("uninstall").description("Remove all prim hooks from Codex's hooks.json").option(
2288
2417
  "--scope <scope>",
@@ -2297,12 +2426,14 @@ function registerCodexCommands(program2) {
2297
2426
  }
2298
2427
  console.log(JSON.stringify(result, null, JSON_INDENT));
2299
2428
  });
2300
- codex.command("status").description("Report whether each prim surface (gate, capture) is installed per scope").action(() => {
2429
+ codex.command("status").description("Report whether each prim surface (gate, capture) is installed per scope").action(async () => {
2301
2430
  const result = performStatus3();
2431
+ const host = await inspectCodexHost();
2302
2432
  const readiness = {
2303
2433
  configured: result.user.complete || result.project.complete,
2304
2434
  runtime: inspectHookRuntime(),
2305
- trust: "unknown",
2435
+ trust: host.trust,
2436
+ host,
2306
2437
  hookExecution: "not-verified",
2307
2438
  passiveCapture: "not-verified"
2308
2439
  };
@@ -2323,12 +2454,12 @@ ${line("project", result.project)}`);
2323
2454
  // src/commands/daemon.ts
2324
2455
  import { spawn as spawn2 } from "child_process";
2325
2456
  import { closeSync as closeSync2, existsSync as existsSync4, mkdirSync as mkdirSync3, openSync as openSync2, readFileSync as readFileSync4, unlinkSync as unlinkSync2 } from "fs";
2326
- import { join as join5 } from "path";
2457
+ import { join as join6 } from "path";
2327
2458
  import { Option as Option2 } from "commander";
2328
2459
 
2329
2460
  // src/daemon/latest-bootstrap.ts
2330
2461
  import { spawn } from "child_process";
2331
- import { join as join3 } from "path";
2462
+ import { join as join4 } from "path";
2332
2463
  var LATEST_BOOTSTRAP_TIMEOUT_MS = 45e3;
2333
2464
  var LATEST_BOOTSTRAP_LOCK_NAME = "daemon-latest.lock";
2334
2465
  async function runPinnedEnsure(options) {
@@ -2369,7 +2500,7 @@ async function runPinnedEnsure(options) {
2369
2500
  });
2370
2501
  }
2371
2502
  async function runLatestDaemonBootstrap(ensureCurrent, options = {}) {
2372
- const lockPath = options.lockPath ?? join3(
2503
+ const lockPath = options.lockPath ?? join4(
2373
2504
  primConfigDirectory({ env: options.env, homeDir: options.homeDir }),
2374
2505
  LATEST_BOOTSTRAP_LOCK_NAME
2375
2506
  );
@@ -2400,28 +2531,28 @@ import {
2400
2531
  chmodSync,
2401
2532
  copyFileSync,
2402
2533
  existsSync as existsSync3,
2403
- lstatSync as lstatSync3,
2534
+ lstatSync as lstatSync4,
2404
2535
  mkdirSync as mkdirSync2,
2405
2536
  mkdtempSync,
2406
2537
  readFileSync as readFileSync3,
2407
2538
  readdirSync as readdirSync2,
2408
2539
  readlinkSync,
2409
- realpathSync,
2540
+ realpathSync as realpathSync2,
2410
2541
  renameSync,
2411
2542
  rmSync,
2412
2543
  statSync,
2413
2544
  symlinkSync,
2414
2545
  writeFileSync as writeFileSync2
2415
2546
  } from "fs";
2416
- import { homedir as homedir3 } from "os";
2417
- import { basename, dirname, isAbsolute, join as join4, resolve as resolve2 } from "path";
2547
+ import { homedir as homedir4 } from "os";
2548
+ import { basename, dirname, isAbsolute as isAbsolute2, join as join5, resolve as resolve2 } from "path";
2418
2549
 
2419
2550
  // src/lib/bounded-file.ts
2420
- import { constants, closeSync, fstatSync, lstatSync as lstatSync2, openSync, readSync } from "fs";
2551
+ import { constants, closeSync, fstatSync, lstatSync as lstatSync3, openSync, readSync } from "fs";
2421
2552
  function readBoundedRegularFile(path, maxBytes) {
2422
2553
  let fd;
2423
2554
  try {
2424
- const linked = lstatSync2(path);
2555
+ const linked = lstatSync3(path);
2425
2556
  if (!linked.isFile() || linked.size > maxBytes) return void 0;
2426
2557
  fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
2427
2558
  const opened = fstatSync(fd);
@@ -2494,33 +2625,33 @@ var LaunchctlError = class extends Error {
2494
2625
  }
2495
2626
  };
2496
2627
  function xdgDataHome(options) {
2497
- const home = options.homeDir ?? homedir3();
2628
+ const home = options.homeDir ?? homedir4();
2498
2629
  const configured = (options.env ?? process.env).XDG_DATA_HOME;
2499
- return configured && isAbsolute(configured) ? configured : join4(home, ".local", "share");
2630
+ return configured && isAbsolute2(configured) ? configured : join5(home, ".local", "share");
2500
2631
  }
2501
2632
  function runtimePaths(options = {}) {
2502
- const dataDir = join4(xdgDataHome(options), "prim");
2503
- const runtimeDir = join4(dataDir, "runtime");
2504
- const currentLink = join4(runtimeDir, "current");
2633
+ const dataDir = join5(xdgDataHome(options), "prim");
2634
+ const runtimeDir = join5(dataDir, "runtime");
2635
+ const currentLink = join5(runtimeDir, "current");
2505
2636
  return {
2506
2637
  dataDir,
2507
2638
  runtimeDir,
2508
- releasesDir: join4(runtimeDir, "releases"),
2639
+ releasesDir: join5(runtimeDir, "releases"),
2509
2640
  currentLink,
2510
- statuslineLauncher: join4(runtimeDir, "prim-statusline"),
2511
- disabledMarker: join4(dataDir, "daemon.disabled"),
2512
- lifecycleLockDir: join4(dataDir, "daemon.lifecycle.lock")
2641
+ statuslineLauncher: join5(runtimeDir, "prim-statusline"),
2642
+ disabledMarker: join5(dataDir, "daemon.disabled"),
2643
+ lifecycleLockDir: join5(dataDir, "daemon.lifecycle.lock")
2513
2644
  };
2514
2645
  }
2515
2646
  function daemonControlPaths(options = {}) {
2516
2647
  const configDir = primConfigDirectory(options);
2517
2648
  const legacy = runtimePaths(options);
2518
2649
  return {
2519
- launcher: join4(configDir, `prim-daemon-launcher-v${LAUNCHER_SCHEMA_VERSION}`),
2520
- disabledMarker: join4(configDir, "daemon.disabled"),
2521
- driftHealMarker: join4(configDir, DRIFT_HEAL_MARKER),
2522
- driftHealClaim: join4(configDir, "daemon-drift-heal.lock"),
2523
- lifecycleLockDir: join4(configDir, "daemon.lifecycle.lock"),
2650
+ launcher: join5(configDir, `prim-daemon-launcher-v${LAUNCHER_SCHEMA_VERSION}`),
2651
+ disabledMarker: join5(configDir, "daemon.disabled"),
2652
+ driftHealMarker: join5(configDir, DRIFT_HEAL_MARKER),
2653
+ driftHealClaim: join5(configDir, "daemon-drift-heal.lock"),
2654
+ lifecycleLockDir: join5(configDir, "daemon.lifecycle.lock"),
2524
2655
  legacyDisabledMarker: legacy.disabledMarker,
2525
2656
  legacyLifecycleLockDir: legacy.lifecycleLockDir
2526
2657
  };
@@ -2528,7 +2659,7 @@ function daemonControlPaths(options = {}) {
2528
2659
  function findPackageVersion(entryFile) {
2529
2660
  let dir = dirname(resolve2(entryFile));
2530
2661
  for (let depth = 0; depth < 6; depth++) {
2531
- const packagePath = join4(dir, "package.json");
2662
+ const packagePath = join5(dir, "package.json");
2532
2663
  if (existsSync3(packagePath)) {
2533
2664
  try {
2534
2665
  const manifest = JSON.parse(readFileSync3(packagePath, "utf8"));
@@ -2562,8 +2693,8 @@ function exactKeys(value, expected) {
2562
2693
  return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
2563
2694
  }
2564
2695
  function readOwnedRuntimeManifest(releaseDir) {
2565
- const manifestPath = join4(releaseDir, "manifest.json");
2566
- const daemonPath = join4(releaseDir, "prim-daemon-server");
2696
+ const manifestPath = join5(releaseDir, "manifest.json");
2697
+ const daemonPath = join5(releaseDir, "prim-daemon-server");
2567
2698
  try {
2568
2699
  const raw = readFileSync3(manifestPath, "utf8");
2569
2700
  const parsed = JSON.parse(raw);
@@ -2579,8 +2710,8 @@ function readOwnedRuntimeManifest(releaseDir) {
2579
2710
  return null;
2580
2711
  }
2581
2712
  const manifest = parsed;
2582
- if (manifest.schemaVersion !== RUNTIME_SCHEMA_VERSION || compareSemver(manifest.version, manifest.version) !== 0 || !isAbsolute(manifest.nodePath) || /[\r\n]/u.test(manifest.nodePath) || manifest.daemonFile !== "prim-daemon-server" || !/^[0-9a-f]{64}$/u.test(manifest.daemonSha256) || new Date(manifest.stagedAt).toISOString() !== manifest.stagedAt || raw !== `${JSON.stringify(manifest, null, 2)}
2583
- ` || !lstatSync3(daemonPath).isFile() || sha256File(daemonPath) !== manifest.daemonSha256) {
2713
+ if (manifest.schemaVersion !== RUNTIME_SCHEMA_VERSION || compareSemver(manifest.version, manifest.version) !== 0 || !isAbsolute2(manifest.nodePath) || /[\r\n]/u.test(manifest.nodePath) || manifest.daemonFile !== "prim-daemon-server" || !/^[0-9a-f]{64}$/u.test(manifest.daemonSha256) || new Date(manifest.stagedAt).toISOString() !== manifest.stagedAt || raw !== `${JSON.stringify(manifest, null, 2)}
2714
+ ` || !lstatSync4(daemonPath).isFile() || sha256File(daemonPath) !== manifest.daemonSha256) {
2584
2715
  return null;
2585
2716
  }
2586
2717
  const entries = readdirSync2(releaseDir).sort();
@@ -2592,8 +2723,8 @@ function readOwnedRuntimeManifest(releaseDir) {
2592
2723
  function sameNode(recorded, desired) {
2593
2724
  if (recorded === desired) return true;
2594
2725
  try {
2595
- const target = realpathSync(desired);
2596
- return recorded !== target && realpathSync(recorded) === target;
2726
+ const target = realpathSync2(desired);
2727
+ return recorded !== target && realpathSync2(recorded) === target;
2597
2728
  } catch {
2598
2729
  return false;
2599
2730
  }
@@ -2639,11 +2770,11 @@ function stageRuntime(options = {}) {
2639
2770
  };
2640
2771
  let currentRelease = null;
2641
2772
  try {
2642
- currentRelease = realpathSync(paths.currentLink);
2773
+ currentRelease = realpathSync2(paths.currentLink);
2643
2774
  } catch {
2644
2775
  }
2645
- const current = currentRelease ? readRuntimeManifest(join4(currentRelease, "manifest.json")) : null;
2646
- const currentDaemon = currentRelease ? join4(currentRelease, desired.daemonFile) : "";
2776
+ const current = currentRelease ? readRuntimeManifest(join5(currentRelease, "manifest.json")) : null;
2777
+ const currentDaemon = currentRelease ? join5(currentRelease, desired.daemonFile) : "";
2647
2778
  if (currentRelease && sameRuntime(current, desired, currentDaemon)) {
2648
2779
  const manifest = current;
2649
2780
  atomicWrite2(
@@ -2661,17 +2792,17 @@ function stageRuntime(options = {}) {
2661
2792
  mkdirSync2(paths.releasesDir, { recursive: true, mode: RUNTIME_DIR_MODE });
2662
2793
  chmodSync(paths.runtimeDir, RUNTIME_DIR_MODE);
2663
2794
  chmodSync(paths.releasesDir, RUNTIME_DIR_MODE);
2664
- const stagingDir = mkdtempSync(join4(paths.releasesDir, ".stage-"));
2795
+ const stagingDir = mkdtempSync(join5(paths.releasesDir, ".stage-"));
2665
2796
  chmodSync(stagingDir, RUNTIME_DIR_MODE);
2666
2797
  let releaseDir;
2667
2798
  try {
2668
- const daemonTarget = join4(stagingDir, desired.daemonFile);
2799
+ const daemonTarget = join5(stagingDir, desired.daemonFile);
2669
2800
  copyFileSync(daemonSource, daemonTarget);
2670
2801
  chmodSync(daemonTarget, RUNTIME_FILE_MODE);
2671
2802
  if (sha256File(daemonTarget) !== desired.daemonSha256) {
2672
2803
  throw new Error("cannot stage runtime: daemon bundle changed while it was copied");
2673
2804
  }
2674
- const manifestTarget = join4(stagingDir, "manifest.json");
2805
+ const manifestTarget = join5(stagingDir, "manifest.json");
2675
2806
  writeFileSync2(manifestTarget, `${JSON.stringify(desired, null, 2)}
2676
2807
  `, {
2677
2808
  encoding: "utf8",
@@ -2679,10 +2810,10 @@ function stageRuntime(options = {}) {
2679
2810
  flag: "wx"
2680
2811
  });
2681
2812
  const releaseName = `release-${createHash2("sha256").update(`${version}\0${nodePath}\0${desired.stagedAt}\0${process.pid}\0${Math.random()}`).digest("hex").slice(0, 16)}`;
2682
- releaseDir = join4(paths.releasesDir, releaseName);
2813
+ releaseDir = join5(paths.releasesDir, releaseName);
2683
2814
  renameSync(stagingDir, releaseDir);
2684
- releaseDir = realpathSync(releaseDir);
2685
- atomicSymlink(join4("releases", releaseName), paths.currentLink);
2815
+ releaseDir = realpathSync2(releaseDir);
2816
+ atomicSymlink(join5("releases", releaseName), paths.currentLink);
2686
2817
  atomicWrite2(
2687
2818
  paths.statuslineLauncher,
2688
2819
  statuslineLauncherContent(desired.version, options),
@@ -2696,14 +2827,14 @@ function stageRuntime(options = {}) {
2696
2827
  changed: true,
2697
2828
  manifest: desired,
2698
2829
  paths,
2699
- daemonPath: join4(releaseDir, desired.daemonFile)
2830
+ daemonPath: join5(releaseDir, desired.daemonFile)
2700
2831
  };
2701
2832
  }
2702
2833
  function shellQuote(value) {
2703
2834
  return `'${value.replaceAll("'", `'"'"'`)}'`;
2704
2835
  }
2705
2836
  function statuslineLauncherContent(version, options = {}) {
2706
- const socketPath = join4(primConfigDirectory(options), "sock");
2837
+ const socketPath = join5(primConfigDirectory(options), "sock");
2707
2838
  const fallback = `primitive ${version} (daemon: down)`;
2708
2839
  return `#!/bin/sh
2709
2840
  response=$(
@@ -2726,7 +2857,7 @@ function assertRegularFile(path, label2) {
2726
2857
  }
2727
2858
  function lstatIfPresent2(path) {
2728
2859
  try {
2729
- return lstatSync3(path);
2860
+ return lstatSync4(path);
2730
2861
  } catch (error) {
2731
2862
  const code = error.code;
2732
2863
  if (code === "ENOENT" || code === "ENOTDIR") return void 0;
@@ -2735,7 +2866,7 @@ function lstatIfPresent2(path) {
2735
2866
  }
2736
2867
  function driftHealMarkerTemporaries(configDir) {
2737
2868
  try {
2738
- return readdirSync2(configDir).filter((entry) => DRIFT_HEAL_MARKER_TEMPORARY_RE.test(entry)).map((entry) => join4(configDir, entry));
2869
+ return readdirSync2(configDir).filter((entry) => DRIFT_HEAL_MARKER_TEMPORARY_RE.test(entry)).map((entry) => join5(configDir, entry));
2739
2870
  } catch (error) {
2740
2871
  const code = error.code;
2741
2872
  if (code === "ENOENT" || code === "ENOTDIR") return [];
@@ -2748,7 +2879,7 @@ function assertDriftHealClaim(path) {
2748
2879
  if (!claim.isDirectory() || readdirSync2(path).some((entry) => entry !== DRIFT_HEAL_CLAIM_OWNER)) {
2749
2880
  throw new Error(`refusing to remove unrecognized daemon drift-heal claim at ${path}`);
2750
2881
  }
2751
- assertRegularFile(join4(path, DRIFT_HEAL_CLAIM_OWNER), "daemon drift-heal claim owner");
2882
+ assertRegularFile(join5(path, DRIFT_HEAL_CLAIM_OWNER), "daemon drift-heal claim owner");
2752
2883
  }
2753
2884
  function assertExactFile(path, expected, label2) {
2754
2885
  if (!lstatIfPresent2(path)) return;
@@ -2762,12 +2893,12 @@ function assertOwnedDaemonRuntime(options) {
2762
2893
  const control = daemonControlPaths(options);
2763
2894
  const configDir = primConfigDirectory(options);
2764
2895
  const service = process.platform === "darwin" ? launchdPaths(options) : void 0;
2765
- const logPath = service?.logPath ?? join4(configDir, "daemon.log");
2896
+ const logPath = service?.logPath ?? join5(configDir, "daemon.log");
2766
2897
  for (const activeArtifact of [
2767
- join4(configDir, "daemon.pid"),
2768
- join4(configDir, "sock"),
2769
- join4(configDir, "daemon.lock"),
2770
- join4(configDir, "client-instance.lock")
2898
+ join5(configDir, "daemon.pid"),
2899
+ join5(configDir, "sock"),
2900
+ join5(configDir, "daemon.lock"),
2901
+ join5(configDir, "client-instance.lock")
2771
2902
  ]) {
2772
2903
  if (lstatIfPresent2(activeArtifact)) {
2773
2904
  throw new Error(`refusing runtime removal while daemon state remains at ${activeArtifact}`);
@@ -2793,8 +2924,8 @@ function assertOwnedDaemonRuntime(options) {
2793
2924
  assertRegularFile(temporary, "daemon drift-heal marker temporary");
2794
2925
  }
2795
2926
  assertDriftHealClaim(control.driftHealClaim);
2796
- assertRegularFile(join4(configDir, "daemon-health.json"), "daemon health snapshot");
2797
- assertRegularFile(join4(configDir, "client_instance_id"), "daemon client instance id");
2927
+ assertRegularFile(join5(configDir, "daemon-health.json"), "daemon health snapshot");
2928
+ assertRegularFile(join5(configDir, "client_instance_id"), "daemon client instance id");
2798
2929
  if (service && lstatIfPresent2(service.plistPath)) {
2799
2930
  assertRegularFile(service.plistPath, "launchd property list");
2800
2931
  if (readFileSync3(service.plistPath, "utf8") !== ownedLaunchAgentPlist(options, logPath)) {
@@ -2822,7 +2953,7 @@ function assertOwnedDaemonRuntime(options) {
2822
2953
  throw new Error(`refusing to remove non-directory daemon releases at ${runtime.releasesDir}`);
2823
2954
  }
2824
2955
  for (const entry of readdirSync2(runtime.releasesDir, { withFileTypes: true })) {
2825
- const releaseDir = join4(runtime.releasesDir, entry.name);
2956
+ const releaseDir = join5(runtime.releasesDir, entry.name);
2826
2957
  const manifest = entry.isDirectory() && RUNTIME_RELEASE_RE.test(entry.name) ? readOwnedRuntimeManifest(releaseDir) : null;
2827
2958
  if (!manifest) {
2828
2959
  throw new Error(`refusing to remove unrecognized daemon release ${releaseDir}`);
@@ -2840,7 +2971,7 @@ function assertOwnedDaemonRuntime(options) {
2840
2971
  }
2841
2972
  const target = readlinkSync(runtime.currentLink);
2842
2973
  const releaseName = basename(target);
2843
- if (target !== join4("releases", releaseName) || !RUNTIME_RELEASE_RE.test(releaseName)) {
2974
+ if (target !== join5("releases", releaseName) || !RUNTIME_RELEASE_RE.test(releaseName)) {
2844
2975
  throw new Error(
2845
2976
  `refusing to remove malformed daemon runtime selector ${runtime.currentLink}`
2846
2977
  );
@@ -2868,7 +2999,7 @@ async function removeDaemonRuntime(options = {}) {
2868
2999
  const control = daemonControlPaths(options);
2869
3000
  const configDir = primConfigDirectory(options);
2870
3001
  const service = process.platform === "darwin" ? launchdPaths(options) : void 0;
2871
- const logPath = service?.logPath ?? join4(configDir, "daemon.log");
3002
+ const logPath = service?.logPath ?? join5(configDir, "daemon.log");
2872
3003
  const ownedArtifacts = [
2873
3004
  runtime.runtimeDir,
2874
3005
  control.launcher,
@@ -2879,8 +3010,8 @@ async function removeDaemonRuntime(options = {}) {
2879
3010
  control.driftHealClaim,
2880
3011
  ...service ? [service.plistPath] : [],
2881
3012
  logPath,
2882
- join4(configDir, "daemon-health.json"),
2883
- join4(configDir, "client_instance_id")
3013
+ join5(configDir, "daemon-health.json"),
3014
+ join5(configDir, "client_instance_id")
2884
3015
  ];
2885
3016
  if (!ownedArtifacts.some((path) => lstatIfPresent2(path))) {
2886
3017
  return { changed: false, runtimePaths: runtime };
@@ -2926,7 +3057,7 @@ function ownedLaunchAgentPlist(options, logPath) {
2926
3057
  return generateLaunchAgentPlist({
2927
3058
  launcherPath: daemonControlPaths(options).launcher,
2928
3059
  logPath,
2929
- workingDirectory: options.homeDir ?? homedir3(),
3060
+ workingDirectory: options.homeDir ?? homedir4(),
2930
3061
  label: options.label
2931
3062
  });
2932
3063
  }
@@ -2941,7 +3072,7 @@ function readDaemonLauncherFile(path) {
2941
3072
  const encoded = /^# prim-daemon-launcher: ([A-Za-z0-9_-]+)$/mu.exec(content)?.[1];
2942
3073
  if (!encoded) return null;
2943
3074
  const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
2944
- if (value.schemaVersion !== LAUNCHER_SCHEMA_VERSION || typeof value.nodePath !== "string" || typeof value.daemonPath !== "string" || typeof value.runtimeVersion !== "string" || value.apiUrl !== null && typeof value.apiUrl !== "string" || value.configDir !== void 0 && (typeof value.configDir !== "string" || !isAbsolute(value.configDir)) || typeof value.revision !== "string") {
3075
+ if (value.schemaVersion !== LAUNCHER_SCHEMA_VERSION || typeof value.nodePath !== "string" || typeof value.daemonPath !== "string" || typeof value.runtimeVersion !== "string" || value.apiUrl !== null && typeof value.apiUrl !== "string" || value.configDir !== void 0 && (typeof value.configDir !== "string" || !isAbsolute2(value.configDir)) || typeof value.revision !== "string") {
2945
3076
  return null;
2946
3077
  }
2947
3078
  const config = {
@@ -2960,7 +3091,7 @@ function readDaemonLauncherFile(path) {
2960
3091
  function readUsableDaemonConfig(path) {
2961
3092
  const config = readDaemonLauncher(path);
2962
3093
  if (!config) return null;
2963
- const manifest = readRuntimeManifest(join4(dirname(config.daemonPath), "manifest.json"));
3094
+ const manifest = readRuntimeManifest(join5(dirname(config.daemonPath), "manifest.json"));
2964
3095
  try {
2965
3096
  accessSync(config.nodePath, constants2.X_OK);
2966
3097
  return manifest?.version === config.runtimeVersion && manifest.nodePath === config.nodePath && manifest.daemonSha256 === sha256File(config.daemonPath) ? config : null;
@@ -3005,7 +3136,7 @@ function generateLaunchAgentPlist(config) {
3005
3136
  `;
3006
3137
  }
3007
3138
  function launchdPaths(options = {}) {
3008
- const home = options.homeDir ?? homedir3();
3139
+ const home = options.homeDir ?? homedir4();
3009
3140
  const configDir = primConfigDirectory(options);
3010
3141
  const uid = options.uid ?? process.getuid?.();
3011
3142
  const label2 = options.label ?? LAUNCHD_LABEL;
@@ -3013,8 +3144,8 @@ function launchdPaths(options = {}) {
3013
3144
  return {
3014
3145
  domainTarget: `gui/${uid}`,
3015
3146
  serviceTarget: `gui/${uid}/${label2}`,
3016
- plistPath: join4(home, "Library", "LaunchAgents", `${label2}.plist`),
3017
- logPath: join4(configDir, "daemon.log")
3147
+ plistPath: join5(home, "Library", "LaunchAgents", `${label2}.plist`),
3148
+ logPath: join5(configDir, "daemon.log")
3018
3149
  };
3019
3150
  }
3020
3151
  var runLaunchctl = (args, timeoutMs2 = COMMAND_TIMEOUT_MS) => {
@@ -3096,7 +3227,7 @@ function canonicalProspectivePath(path) {
3096
3227
  ancestor = parent;
3097
3228
  }
3098
3229
  try {
3099
- return join4(realpathSync(ancestor), ...suffix);
3230
+ return join5(realpathSync2(ancestor), ...suffix);
3100
3231
  } catch {
3101
3232
  return resolve2(path);
3102
3233
  }
@@ -3111,7 +3242,7 @@ async function withDaemonLifecycleLock(operation, options = {}) {
3111
3242
  );
3112
3243
  }
3113
3244
  async function stopVerifiedLegacyDaemon(options, deadlineMs, nowMs, sleep2) {
3114
- const pidPath = join4(primConfigDirectory(options), "daemon.pid");
3245
+ const pidPath = join5(primConfigDirectory(options), "daemon.pid");
3115
3246
  let pid;
3116
3247
  try {
3117
3248
  pid = Number(readFileSync3(pidPath, "utf8").trim());
@@ -3403,7 +3534,7 @@ async function ensureMacDaemonLocked(options) {
3403
3534
  const configuredApiUrl = (options.env ?? process.env).PRIM_API_URL;
3404
3535
  const apiUrl = configuredApiUrl ? normalizeApiUrl(configuredApiUrl) || void 0 : void 0;
3405
3536
  const configDir = primConfigDirectory(options);
3406
- const legacyDefaultConfigDir = join4(options.homeDir ?? homedir3(), ".config", "prim");
3537
+ const legacyDefaultConfigDir = join5(options.homeDir ?? homedir4(), ".config", "prim");
3407
3538
  const launcherConfigDir = configDir === legacyDefaultConfigDir ? void 0 : configDir;
3408
3539
  if (retainSelected && selected) {
3409
3540
  const usable = readUsableDaemonConfig(control.launcher);
@@ -3438,7 +3569,7 @@ async function ensureMacDaemonLocked(options) {
3438
3569
  const plist = generateLaunchAgentPlist({
3439
3570
  launcherPath: control.launcher,
3440
3571
  logPath: servicePaths.logPath,
3441
- workingDirectory: options.homeDir ?? homedir3(),
3572
+ workingDirectory: options.homeDir ?? homedir4(),
3442
3573
  label: options.label
3443
3574
  });
3444
3575
  const plistChanged = atomicWrite2(
@@ -3558,9 +3689,9 @@ async function bootoutMacDaemonLocked(options) {
3558
3689
  // src/commands/daemon.ts
3559
3690
  var DAEMON_BIN = "prim-daemon-server";
3560
3691
  var CONFIG_DIR = primConfigDirectory();
3561
- var PID_PATH = join5(CONFIG_DIR, "daemon.pid");
3562
- var SOCK_PATH = join5(CONFIG_DIR, "sock");
3563
- var LOG_PATH = join5(CONFIG_DIR, "daemon.log");
3692
+ var PID_PATH = join6(CONFIG_DIR, "daemon.pid");
3693
+ var SOCK_PATH = join6(CONFIG_DIR, "sock");
3694
+ var LOG_PATH = join6(CONFIG_DIR, "daemon.log");
3564
3695
  var CONFIG_DIR_MODE = 448;
3565
3696
  var LOG_FILE_MODE = 384;
3566
3697
  var STOP_TIMEOUT_MS = 5e3;
@@ -3633,7 +3764,7 @@ function openDaemonLog(configDir = CONFIG_DIR) {
3633
3764
  if (!existsSync4(configDir)) {
3634
3765
  mkdirSync3(configDir, { recursive: true, mode: CONFIG_DIR_MODE });
3635
3766
  }
3636
- return openSync2(join5(configDir, "daemon.log"), "a", LOG_FILE_MODE);
3767
+ return openSync2(join6(configDir, "daemon.log"), "a", LOG_FILE_MODE);
3637
3768
  }
3638
3769
  async function waitForReady() {
3639
3770
  const deadline = Date.now() + READY_TIMEOUT_MS;
@@ -6663,16 +6794,16 @@ function validate(value) {
6663
6794
  // src/demo/sandbox.ts
6664
6795
  import {
6665
6796
  existsSync as existsSync5,
6666
- lstatSync as lstatSync4,
6797
+ lstatSync as lstatSync5,
6667
6798
  mkdtempSync as mkdtempSync2,
6668
6799
  readFileSync as readFileSync5,
6669
6800
  readdirSync as readdirSync3,
6670
- realpathSync as realpathSync2,
6801
+ realpathSync as realpathSync3,
6671
6802
  rmdirSync,
6672
6803
  unlinkSync as unlinkSync3
6673
6804
  } from "fs";
6674
6805
  import { tmpdir } from "os";
6675
- import { basename as basename2, dirname as dirname2, join as join6 } from "path";
6806
+ import { basename as basename2, dirname as dirname2, join as join7 } from "path";
6676
6807
 
6677
6808
  // src/demo/scenario.ts
6678
6809
  var SAMPLE_NOTE = [
@@ -6741,17 +6872,17 @@ function allowedFiles(run) {
6741
6872
  }
6742
6873
  function inspectSandbox(run) {
6743
6874
  const sandbox = run.sandbox;
6744
- if (!sandbox || dirname2(sandbox.path) !== realpathSync2(tmpdir()) || !basename2(sandbox.path).startsWith("prim-demo-")) {
6875
+ if (!sandbox || dirname2(sandbox.path) !== realpathSync3(tmpdir()) || !basename2(sandbox.path).startsWith("prim-demo-")) {
6745
6876
  throw new Error("invalid demo sandbox ownership");
6746
6877
  }
6747
- const stat = lstatSync4(sandbox.path);
6878
+ const stat = lstatSync5(sandbox.path);
6748
6879
  if (!stat.isDirectory() || stat.dev !== sandbox.device || stat.ino !== sandbox.inode) {
6749
6880
  throw new Error(`demo sandbox changed; retained ${sandbox.path}`);
6750
6881
  }
6751
6882
  const allowed = allowedFiles(run);
6752
6883
  for (const name of readdirSync3(sandbox.path)) {
6753
- const path = join6(sandbox.path, name);
6754
- const file = lstatSync4(path);
6884
+ const path = join7(sandbox.path, name);
6885
+ const file = lstatSync5(path);
6755
6886
  if (!Object.hasOwn(allowed, name) || !file.isFile() || file.nlink !== 1 || file.size > 16384 || !allowed[name].includes(readFileSync5(path, "utf8"))) {
6756
6887
  throw new Error(`unexpected demo contents; retained ${sandbox.path}`);
6757
6888
  }
@@ -6760,8 +6891,8 @@ function inspectSandbox(run) {
6760
6891
  }
6761
6892
  function createSandbox(run) {
6762
6893
  if (!run.sandbox) {
6763
- const path = mkdtempSync2(join6(realpathSync2(tmpdir()), "prim-demo-"));
6764
- const stat = lstatSync4(path);
6894
+ const path = mkdtempSync2(join7(realpathSync3(tmpdir()), "prim-demo-"));
6895
+ const stat = lstatSync5(path);
6765
6896
  run.sandbox = { path, device: stat.dev, inode: stat.ino };
6766
6897
  saveRun(run);
6767
6898
  }
@@ -6773,22 +6904,22 @@ function createSandbox(run) {
6773
6904
  "decisions.json": decisionBytes(false)
6774
6905
  };
6775
6906
  for (const [name, content] of Object.entries(files)) {
6776
- const path = join6(root, name);
6907
+ const path = join7(root, name);
6777
6908
  if (!existsSync5(path)) atomicWriteFile(path, content, { mode: 384 });
6778
6909
  }
6779
6910
  }
6780
6911
  function writeSample(run, name, bytes) {
6781
6912
  const root = inspectSandbox(run);
6782
6913
  if (!allowedFiles(run)[name].includes(bytes)) throw new Error("unsupported demo edit");
6783
- atomicWriteFile(join6(root, name), bytes, { mode: 384 });
6914
+ atomicWriteFile(join7(root, name), bytes, { mode: 384 });
6784
6915
  }
6785
6916
  function readSample(run, name) {
6786
- return readFileSync5(join6(inspectSandbox(run), name), "utf8");
6917
+ return readFileSync5(join7(inspectSandbox(run), name), "utf8");
6787
6918
  }
6788
6919
  function cleanSandbox(run) {
6789
6920
  if (!run.sandbox) return;
6790
6921
  try {
6791
- lstatSync4(run.sandbox.path);
6922
+ lstatSync5(run.sandbox.path);
6792
6923
  } catch (error) {
6793
6924
  if (error.code !== "ENOENT") throw error;
6794
6925
  run.sandbox = void 0;
@@ -6797,7 +6928,7 @@ function cleanSandbox(run) {
6797
6928
  const root = inspectSandbox(run);
6798
6929
  for (const name of readdirSync3(root)) {
6799
6930
  inspectSandbox(run);
6800
- unlinkSync3(join6(root, name));
6931
+ unlinkSync3(join7(root, name));
6801
6932
  }
6802
6933
  rmdirSync(root);
6803
6934
  run.sandbox = void 0;
@@ -6821,7 +6952,7 @@ function compactDiff(before, after) {
6821
6952
  }
6822
6953
  function demoTrustGuidance(agent) {
6823
6954
  if (agent === "codex")
6824
- return "Check /hooks in Codex. Approve only if a trust action is offered. If hooks are already active, retry the exact standalone command once; do not keep asking for trust or a new session. If still pending, run diagnosticAction once. Inspect its expected PreToolUse/Bash event and runtime; UserPromptSubmit does not acknowledge the tour. Do not prepare a new run.";
6955
+ return "Run diagnosticAction once. Codex can report hooks trusted while its running session still uses the configuration from before installation. Follow the diagnostic's repairAction when provided; otherwise inspect /hooks for errors or review. Never ask for trust again when hooks are already trusted. Keep this run.";
6825
6956
  if (agent === "hermes")
6826
6957
  return "Approve the installed prim hooks when Hermes prompts, then retry the exact nextAction.";
6827
6958
  if (agent === "cursor")
@@ -7008,7 +7139,11 @@ async function finishResolution(run, choice, reason) {
7008
7139
  finishOnboarding("completed");
7009
7140
  }
7010
7141
  }
7011
- function pendingIsolation(run, isolation, action, choice, reason) {
7142
+ async function pendingIsolation(run, isolation, action, choice, reason) {
7143
+ const host = run.agent === "codex" && action === "status" ? await inspectCodexHost() : void 0;
7144
+ const diagnostics = isolationDiagnostics(run);
7145
+ const repairAction = host?.trust === "trusted" && !diagnostics.hookObservation && diagnostics.runtime.state === "ready" ? [...run.launcher, "codex", "refresh"].map((part) => `'${part.replaceAll("'", "'\\''")}'`).join(" ") : void 0;
7146
+ const guidance = diagnostics.hookObservation ? diagnostics.hookObservation.result === "acknowledged" ? `The pre-tool hook previously acknowledged this tour, but the current acknowledgment is invalid (${isolation}). Run the exact resume action in the bound session to obtain a fresh acknowledgment; do not repeat setup or trust review.` : `The pre-tool hook reached Primitive: ${diagnostics.hookObservation.result}${diagnostics.hookObservation.errorCode ? ` (${diagnostics.hookObservation.errorCode})` : ""}. Repair that reported failure before resuming this same tour; do not repeat setup or trust review.` : host ? codexHostGuidance(host) : demoTrustGuidance(run.agent);
7012
7147
  return {
7013
7148
  fictional: true,
7014
7149
  evaluation: "live",
@@ -7016,13 +7151,14 @@ function pendingIsolation(run, isolation, action, choice, reason) {
7016
7151
  stage: "pending",
7017
7152
  isolation,
7018
7153
  ...action === "status" ? { resumeAction: demoResumeCommand(run) } : { nextAction: demoCommand(run, action, choice, reason) },
7019
- diagnostics: isolationDiagnostics(run),
7154
+ diagnostics: { ...diagnostics, ...host ? { host, trust: host.trust } : {} },
7155
+ ...repairAction ? { repairAction } : {},
7020
7156
  ...action === "status" ? {} : { diagnosticAction: demoDiagnosticCommand(run) },
7021
7157
  skipAction: demoCommand(run, "skip"),
7022
7158
  presentation: `Tour prepared \u2192 **Isolation pending** \u2192 ${run.stage === "prepared" ? "Story not started" : "Story paused"}.
7023
7159
 
7024
- ${isolation}. Checking the installed pre-tool hook before continuing.`,
7025
- guidance: demoTrustGuidance(run.agent),
7160
+ ${action === "status" ? guidance : "The pre-tool hook has not verified isolation. Run the returned diagnostic action."}`,
7161
+ guidance,
7026
7162
  recovery: `${action === "status" ? "Use this evidence to repair the hook before resumeAction." : "Run diagnosticAction once."} If no hook observation exists, the CLI has no evidence this command reached its installed pre-tool hook. Check the host hook event/error view and configuration-directory access; absence of a log is not proof of healthy hooks. Retry only after a repair, using this run. Never fabricate acknowledgment or read sample files.`
7027
7163
  };
7028
7164
  }
@@ -7395,8 +7531,8 @@ async function inspectJournalDelivery(buckets, options = {}) {
7395
7531
 
7396
7532
  // src/commands/hermes-install.ts
7397
7533
  import { existsSync as existsSync6, readFileSync as readFileSync6, rmSync as rmSync2, statSync as statSync2 } from "fs";
7398
- import { homedir as homedir4 } from "os";
7399
- import { join as join7 } from "path";
7534
+ import { homedir as homedir5 } from "os";
7535
+ import { join as join8 } from "path";
7400
7536
  import { Document, isMap, isSeq, parseAllDocuments, stringify, visit } from "yaml";
7401
7537
  var CAPTURE_BIN2 = "prim-hook";
7402
7538
  var GATE_BIN2 = "prim-pre-tool-use";
@@ -7409,13 +7545,13 @@ var JSON_INDENT2 = 2;
7409
7545
  var CONFIG_MODE = 384;
7410
7546
  var PRIM_BINS2 = [CAPTURE_BIN2, GATE_BIN2, POST_TOOL_USE_BIN2, SESSION_START_BIN2, SESSION_END_BIN];
7411
7547
  function hermesHome() {
7412
- return process.env.HERMES_HOME ?? join7(homedir4(), ".hermes");
7548
+ return process.env.HERMES_HOME ?? join8(homedir5(), ".hermes");
7413
7549
  }
7414
7550
  function configPath() {
7415
- return join7(hermesHome(), "config.yaml");
7551
+ return join8(hermesHome(), "config.yaml");
7416
7552
  }
7417
7553
  function legacyShimPath() {
7418
- return join7(hermesHome(), "agent-hooks", "prim-shim.sh");
7554
+ return join8(hermesHome(), "agent-hooks", "prim-shim.sh");
7419
7555
  }
7420
7556
  function commandFor(bin) {
7421
7557
  return stableHookCommand(bin, HERMES_ARGS);
@@ -8422,7 +8558,7 @@ function classifyClaudeHooks(statuses) {
8422
8558
  }
8423
8559
  return { name: "feedback-hooks", status: "ok", detail: "complete Claude lifecycle ready" };
8424
8560
  }
8425
- function classifyCodexHooks(statuses, uncoveredWorktree = null, capturedAt) {
8561
+ function classifyCodexHooks(statuses, uncoveredWorktree = null, capturedAt, host) {
8426
8562
  const installed = statuses.filter((status) => status.present);
8427
8563
  if (installed.length === 0) {
8428
8564
  if (uncoveredWorktree !== null) {
@@ -8443,8 +8579,8 @@ function classifyCodexHooks(statuses, uncoveredWorktree = null, capturedAt) {
8443
8579
  }
8444
8580
  return {
8445
8581
  name: "codex-hooks",
8446
- status: capturedAt === void 0 ? "warn" : "ok",
8447
- detail: capturedAt === void 0 ? "installed; conversation capture unverified; Codex trust unknown \u2014 verify with `/hooks`" : `installed; conversation capture observed ${new Date(capturedAt).toISOString()}; current trust unknown`
8582
+ status: capturedAt === void 0 || host?.trust === "review-required" || host?.trust === "disabled" ? "warn" : "ok",
8583
+ detail: host && host.trust !== "unknown" ? `installed; ${capturedAt === void 0 ? "conversation capture unverified" : `conversation capture observed ${new Date(capturedAt).toISOString()}`}; ${host.trust === "trusted" ? "Codex reports hooks enabled and trusted" : codexHostGuidance(host)}` : capturedAt === void 0 ? "installed; conversation capture unverified; Codex trust unknown \u2014 verify with `/hooks`" : `installed; conversation capture observed ${new Date(capturedAt).toISOString()}; current trust unknown`
8448
8584
  };
8449
8585
  }
8450
8586
  function classifyCursorHooks(statuses) {
@@ -8492,7 +8628,7 @@ function classifyHermesHooks(status) {
8492
8628
  detail: "installed; hook consent is not pre-authorized \u2014 run `prim hermes install --auto-accept`"
8493
8629
  };
8494
8630
  }
8495
- function checkAgentHooks() {
8631
+ async function checkAgentHooks() {
8496
8632
  const checks = [];
8497
8633
  try {
8498
8634
  const status = performStatus3();
@@ -8500,7 +8636,8 @@ function checkAgentHooks() {
8500
8636
  classifyCodexHooks(
8501
8637
  [status.project, status.user],
8502
8638
  uncoveredWorktreeHooks(status),
8503
- lastConversationCaptured(process.cwd(), "codex")
8639
+ lastConversationCaptured(process.cwd(), "codex"),
8640
+ status.user.present || status.project.present ? await inspectCodexHost() : void 0
8504
8641
  )
8505
8642
  );
8506
8643
  } catch (error) {
@@ -8725,7 +8862,7 @@ async function independentChecks() {
8725
8862
  after: [
8726
8863
  await checkJournalOrganization(),
8727
8864
  checkFeedbackHooks(),
8728
- ...checkAgentHooks(),
8865
+ ...await checkAgentHooks(),
8729
8866
  checkHookRuntime(),
8730
8867
  await checkRepositoryBinding(),
8731
8868
  checkManagedHook("pre-commit"),
@@ -8780,11 +8917,11 @@ function registerDoctorCommands(program2, dependencies = {}) {
8780
8917
 
8781
8918
  // src/commands/moves.ts
8782
8919
  import { existsSync as existsSync9, mkdirSync as mkdirSync5, unlinkSync as unlinkSync5, writeFileSync as writeFileSync4 } from "fs";
8783
- import { join as join10 } from "path";
8920
+ import { join as join11 } from "path";
8784
8921
 
8785
8922
  // src/flusher.ts
8786
8923
  import { createReadStream, renameSync as renameSync3, statSync as statSync3, unlinkSync as unlinkSync4 } from "fs";
8787
- import { dirname as dirname4, join as join9 } from "path";
8924
+ import { dirname as dirname4, join as join10 } from "path";
8788
8925
 
8789
8926
  // src/dead-letter.ts
8790
8927
  import { createHash as createHash4, randomBytes as randomBytes4 } from "crypto";
@@ -8801,16 +8938,16 @@ import {
8801
8938
  rmSync as rmSync3,
8802
8939
  writeFileSync as writeFileSync3
8803
8940
  } from "fs";
8804
- import { dirname as dirname3, join as join8 } from "path";
8941
+ import { dirname as dirname3, join as join9 } from "path";
8805
8942
  var DIRECTORY_MODE = 448;
8806
8943
  var FILE_MODE = 384;
8807
8944
  var DEAD_LETTER_DIRNAME = "dead-letter";
8808
8945
  function deadLetterDirectoryForRotation(flushingPath) {
8809
- return join8(dirname3(flushingPath), DEAD_LETTER_DIRNAME);
8946
+ return join9(dirname3(flushingPath), DEAD_LETTER_DIRNAME);
8810
8947
  }
8811
8948
  function deadLetterPathForRawLine(flushingPath, rawLine) {
8812
8949
  const quarantineId = createHash4("sha256").update(rawLine).digest("hex");
8813
- return join8(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
8950
+ return join9(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
8814
8951
  }
8815
8952
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
8816
8953
  const directory = deadLetterDirectoryForRotation(flushingPath);
@@ -8824,7 +8961,7 @@ function persistDeadLetter(directory, path, quarantineId, record3, persistDirect
8824
8961
  persistDirectory(directory);
8825
8962
  return;
8826
8963
  }
8827
- const temporaryPath = join8(
8964
+ const temporaryPath = join9(
8828
8965
  directory,
8829
8966
  `.${quarantineId}.${String(process.pid)}.${randomBytes4(8).toString("hex")}.tmp`
8830
8967
  );
@@ -8856,7 +8993,7 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
8856
8993
  reason,
8857
8994
  move
8858
8995
  };
8859
- const path = join8(directory, `${record3.quarantineId}.json`);
8996
+ const path = join9(directory, `${record3.quarantineId}.json`);
8860
8997
  persistDeadLetter(directory, path, record3.quarantineId, record3, persistDirectory);
8861
8998
  return record3;
8862
8999
  }
@@ -9251,7 +9388,7 @@ async function flushOnce() {
9251
9388
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
9252
9389
  }
9253
9390
  var flushInFlight;
9254
- var FLUSH_LOCK_PATH = join9(dirname4(JOURNAL_DIR), ".flush.lock");
9391
+ var FLUSH_LOCK_PATH = join10(dirname4(JOURNAL_DIR), ".flush.lock");
9255
9392
  var FLUSH_LOCK_TIMEOUT_MS = 250;
9256
9393
  function isFlushLockContended(error) {
9257
9394
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -9383,18 +9520,18 @@ function registerMovesCommands(program2) {
9383
9520
  }
9384
9521
  });
9385
9522
  moves.command("bind").description("Pin the current directory to an org via .prim/workspace.json").requiredOption("--orgId <orgId>", "Convex organization id").action((opts) => {
9386
- const dir = join10(process.cwd(), ".prim");
9523
+ const dir = join11(process.cwd(), ".prim");
9387
9524
  if (!existsSync9(dir)) {
9388
9525
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
9389
9526
  }
9390
- const file = join10(process.cwd(), WORKSPACE_FILE);
9527
+ const file = join11(process.cwd(), WORKSPACE_FILE);
9391
9528
  writeFileSync4(file, JSON.stringify({ orgId: opts.orgId, boundAt: Date.now() }, null, 2), {
9392
9529
  mode: FILE_MODE2
9393
9530
  });
9394
9531
  console.log(`[prim] bound ${process.cwd()} to org ${opts.orgId}`);
9395
9532
  });
9396
9533
  moves.command("drop").description("Remove the .prim/workspace.json binding from the cwd").action(() => {
9397
- const file = join10(process.cwd(), WORKSPACE_FILE);
9534
+ const file = join11(process.cwd(), WORKSPACE_FILE);
9398
9535
  if (!existsSync9(file)) {
9399
9536
  console.log("[prim] no workspace binding in cwd");
9400
9537
  return;
@@ -9532,7 +9669,7 @@ import {
9532
9669
  unlinkSync as unlinkSync6,
9533
9670
  writeFileSync as writeFileSync5
9534
9671
  } from "fs";
9535
- import { join as join11 } from "path";
9672
+ import { join as join12 } from "path";
9536
9673
  var DIR_MODE2 = 448;
9537
9674
  var FILE_MODE3 = 384;
9538
9675
  function ensureDir() {
@@ -9541,7 +9678,7 @@ function ensureDir() {
9541
9678
  }
9542
9679
  }
9543
9680
  function markerPath(sessionId) {
9544
- return join11(SESSIONS_DIR, `${sessionId}.json`);
9681
+ return join12(SESSIONS_DIR, `${sessionId}.json`);
9545
9682
  }
9546
9683
  function registerSessionCommands(program2) {
9547
9684
  const session = program2.command("session").description("Decision Event Pipeline \u2014 session binding markers");
@@ -9569,7 +9706,7 @@ function registerSessionCommands(program2) {
9569
9706
  for (const f of files) {
9570
9707
  const sessionId = f.replace(/\.json$/, "");
9571
9708
  try {
9572
- const m = JSON.parse(readFileSync7(join11(SESSIONS_DIR, f), "utf-8"));
9709
+ const m = JSON.parse(readFileSync7(join12(SESSIONS_DIR, f), "utf-8"));
9573
9710
  console.log(`${sessionId} org=${m.orgId}`);
9574
9711
  } catch {
9575
9712
  }
@@ -9589,7 +9726,7 @@ function registerSessionCommands(program2) {
9589
9726
  // src/commands/setup.ts
9590
9727
  import { spawnSync as spawnSync2 } from "child_process";
9591
9728
  import { existsSync as existsSync11, readFileSync as readFileSync8 } from "fs";
9592
- import { join as join12 } from "path";
9729
+ import { join as join13 } from "path";
9593
9730
  var EXIT_INCOMPLETE = 1;
9594
9731
  var EXIT_USAGE3 = 2;
9595
9732
  var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
@@ -9727,7 +9864,7 @@ function detectProjectConflicts(agent, run, globalHooksActive) {
9727
9864
  let preCommit;
9728
9865
  try {
9729
9866
  const root = gitToplevel();
9730
- const path = root && join12(root, ".git", "hooks", "pre-commit");
9867
+ const path = root && join13(root, ".git", "hooks", "pre-commit");
9731
9868
  if (path && existsSync11(path)) preCommit = readFileSync8(path, "utf-8");
9732
9869
  } catch {
9733
9870
  }
@@ -10534,9 +10671,9 @@ import { readFileSync as readFileSync10 } from "fs";
10534
10671
 
10535
10672
  // src/daemon/health.ts
10536
10673
  import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync7, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
10537
- import { dirname as dirname6, join as join13 } from "path";
10674
+ import { dirname as dirname6, join as join14 } from "path";
10538
10675
  var HEARTBEAT_FRESH_MS = 9e4;
10539
- var DAEMON_HEALTH_PATH = join13(primConfigDirectory(), "daemon-health.json");
10676
+ var DAEMON_HEALTH_PATH = join14(primConfigDirectory(), "daemon-health.json");
10540
10677
 
10541
10678
  // src/lib/background-flush.ts
10542
10679
  function record2(value) {