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

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
@@ -22,7 +22,7 @@ import {
22
22
  } from "./chunk-2EKPBZNA.js";
23
23
  import {
24
24
  requireDurableIngestAcknowledgement
25
- } from "./chunk-IDMLJ4TM.js";
25
+ } from "./chunk-4CO4A6NR.js";
26
26
  import {
27
27
  checkAffectedDecisions,
28
28
  daemonOrDirectGet,
@@ -60,15 +60,18 @@ import {
60
60
  import {
61
61
  RUN_ID,
62
62
  demoCommand,
63
+ demoDiagnosticCommand,
64
+ demoWelcomeCommand,
63
65
  exclusionPath,
64
66
  finishOnboarding,
65
67
  lockRun,
68
+ lockRunAsync,
66
69
  onboardingFinished,
67
70
  pendingRuns,
68
71
  prepareRun,
69
72
  readDemoJson,
70
73
  saveRun
71
- } from "./chunk-6WCBVSND.js";
74
+ } from "./chunk-7GSBXHK4.js";
72
75
  import {
73
76
  MS_PER_SECOND,
74
77
  deliveryBacklogState,
@@ -77,7 +80,7 @@ import {
77
80
  formatStatusline,
78
81
  formatTeammates,
79
82
  repositoryBindingDiagnosticLabel
80
- } from "./chunk-5HFTJEA6.js";
83
+ } from "./chunk-72CQVK4E.js";
81
84
  import {
82
85
  bold,
83
86
  boundedHealthError,
@@ -91,13 +94,18 @@ import {
91
94
  isDecisionRescopeResponse,
92
95
  isDecisionStageSuccessResponse,
93
96
  isDecisionSupersedeRequest,
97
+ isDemoCompleteRequest,
98
+ isDemoResolveRequest,
99
+ isDemoRunRequest,
100
+ isDemoStartRequest,
101
+ isDemoStatusResponse,
94
102
  isGitHubInstallIntentStartErrorResponse,
95
103
  isGitHubInstallIntentStartResponse,
96
104
  isGitHubInstallIntentStatusResponse,
97
105
  isMoveIngestRequest,
98
106
  isReconcileResolutionResponse,
99
107
  stripAnsi
100
- } from "./chunk-GSBHBU7N.js";
108
+ } from "./chunk-FFYZ3XMX.js";
101
109
  import {
102
110
  CliManagementResponseError,
103
111
  HttpError,
@@ -180,7 +188,7 @@ import {
180
188
 
181
189
  // src/index.ts
182
190
  import { readFileSync as readFileSync11 } from "fs";
183
- import { dirname as dirname7, resolve as resolve4 } from "path";
191
+ import { dirname as dirname7, resolve as resolve5 } from "path";
184
192
  import { fileURLToPath as fileURLToPath2 } from "url";
185
193
  import { Command } from "commander";
186
194
  import updateNotifier from "update-notifier";
@@ -191,8 +199,8 @@ function isNonInteractive(globals) {
191
199
  }
192
200
  async function askConfirmation(question, output = process.stdout) {
193
201
  if (!process.stdin.isTTY) return false;
194
- const { createInterface } = await import("readline/promises");
195
- const rl = createInterface({ input: process.stdin, output });
202
+ const { createInterface: createInterface2 } = await import("readline/promises");
203
+ const rl = createInterface2({ input: process.stdin, output });
196
204
  try {
197
205
  const answer = await rl.question(`${question} [y/N] `);
198
206
  const normalized = answer.trim().toLowerCase();
@@ -1063,8 +1071,8 @@ ${verificationUrl}`);
1063
1071
  const state = base64url(randomBytes2(16));
1064
1072
  const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
1065
1073
  let settle;
1066
- const outcome = new Promise((resolve5) => {
1067
- settle = resolve5;
1074
+ const outcome = new Promise((resolve6) => {
1075
+ settle = resolve6;
1068
1076
  });
1069
1077
  const server = createServer((req, res) => {
1070
1078
  const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
@@ -1078,12 +1086,12 @@ ${verificationUrl}`);
1078
1086
  res.end(page.html, () => settle(page.result));
1079
1087
  });
1080
1088
  try {
1081
- await new Promise((resolve5, reject) => {
1089
+ await new Promise((resolve6, reject) => {
1082
1090
  const onError = (err) => reject(err);
1083
1091
  server.once("error", onError);
1084
1092
  server.listen(CALLBACK_PORT, LOCALHOST, () => {
1085
1093
  server.removeListener("error", onError);
1086
- resolve5();
1094
+ resolve6();
1087
1095
  });
1088
1096
  });
1089
1097
  } catch (err) {
@@ -1908,11 +1916,12 @@ function registerHooksCommands(program2) {
1908
1916
  "Note: Husky detected but stdin is not a TTY \u2014 falling back to .git/hooks. Pass --yes for Husky or --non-interactive to fail fast."
1909
1917
  );
1910
1918
  } else if (await askConfirmation(
1911
- "Husky detected. Install prim hooks into .husky/ instead of .git/hooks/?"
1919
+ "Husky detected. Install prim hooks into .husky/ instead of .git/hooks/?",
1920
+ process.stderr
1912
1921
  )) {
1913
1922
  return installHooks(gitRoot, "husky");
1914
1923
  } else {
1915
- console.log("Falling back to .git/hooks install.");
1924
+ console.error("Falling back to .git/hooks install.");
1916
1925
  }
1917
1926
  return installHooks(gitRoot, "git-hooks");
1918
1927
  }
@@ -2254,7 +2263,7 @@ function resolveScope(input) {
2254
2263
  console.error(`[prim] unknown --scope "${input}" (expected: user or project)`);
2255
2264
  process.exit(1);
2256
2265
  }
2257
- var TRUST_NOTICE = "[prim] Codex requires hook trust: run `/hooks` in Codex to review and trust these hooks (or start Codex with --dangerously-bypass-hook-trust). Until trusted, the hooks will not fire.";
2266
+ 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.";
2258
2267
  function registerCodexCommands(program2) {
2259
2268
  const codex = program2.command("codex").description("Manage the prim Codex integration (capture, gate, ingest, presence)");
2260
2269
  codex.command("install").description("Register the prim hooks in Codex's hooks.json (user scope by default)").option(
@@ -2287,7 +2296,7 @@ function registerCodexCommands(program2) {
2287
2296
  codex.command("status").description("Report whether each prim surface (gate, capture) is installed per scope").action(() => {
2288
2297
  const result = performStatus3();
2289
2298
  const mark = (b) => b ? "\u2713" : "\u2717";
2290
- const line = (label, s) => `[prim] ${label}: gate ${mark(s.gate)} \xB7 capture ${mark(s.capture)} (${s.path})`;
2299
+ const line = (label2, s) => `[prim] ${label2}: gate ${mark(s.gate)} \xB7 capture ${mark(s.capture)} (${s.path})`;
2291
2300
  console.error(`${line("user", result.user)}
2292
2301
  ${line("project", result.project)}`);
2293
2302
  const uncovered = uncoveredWorktreeHooks(result);
@@ -2317,7 +2326,7 @@ async function runPinnedEnsure(options) {
2317
2326
  npm_config_fetch_retry_maxtimeout: "5000",
2318
2327
  npm_config_fetch_timeout: "15000"
2319
2328
  };
2320
- return await new Promise((resolve5) => {
2329
+ return await new Promise((resolve6) => {
2321
2330
  let settled = false;
2322
2331
  let child;
2323
2332
  try {
@@ -2327,7 +2336,7 @@ async function runPinnedEnsure(options) {
2327
2336
  { env, stdio: "ignore" }
2328
2337
  );
2329
2338
  } catch {
2330
- resolve5(false);
2339
+ resolve6(false);
2331
2340
  return;
2332
2341
  }
2333
2342
  const timer = setTimeout(() => {
@@ -2338,7 +2347,7 @@ async function runPinnedEnsure(options) {
2338
2347
  if (settled) return;
2339
2348
  settled = true;
2340
2349
  clearTimeout(timer);
2341
- resolve5(result);
2350
+ resolve6(result);
2342
2351
  };
2343
2352
  timer.unref();
2344
2353
  child.once("error", () => finish(false));
@@ -2695,10 +2704,10 @@ else
2695
2704
  fi
2696
2705
  `;
2697
2706
  }
2698
- function assertRegularFile(path, label) {
2707
+ function assertRegularFile(path, label2) {
2699
2708
  const stat = lstatIfPresent2(path);
2700
2709
  if (stat && !stat.isFile()) {
2701
- throw new Error(`refusing to remove non-file ${label} at ${path}`);
2710
+ throw new Error(`refusing to remove non-file ${label2} at ${path}`);
2702
2711
  }
2703
2712
  }
2704
2713
  function lstatIfPresent2(path) {
@@ -2727,11 +2736,11 @@ function assertDriftHealClaim(path) {
2727
2736
  }
2728
2737
  assertRegularFile(join4(path, DRIFT_HEAL_CLAIM_OWNER), "daemon drift-heal claim owner");
2729
2738
  }
2730
- function assertExactFile(path, expected, label) {
2739
+ function assertExactFile(path, expected, label2) {
2731
2740
  if (!lstatIfPresent2(path)) return;
2732
- assertRegularFile(path, label);
2741
+ assertRegularFile(path, label2);
2733
2742
  if (readFileSync3(path, "utf8") !== expected) {
2734
- throw new Error(`refusing to remove unrecognized ${label} at ${path}`);
2743
+ throw new Error(`refusing to remove unrecognized ${label2} at ${path}`);
2735
2744
  }
2736
2745
  }
2737
2746
  function assertOwnedDaemonRuntime(options) {
@@ -2985,12 +2994,12 @@ function launchdPaths(options = {}) {
2985
2994
  const home = options.homeDir ?? homedir3();
2986
2995
  const configDir = primConfigDirectory(options);
2987
2996
  const uid = options.uid ?? process.getuid?.();
2988
- const label = options.label ?? LAUNCHD_LABEL;
2997
+ const label2 = options.label ?? LAUNCHD_LABEL;
2989
2998
  if (uid === void 0) throw new Error("cannot determine uid for launchd user domain");
2990
2999
  return {
2991
3000
  domainTarget: `gui/${uid}`,
2992
- serviceTarget: `gui/${uid}/${label}`,
2993
- plistPath: join4(home, "Library", "LaunchAgents", `${label}.plist`),
3001
+ serviceTarget: `gui/${uid}/${label2}`,
3002
+ plistPath: join4(home, "Library", "LaunchAgents", `${label2}.plist`),
2994
3003
  logPath: join4(configDir, "daemon.log")
2995
3004
  };
2996
3005
  }
@@ -3022,11 +3031,11 @@ function getLaunchdService(options = {}) {
3022
3031
  )
3023
3032
  );
3024
3033
  }
3025
- function atomicWrite2(path, content, mode, validate) {
3034
+ function atomicWrite2(path, content, mode, validate2) {
3026
3035
  try {
3027
3036
  if (readFileSync3(path, "utf8") === content) {
3028
3037
  chmodSync(path, mode);
3029
- validate?.(path, COMMAND_TIMEOUT_MS);
3038
+ validate2?.(path, COMMAND_TIMEOUT_MS);
3030
3039
  return false;
3031
3040
  }
3032
3041
  } catch {
@@ -3035,7 +3044,7 @@ function atomicWrite2(path, content, mode, validate) {
3035
3044
  const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
3036
3045
  writeFileSync2(temp, content, { encoding: "utf8", mode, flag: "wx" });
3037
3046
  try {
3038
- validate?.(temp, COMMAND_TIMEOUT_MS);
3047
+ validate2?.(temp, COMMAND_TIMEOUT_MS);
3039
3048
  renameSync(temp, path);
3040
3049
  } catch (error) {
3041
3050
  rmSync(temp, { force: true });
@@ -3322,10 +3331,10 @@ function launchAgentProgram(plist) {
3322
3331
  if (plist.split(PLIST_LABEL_KEY).length !== 2 || plist.split(PLIST_PROGRAM_KEY).length !== 2) {
3323
3332
  return void 0;
3324
3333
  }
3325
- const label = PLIST_LABEL_RE.exec(plist)?.[1];
3334
+ const label2 = PLIST_LABEL_RE.exec(plist)?.[1];
3326
3335
  const program2 = PLIST_PROGRAM_RE.exec(plist)?.[1];
3327
- if (label === void 0 || program2 === void 0) return void 0;
3328
- const decodedLabel = xmlUnescape(label);
3336
+ if (label2 === void 0 || program2 === void 0) return void 0;
3337
+ const decodedLabel = xmlUnescape(label2);
3329
3338
  const decodedProgram = xmlUnescape(program2);
3330
3339
  return decodedLabel === void 0 || decodedProgram === void 0 ? void 0 : { label: decodedLabel, program: decodedProgram };
3331
3340
  }
@@ -3600,7 +3609,7 @@ function clearStaleArtifacts() {
3600
3609
  }
3601
3610
  }
3602
3611
  function sleep(ms) {
3603
- return new Promise((resolve5) => setTimeout(resolve5, ms));
3612
+ return new Promise((resolve6) => setTimeout(resolve6, ms));
3604
3613
  }
3605
3614
  function spawnDaemon(options) {
3606
3615
  const file = binFile(DAEMON_BIN);
@@ -4321,8 +4330,8 @@ function truncate(s, max) {
4321
4330
  }
4322
4331
  return `${safe.slice(0, max - 1)}\u2026`;
4323
4332
  }
4324
- function bracketed(label) {
4325
- return `[${terminalSafeLine(label)}]`;
4333
+ function bracketed(label2) {
4334
+ return `[${terminalSafeLine(label2)}]`;
4326
4335
  }
4327
4336
  function knowledgeRow(files, contexts, triggerFile, triggerContextName) {
4328
4337
  const tokens = [];
@@ -4642,11 +4651,11 @@ function formatRecentHuman(result) {
4642
4651
  }
4643
4652
  return `[prim] recent \xB7 ${terminalSafeLine(result.author.name)} \xB7 0 decisions`;
4644
4653
  }
4645
- const label = result.author === void 0 ? "recent" : `recent \xB7 ${terminalSafeLine(result.author.name)}`;
4654
+ const label2 = result.author === void 0 ? "recent" : `recent \xB7 ${terminalSafeLine(result.author.name)}`;
4646
4655
  if (result.decisions.length === 0) {
4647
4656
  return "[prim] recent \xB7 0 decisions";
4648
4657
  }
4649
- const header = `[prim] ${label} \xB7 ${String(result.decisions.length)} decision(s)`;
4658
+ const header = `[prim] ${label2} \xB7 ${String(result.decisions.length)} decision(s)`;
4650
4659
  const hint = remainingHint(result);
4651
4660
  const lines = [hint === void 0 ? header : `${header} \xB7 ${hint}`];
4652
4661
  for (const row of result.decisions) {
@@ -5971,11 +5980,11 @@ function pushContexts(lines, contexts) {
5971
5980
  lines.push(` - ${terminalSafeLine(ctx.name)}`);
5972
5981
  }
5973
5982
  }
5974
- function pushEdges(lines, label, arrow, nodes) {
5983
+ function pushEdges(lines, label2, arrow, nodes) {
5975
5984
  if (nodes.length === 0) {
5976
5985
  return;
5977
5986
  }
5978
- lines.push(` ${label} (${String(nodes.length)}):`);
5987
+ lines.push(` ${label2} (${String(nodes.length)}):`);
5979
5988
  for (const node of nodes) {
5980
5989
  lines.push(` ${arrow} ${describeNode(node)}`);
5981
5990
  }
@@ -6610,7 +6619,32 @@ function registerDecisionsCommands(program2) {
6610
6619
  }
6611
6620
 
6612
6621
  // src/commands/demo.ts
6613
- import { createPatch } from "diff";
6622
+ import { createHash as createHash3 } from "crypto";
6623
+ import { resolve as resolve3 } from "path";
6624
+ import { createInterface } from "readline/promises";
6625
+ import { diffLines } from "diff";
6626
+
6627
+ // src/demo/api.ts
6628
+ async function demoApi(action, body) {
6629
+ const valid = action === "start" ? isDemoStartRequest : action === "resolve" ? isDemoResolveRequest : action === "complete" ? isDemoCompleteRequest : isDemoRunRequest;
6630
+ if (!valid(body)) throw new Error("Invalid demo request");
6631
+ return validate(
6632
+ await getClient().post(`/api/cli/demo/${action}`, body, {
6633
+ signal: AbortSignal.timeout(2e4)
6634
+ })
6635
+ );
6636
+ }
6637
+ async function demoStatus(runId) {
6638
+ if (!/^[a-zA-Z0-9]{1,64}$/u.test(runId)) throw new Error("Invalid server demo identity");
6639
+ return validate(
6640
+ await getClient().get(`/api/cli/demo/${runId}`, { signal: AbortSignal.timeout(2e4) })
6641
+ );
6642
+ }
6643
+ function validate(value) {
6644
+ if (!isDemoStatusResponse(value))
6645
+ throw new Error("Invalid demo response; no sample write applied");
6646
+ return value;
6647
+ }
6614
6648
 
6615
6649
  // src/demo/sandbox.ts
6616
6650
  import {
@@ -6665,13 +6699,22 @@ var SAMPLE_FILES = {
6665
6699
  "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"
6666
6700
  };
6667
6701
  var WARNING_EDIT = 'export const loadOrders = () => fetch("/orders");\n';
6668
- var BLOCKED_EDIT = 'export const saveOrder = (order: unknown) => localStorage.setItem("order", JSON.stringify(order));\n';
6669
6702
  var REPOSITORY_EDIT = 'import { orders } from "./shared";\nexport const saveOrder = (order: unknown) => orders.save(order);\n';
6670
6703
 
6704
+ // src/demo/story.ts
6705
+ var DEMO_TASK = "Implement CSV export for customer records, including name and email.";
6706
+ var DEMO_ORIGINAL = "Exclude customer email addresses from CSV exports";
6707
+ var DEMO_REPLACEMENT = "Allow customer names and email addresses in CSV exports";
6708
+ var DEMO_INITIAL = '// Fictional customer export project.\nexport const customerCsv = "";\n';
6709
+ var DEMO_ADHERE = '// Fictional customer export project.\nexport const customerCsv = "name\\nAvery";\n';
6710
+ var DEMO_SUPERSEDE = '// Fictional customer export project.\nexport const customerCsv = "name,email\\nAvery,avery@example.invalid";\n';
6711
+
6671
6712
  // src/demo/sandbox.ts
6672
6713
  var decisionBytes = (adopted) => `${JSON.stringify(adopted ? SAMPLE_DECISIONS : SAMPLE_DECISIONS.slice(0, 1), null, 2)}
6673
6714
  `;
6674
6715
  function allowedFiles(run) {
6716
+ if (run.version === 2)
6717
+ return { ".owner": [run.id], "customers.ts": [DEMO_INITIAL, DEMO_ADHERE, DEMO_SUPERSEDE] };
6675
6718
  return {
6676
6719
  ".owner": [run.id],
6677
6720
  "note.md": [SAMPLE_NOTE],
@@ -6708,12 +6751,13 @@ function createSandbox(run) {
6708
6751
  saveRun(run);
6709
6752
  }
6710
6753
  const root = inspectSandbox(run);
6711
- for (const [name, content] of Object.entries({
6754
+ const files = run.version === 2 ? { ".owner": run.id, "customers.ts": DEMO_INITIAL } : {
6712
6755
  ".owner": run.id,
6713
6756
  "note.md": SAMPLE_NOTE,
6714
6757
  ...SAMPLE_FILES,
6715
6758
  "decisions.json": decisionBytes(false)
6716
- })) {
6759
+ };
6760
+ for (const [name, content] of Object.entries(files)) {
6717
6761
  const path = join6(root, name);
6718
6762
  if (!existsSync5(path)) atomicWriteFile(path, content, { mode: 384 });
6719
6763
  }
@@ -6745,347 +6789,378 @@ function cleanSandbox(run) {
6745
6789
  }
6746
6790
 
6747
6791
  // src/commands/demo.ts
6748
- var intro = "SIMULATED TOUR \u2014 fictional Decisions and scripted verdicts; no live ingestion or enforcement check.";
6749
- var handoff = "Sample files removed. Next: ask your agent to propose one real Decision from your project's shared memory for your individual approval.";
6750
- 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.";
6751
- var completionReceipt = [
6752
- "Extracted a Decision with supporting evidence",
6753
- "Adopted a Decision with your confirmation",
6754
- "Surfaced a warning and allowed the edit",
6755
- "Refused a conflicting write",
6756
- "Applied the compliant implementation"
6757
- ];
6758
- function resultFor2(run) {
6759
- const action = run.stage === "prepared" ? "start" : run.stage === "proposal" ? "confirm" : "resolve";
6760
- const done = run.stage === "completed" || run.stage === "skipped";
6761
- return {
6762
- simulated: true,
6763
- runId: run.id,
6764
- stage: run.stage,
6765
- ...done ? { message: handoff, nextAction: `prim welcome${run.binding ? " --capture-excluded" : ""}` } : {
6766
- nextAction: demoCommand(run, action, action === "resolve" ? "repository" : void 0),
6767
- skipAction: demoCommand(run, "skip")
6768
- },
6769
- ...run.sandbox ? { sandbox: run.sandbox.path } : {},
6770
- ...run.stage === "conflict" ? { retryAction: demoCommand(run, "resolve", "local-storage") } : {}
6771
- };
6792
+ var printJson2 = (value) => process.stdout.write(`${JSON.stringify(value)}
6793
+ `);
6794
+ var digest = (bytes) => createHash3("sha256").update(bytes).digest("hex");
6795
+ var captureNotice = "Start a new agent session to resume passive capture. Explicitly approved real Decisions still work here.";
6796
+ var label = "**Fictional project \xB7 real conflict check**";
6797
+ var diagram = (value) => `
6798
+ \`\`\`text
6799
+ ${value}
6800
+ \`\`\``;
6801
+ var safeMarkdown = (value) => terminalSafeLine(value).replace(/[\\`*_{}[\]<>]/gu, "\\$&");
6802
+ function compactDiff(before, after) {
6803
+ return diffLines(before, after).filter((part) => part.added || part.removed).map(
6804
+ (part) => part.value.trimEnd().split("\n").map((line) => `${part.added ? "+" : "-"} ${line}`).join("\n")
6805
+ ).join("\n");
6772
6806
  }
6773
6807
  function demoTrustGuidance(agent) {
6774
6808
  if (agent === "codex")
6775
- return "Trust the installed prim hooks with /hooks in Codex, then retry the exact nextAction.";
6809
+ 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 and inspect hook errors.";
6776
6810
  if (agent === "hermes")
6777
6811
  return "Approve the installed prim hooks when Hermes prompts, then retry the exact nextAction.";
6778
6812
  if (agent === "cursor")
6779
6813
  return "Trust this Cursor workspace and activate its installed hooks, then retry the exact nextAction.";
6780
6814
  return "Activate the installed prim hooks in your agent, then retry the exact nextAction.";
6781
6815
  }
6782
- function consumeAcknowledgment(run, action, choice) {
6783
- if (run.terminal) return Boolean(process.stdin.isTTY && process.stderr.isTTY);
6816
+ function consumeAcknowledgment(run, action, choice, reason) {
6817
+ if (run.terminal)
6818
+ return process.stdin.isTTY && process.stderr.isTTY ? void 0 : "terminal-required";
6784
6819
  const ack = run.acknowledgment;
6785
6820
  run.acknowledgment = void 0;
6786
6821
  saveRun(run);
6787
- if (!run.binding || !ack || ack.command !== demoCommand(run, action, choice)) return false;
6822
+ if (!run.binding || !ack) return "acknowledgment-missing";
6823
+ if (ack.command !== demoCommand(run, action, choice, reason)) return "command-mismatch";
6788
6824
  const age = Date.now() - ack.at;
6789
- if (!Number.isFinite(age) || age < 0 || age > 3e4) return false;
6825
+ if (!Number.isFinite(age) || age < 0 || age > 3e4) return "acknowledgment-expired";
6790
6826
  try {
6791
6827
  const exclusion = readDemoJson(exclusionPath(run.binding));
6792
- return typeof exclusion.runId === "string" && RUN_ID.test(exclusion.runId);
6828
+ return typeof exclusion.runId === "string" && RUN_ID.test(exclusion.runId) ? void 0 : "exclusion-invalid";
6793
6829
  } catch {
6794
- return false;
6830
+ return "exclusion-missing";
6795
6831
  }
6796
6832
  }
6797
- function narrateDecision(index) {
6798
- const item = SAMPLE_DECISIONS[index];
6799
- const status = index === 1 ? "proposed adoption, awaiting confirmation" : item.stage;
6800
- const source = index === 1 ? "Fictional authoring proposal" : item.source;
6801
- process.stderr.write(
6802
- `
6803
- Decision: ${item.decision}
6804
- Status: ${status} (sample)
6805
- Source: ${source}
6806
- Rationale: ${item.rationale}
6807
- Scope: ${item.files.join(", ")}
6808
- Alternatives rejected: ${item.alternativesRejected.join("; ")}
6809
- `
6810
- );
6811
- if (index === 0) {
6812
- const extracted = SAMPLE_DECISIONS[0];
6813
- process.stderr.write(
6814
- `Source evidence:
6815
- ${extracted.evidence.map((quote) => ` "${quote}"`).join("\n")}
6816
- Scope basis: ${extracted.scopeBasis}
6817
- `
6818
- );
6819
- }
6820
- }
6821
- function narrateBlockedAttempt(unchanged) {
6822
- process.stderr.write(`
6823
- ${bold(color("BLOCKED \u2014 file unchanged (simulated)", "red"))}
6824
- `);
6825
- process.stderr.write(
6826
- `Attempt: save the order with localStorage.setItem(...).
6827
- Decision (adopted sample): ${SAMPLE_DECISIONS[1].decision}
6828
- Conflict: direct storage bypasses the shared repository and its validation.
6829
- Outcome: this scenario refuses the proposed write.
6830
- `
6831
- );
6832
- process.stderr.write(createPatch("orders.ts (refused proposal)", unchanged, BLOCKED_EDIT));
6833
- process.stderr.write(
6834
- `Proof: orders.ts is unchanged. Actual file:
6835
- ${unchanged}
6836
- Next: save through orders.save(...) to preserve repository validation.
6837
- `
6838
- );
6833
+ function resultFor2(run) {
6834
+ const complete = run.stage === "completed" || run.stage === "skipped";
6835
+ return {
6836
+ fictional: true,
6837
+ evaluation: "live",
6838
+ runId: run.id,
6839
+ stage: run.stage,
6840
+ ...run.server && run.stage !== "skipped" ? { server: run.server } : {},
6841
+ ...run.sandbox ? { sandbox: run.sandbox.path } : {},
6842
+ skipAction: demoCommand(run, "skip"),
6843
+ statusAction: demoCommand(run, "status"),
6844
+ ...complete ? { nextAction: demoWelcomeCommand(run) } : {}
6845
+ };
6839
6846
  }
6840
- function narrateCompletion(run) {
6841
- process.stderr.write(`
6842
- ${bold(color("WALKTHROUGH COMPLETE \u2014 simulated", "green"))}
6843
- `);
6844
- process.stderr.write(`${completionReceipt.map((item) => `\u2713 ${item}`).join("\n")}
6845
- `);
6846
- process.stderr.write(`${handoff}
6847
- ${run.terminal ? "" : `${captureNotice}
6848
- `}`);
6847
+ function present(run) {
6848
+ if (run.stage === "prepared") return "Tour ready. Run nextAction to check session isolation.";
6849
+ if (run.stage === "skipped") return "Tour skipped. Owned sample files removed.";
6850
+ if (run.stage === "prompt")
6851
+ return `${label}
6852
+
6853
+ Imagine you\u2019re a new engineer joining a team. In this story, you previously authored a Decision; now experience it as the new engineer. We\u2019ll email the outcome to your signed-in address.
6854
+ ${diagram("[1 Enter task] \u2192 [2 Your Decision stops it] \u2192 [3 Choose \u2192 Email]")}
6855
+
6856
+ Enter this prompt in this chat:
6857
+
6858
+ \`\`\`text
6859
+ ${DEMO_TASK}
6860
+ \`\`\``;
6861
+ if (run.stage === "conflict")
6862
+ return `${label}
6863
+
6864
+ **YOUR DECISION STOPPED THIS**
6865
+ ${diagram("CSV export [name, email]\n \u2502\n \u2715 email excluded\n \u2502\n customers.ts unchanged")}
6866
+
6867
+ **${DEMO_ORIGINAL}**
6868
+ Fictional prior author: ${safeMarkdown(run.server?.authorName ?? "you")}
6869
+
6870
+ \`\`\`ts
6871
+ ${readSample(run, "customers.ts").trimEnd()}
6872
+ \`\`\`
6873
+
6874
+ Choose **Adhere** (export names only) or **Supersede** with **${DEMO_REPLACEMENT}** and your short reason.`;
6875
+ if (run.stage === "completed" || run.stage === "cleanup") {
6876
+ const choice = run.server?.choice;
6877
+ const after = choice === "adhere" ? DEMO_ADHERE : DEMO_SUPERSEDE;
6878
+ return `${label}
6879
+
6880
+ **PASS \u2014 CSV export implemented**
6881
+ ${diagram(`CSV [${choice === "adhere" ? "name" : "name, email"}] \u2192 CHECK PASSED \u2192 IMPLEMENTED
6882
+ Your Decision \u2192 ${choice === "adhere" ? "preserved" : "replacement + your reason"} \u2192 EMAIL ${run.server?.email.toUpperCase()}`)}
6883
+
6884
+ \`\`\`diff
6885
+ ${compactDiff(DEMO_INITIAL, after)}
6886
+ \`\`\`
6887
+
6888
+ ${run.stage === "cleanup" ? "Sample cleanup still needs attention." : "Owned sample files removed."} ${run.server?.email === "accepted" ? "The provider accepted the email; inbox delivery is not confirmed." : "Queued is not inbox delivery."}
6889
+
6890
+ ${run.binding ? captureNotice : "Ready for your real Decisions."}`;
6891
+ }
6892
+ return `${label}
6893
+
6894
+ Checked edit saved; email finalization is pending. Retry the same resolution to finish. No second email will be queued.`;
6895
+ }
6896
+ function handoff(run) {
6897
+ const result = { ...resultFor2(run), presentation: present(run) };
6898
+ if (run.stage === "prepared") return { ...result, nextAction: demoCommand(run, "start") };
6899
+ if (run.stage === "prompt")
6900
+ return { ...result, awaitUserPrompt: DEMO_TASK, attemptAction: demoCommand(run, "attempt") };
6901
+ if (run.stage === "conflict")
6902
+ return {
6903
+ ...result,
6904
+ choices: {
6905
+ adhere: demoCommand(run, "resolve", "adhere"),
6906
+ supersede: {
6907
+ command: demoCommand(run, "resolve", "supersede"),
6908
+ requiredArgument: "--reason <user-provided reason>",
6909
+ replacement: DEMO_REPLACEMENT
6910
+ }
6911
+ }
6912
+ };
6913
+ if (run.server?.choice && !["completed", "skipped"].includes(run.stage))
6914
+ return {
6915
+ ...result,
6916
+ nextAction: demoCommand(run, "resolve", run.server.choice, run.server.reason)
6917
+ };
6918
+ return result;
6919
+ }
6920
+ function requireResolution(choice, reason) {
6921
+ if (choice !== "adhere" && choice !== "supersede") throw new Error("Choose adhere or supersede");
6922
+ if (choice === "supersede" && (!reason?.trim() || reason.length > 500))
6923
+ throw new Error("Supersession requires your short reason (1\u2013500 characters)");
6924
+ if (choice === "adhere" && reason !== void 0)
6925
+ throw new Error("A supersession reason only applies to supersede");
6926
+ }
6927
+ async function finishResolution(run, choice, reason) {
6928
+ if (!run.server) throw new Error("Start the story first");
6929
+ if (run.stage !== "conflict" && run.server.choice && (run.server.choice !== choice || run.server.reason !== reason))
6930
+ throw new Error("This run already has a different approved resolution");
6931
+ if (run.stage === "conflict") {
6932
+ run.server = await demoApi("resolve", {
6933
+ runId: run.server.runId,
6934
+ revision: run.server.revision,
6935
+ choice,
6936
+ ...reason === void 0 ? {} : { reason }
6937
+ });
6938
+ if (run.server.stage !== "approved" || run.server.verdict !== "pass") {
6939
+ saveRun(run);
6940
+ return;
6941
+ }
6942
+ run.stage = "approved";
6943
+ saveRun(run);
6944
+ }
6945
+ if (run.stage === "approved") {
6946
+ const after = choice === "adhere" ? DEMO_ADHERE : DEMO_SUPERSEDE;
6947
+ if (digest(after) !== run.server.approvedDigest)
6948
+ throw new Error("Server approved unexpected sample bytes");
6949
+ const before = readSample(run, "customers.ts");
6950
+ if (before !== DEMO_INITIAL && before !== after)
6951
+ throw new Error("Sample changed; retained for inspection");
6952
+ writeSample(run, "customers.ts", after);
6953
+ if (readSample(run, "customers.ts") !== after) throw new Error("Sample write was not verified");
6954
+ run.receipt = { revision: run.server.revision, appliedDigest: digest(after) };
6955
+ run.stage = "applied";
6956
+ saveRun(run);
6957
+ }
6958
+ if (run.stage === "applied") {
6959
+ if (!run.receipt || digest(readSample(run, "customers.ts")) !== run.receipt.appliedDigest)
6960
+ throw new Error("Applied sample receipt no longer matches");
6961
+ run.server = await demoApi("complete", { runId: run.server.runId, ...run.receipt });
6962
+ if (run.server.stage !== "completed" || run.server.email === "not_queued")
6963
+ throw new Error("Email was not durably queued");
6964
+ run.stage = "cleanup";
6965
+ saveRun(run);
6966
+ }
6967
+ if (run.stage === "cleanup") {
6968
+ cleanSandbox(run);
6969
+ run.stage = "completed";
6970
+ saveRun(run);
6971
+ finishOnboarding("completed");
6972
+ }
6849
6973
  }
6850
- function advanceDemo(id, action, choice) {
6851
- return lockRun(id, (run) => {
6974
+ async function advanceDemo(id, action, choice, reason) {
6975
+ return await lockRunAsync(id, async (run) => {
6976
+ if (action === "resolve") requireResolution(choice, reason);
6852
6977
  if (action === "skip") {
6978
+ if (run.server && !["completed", "skipped"].includes(run.server.stage)) {
6979
+ const latest = await demoStatus(run.server.runId);
6980
+ run.server = await demoApi("skip", { runId: latest.runId, revision: latest.revision });
6981
+ }
6853
6982
  cleanSandbox(run);
6854
6983
  run.stage = "skipped";
6855
6984
  saveRun(run);
6856
6985
  finishOnboarding("skipped");
6857
- process.stderr.write(`[prim] ${handoff}
6858
- `);
6859
- if (run.binding) process.stderr.write(`${captureNotice}
6860
- `);
6861
- return resultFor2(run);
6986
+ return handoff(run);
6862
6987
  }
6863
- if (!consumeAcknowledgment(run, action, choice)) {
6864
- const message = `Tour pending: session isolation has not been acknowledged. ${demoTrustGuidance(run.agent)}`;
6865
- process.stderr.write(`[prim] ${message}
6866
- `);
6988
+ if (run.version === 1)
6989
+ throw new Error(
6990
+ `Legacy tour: clean up with ${demoCommand(run, "skip")}, then run prim demo again`
6991
+ );
6992
+ const isolation = consumeAcknowledgment(run, action, choice, reason);
6993
+ if (isolation)
6867
6994
  return {
6868
- ...resultFor2(run),
6995
+ fictional: true,
6996
+ evaluation: "live",
6997
+ runId: id,
6869
6998
  stage: "pending",
6870
- message,
6871
- nextAction: demoCommand(run, action, choice)
6999
+ isolation,
7000
+ nextAction: demoCommand(run, action, choice, reason),
7001
+ diagnosticAction: demoDiagnosticCommand(run),
7002
+ skipAction: demoCommand(run, "skip"),
7003
+ presentation: `Session isolation pending (${isolation}). ${demoTrustGuidance(run.agent)}`
6872
7004
  };
7005
+ if (action === "status") {
7006
+ const server = run.server ? await demoStatus(run.server.runId) : void 0;
7007
+ return { ...handoff(run), ...server ? { server } : {} };
6873
7008
  }
6874
- if (action === "confirm" && run.stage === "prepared") {
6875
- throw new Error("start the demo before confirming its proposal");
6876
- }
6877
- if (action === "resolve" && (run.stage === "prepared" || run.stage === "proposal")) {
6878
- throw new Error("confirm the sample Decision before resolving");
6879
- }
7009
+ if (["completed", "skipped"].includes(run.stage)) return handoff(run);
7010
+ const allowed = action === "start" ? ["prepared", "prompt"] : action === "attempt" ? ["prompt", "conflict"] : ["conflict", "approved", "applied", "cleanup"];
7011
+ if (!allowed.includes(run.stage)) throw new Error("Invalid demo transition");
6880
7012
  try {
6881
- process.stderr.write(`${bold(intro)}
6882
- `);
6883
- if (!run.terminal && action === "start") process.stderr.write(`${captureNotice}
6884
- `);
6885
- if (run.stage === "completed") {
6886
- narrateCompletion(run);
6887
- return { ...resultFor2(run), receipt: completionReceipt };
6888
- }
6889
- if (run.stage === "skipped") return resultFor2(run);
6890
- if (action === "start") {
6891
- if (run.stage === "prepared") {
6892
- createSandbox(run);
6893
- run.stage = "proposal";
6894
- saveRun(run);
6895
- }
6896
- if (run.stage === "proposal") {
6897
- process.stderr.write(
6898
- `
6899
- ${bold("YOUR MISSION: add order saving")}
6900
- Your fictional team discussed how this should work. Watch that context become Decisions, then guide an agent's implementation.
6901
- Local simulation \xB7 fictional examples \xB7 disposable files
6902
- `
6903
- );
6904
- process.stderr.write(`
6905
- Sample ingestion (scripted extraction):
6906
- ${SAMPLE_NOTE}
6907
- `);
6908
- process.stderr.write(`
6909
- ${bold(color("DECISION EXTRACTED \u2014 simulated", "green"))}
6910
- `);
6911
- narrateDecision(0);
6912
- process.stderr.write("The choice, its reason, and its source now travel together.\n");
6913
- process.stderr.write("\nNow explicitly author another sample Decision:\n");
6914
- narrateDecision(1);
6915
- process.stderr.write("Confirm this fictional Decision to adopt it, or skip the tour.\n");
6916
- }
6917
- return {
6918
- ...resultFor2(run),
6919
- decisions: SAMPLE_DECISIONS.slice(0, run.stage === "proposal" ? 1 : 2)
6920
- };
7013
+ if (run.needsStatus && run.server) {
7014
+ const latest = await demoStatus(run.server.runId);
7015
+ if (latest.runId !== run.server.runId)
7016
+ throw new Error("Server returned a different demo run");
7017
+ run.server = latest;
7018
+ run.needsStatus = false;
7019
+ saveRun(run);
6921
7020
  }
6922
- if (action === "confirm") {
6923
- const before2 = SAMPLE_FILES["service.ts"];
6924
- if (run.stage === "proposal") {
6925
- writeSample(run, "decisions.json", decisionBytes(true));
6926
- writeSample(run, "service.ts", WARNING_EDIT);
7021
+ if (action === "start" && run.stage === "prepared") {
7022
+ run.server = await demoApi("start", { scenarioVersion: 1, localRunId: run.id });
7023
+ if (run.server.stage !== "ready")
7024
+ throw new Error("Existing backend run needs recovery; inspect status");
7025
+ saveRun(run);
7026
+ createSandbox(run);
7027
+ run.stage = "prompt";
7028
+ saveRun(run);
7029
+ } else if (action === "attempt" && run.stage === "prompt") {
7030
+ if (!run.server || readSample(run, "customers.ts") !== DEMO_INITIAL)
7031
+ throw new Error("Initial sample changed");
7032
+ run.server = await demoApi("check", {
7033
+ runId: run.server.runId,
7034
+ revision: run.server.revision
7035
+ });
7036
+ if (run.server.stage === "blocked" && run.server.verdict === "block")
6927
7037
  run.stage = "conflict";
6928
- saveRun(run);
6929
- process.stderr.write(
6930
- `
6931
- ${bold(color("SAMPLE DECISION ADOPTED \u2014 simulated", "green"))}
6932
- ${SAMPLE_DECISIONS[1].decision}
6933
- Your confirmation changed this proposal into an adopted sample Decision.
6934
- `
6935
- );
6936
- }
6937
- const after2 = readSample(run, "service.ts");
6938
- const unchanged = readSample(run, "orders.ts");
6939
- process.stderr.write(`
6940
- ${bold(color("WARNING \u2014 edit allowed (simulated)", "yellow"))}
6941
- `);
6942
- process.stderr.write(
6943
- `Attempt: call fetch("/orders") directly.
6944
- Decision (provisional sample): ${SAMPLE_DECISIONS[0].decision}
6945
- Conflict: direct fetch bypasses consistent retries and request tracing.
6946
- Outcome: this scenario surfaces the conflict and allows the edit.
6947
- `
6948
- );
6949
- process.stderr.write(createPatch("service.ts", before2, after2));
6950
- process.stderr.write(
6951
- `Proof: service.ts ${before2 === after2 ? "already matches the shared client" : "changed, as shown above"}.
6952
- Next: restore the shared HTTP client for consistent retries and tracing.
6953
- `
6954
- );
6955
- narrateBlockedAttempt(unchanged);
6956
- process.stderr.write(
6957
- "\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"
6958
- );
7038
+ saveRun(run);
7039
+ } else if (action === "resolve") {
7040
+ if (!["conflict", "approved", "applied", "cleanup"].includes(run.stage))
7041
+ throw new Error("Enter the task and see its conflict before resolving");
7042
+ await finishResolution(run, choice, reason);
7043
+ } else if (!(action === "start" && run.stage === "prompt" || action === "attempt" && run.stage === "conflict")) {
7044
+ throw new Error("Invalid demo transition");
7045
+ }
7046
+ if (run.server?.verdict === "pending")
6959
7047
  return {
6960
7048
  ...resultFor2(run),
6961
- decisions: SAMPLE_DECISIONS,
6962
- evidence: {
6963
- warning: { before: before2, after: after2 },
6964
- block: {
6965
- before: unchanged,
6966
- proposed: BLOCKED_EDIT,
6967
- after: readSample(run, "orders.ts")
6968
- }
6969
- }
7049
+ stage: "pending",
7050
+ nextAction: demoCommand(run, action, choice, reason),
7051
+ presentation: `${label}
7052
+
7053
+ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File unchanged; retry or skip.`
6970
7054
  };
6971
- }
6972
- if (choice !== "repository" && choice !== "local-storage")
6973
- throw new Error("choose repository or local-storage");
6974
- if (choice === "local-storage") {
6975
- const unchanged = readSample(run, "orders.ts");
6976
- narrateBlockedAttempt(unchanged);
6977
- return { ...resultFor2(run), evidence: { unchanged } };
6978
- }
6979
- const before = readSample(run, "service.ts");
6980
- const ordersBefore = readSample(run, "orders.ts");
6981
- writeSample(run, "service.ts", SAMPLE_FILES["service.ts"]);
6982
- writeSample(run, "orders.ts", REPOSITORY_EDIT);
6983
- const after = readSample(run, "service.ts");
6984
- const orders = readSample(run, "orders.ts");
6985
- process.stderr.write(createPatch("service.ts", before, after));
6986
- process.stderr.write(createPatch("orders.ts", ordersBefore, orders));
6987
- process.stderr.write(
6988
- `${bold(color("PASS \u2014 compliant implementation written (simulated)", "green"))}
6989
- Order saving now uses the shared repository. Service calls use the shared HTTP client.
6990
- The requested change landed while preserving both sample Decisions.
6991
- `
6992
- );
6993
- cleanSandbox(run);
6994
- run.stage = "completed";
7055
+ return handoff(run);
7056
+ } catch (error) {
7057
+ run.needsStatus = true;
6995
7058
  saveRun(run);
6996
- finishOnboarding("completed");
6997
- narrateCompletion(run);
6998
7059
  return {
6999
7060
  ...resultFor2(run),
7000
- receipt: completionReceipt,
7001
- evidence: {
7002
- correction: { before, after },
7003
- orders,
7004
- orderCorrection: { before: ordersBefore, after: orders }
7005
- }
7061
+ stage: "pending",
7062
+ nextAction: demoCommand(run, action, choice, reason),
7063
+ presentation: `Tour pending: ${terminalSafeLine(error instanceof Error ? error.message : String(error))}`,
7064
+ ...run.stage === "cleanup" ? { outcomePresentation: present(run) } : {}
7006
7065
  };
7007
- } catch (error) {
7008
- try {
7009
- cleanSandbox(run);
7010
- run.stage = "prepared";
7011
- saveRun(run);
7012
- } catch {
7013
- }
7014
- throw error;
7015
7066
  }
7016
7067
  });
7017
7068
  }
7018
- function parseDemoAgent(value) {
7069
+ function parseAgent(value) {
7019
7070
  if (value === "claude") return "claude_code";
7020
7071
  if (value === void 0 || ["claude_code", "codex", "cursor", "hermes"].includes(value))
7021
7072
  return value;
7022
- throw new Error("expected --agent claude, codex, cursor, or hermes");
7073
+ throw new Error("Expected --agent claude, codex, cursor, or hermes");
7023
7074
  }
7024
7075
  function reportError(error) {
7025
- const message = error instanceof Error ? error.message : String(error);
7076
+ const message = terminalSafeLine(error instanceof Error ? error.message : String(error));
7026
7077
  process.stderr.write(`[prim] demo: ${message}
7027
7078
  `);
7028
- printJson({ simulated: true, stage: "error", message });
7079
+ printJson2({ fictional: true, evaluation: "live", stage: "error", message });
7029
7080
  process.exitCode = 1;
7030
7081
  }
7082
+ async function terminalTour(run) {
7083
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
7084
+ const show = (result) => {
7085
+ const text = result.presentation.replace(/^```(?:text|ts|diff)?\n/gmu, "").replace(/```/gu, "").replace(/\*\*(.*?)\*\*/gu, (_match, title) => bold(title));
7086
+ process.stderr.write(
7087
+ `${text.replace("YOUR DECISION STOPPED THIS", color("YOUR DECISION STOPPED THIS", "red")).replace("PASS \u2014 CSV export implemented", color("PASS \u2014 CSV export implemented", "green"))}
7088
+ `
7089
+ );
7090
+ if (["completed", "skipped"].includes(result.stage) && "nextAction" in result) {
7091
+ process.stderr.write(`Next: ${result.nextAction}
7092
+ `);
7093
+ }
7094
+ return result;
7095
+ };
7096
+ try {
7097
+ const started = show(await advanceDemo(run.id, "start"));
7098
+ if (started.stage !== "prompt") return started;
7099
+ const task = await rl.question("Enter the task above (or skip): ");
7100
+ if (task.trim() !== DEMO_TASK) return show(await advanceDemo(run.id, "skip"));
7101
+ const blocked = show(await advanceDemo(run.id, "attempt"));
7102
+ if (blocked.stage !== "conflict") return blocked;
7103
+ const choice = (await rl.question("Adhere or supersede? [adhere/supersede/skip] ")).trim().toLowerCase();
7104
+ if (choice !== "adhere" && choice !== "supersede")
7105
+ return show(await advanceDemo(run.id, "skip"));
7106
+ const reason = choice === "supersede" ? await rl.question("Your reason for the replacement: ") : void 0;
7107
+ return show(await advanceDemo(run.id, "resolve", choice, reason));
7108
+ } finally {
7109
+ rl.close();
7110
+ }
7111
+ }
7031
7112
  function registerDemoCommands(program2) {
7032
- const demo = program2.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) => {
7113
+ const demo = program2.command("demo").description("Experience your Decision protecting a fictional teammate change").option("--agent <agent>", "calling agent; requires session isolation").option("--details", "include supporting story detail").action(async (options, command) => {
7033
7114
  try {
7034
- const agent = parseDemoAgent(options.agent);
7035
- 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;
7115
+ const agent = parseAgent(options.agent);
7116
+ const terminal = !agent && !isNonInteractive(command.optsWithGlobals()) && !!process.stdin.isTTY && !!process.stderr.isTTY && !process.env.CLAUDECODE && !process.env.CODEX_THREAD_ID && !process.env.CURSOR_AGENT && !process.env.HERMES_INTERACTIVE;
7036
7117
  const recovery = pendingRuns().map(
7037
- (id) => lockRun(id, (run2) => ({ runId: id, skipAction: demoCommand(run2, "skip") }))
7118
+ (id) => lockRun(id, (run2) => ({
7119
+ runId: id,
7120
+ skipAction: demoCommand(
7121
+ { ...run2, launcher: [process.execPath, resolve3(process.argv[1])] },
7122
+ "skip"
7123
+ )
7124
+ }))
7038
7125
  );
7039
7126
  const run = prepareRun(agent, terminal);
7040
- if (!terminal) {
7041
- process.stderr.write(
7042
- "[prim] Preparing the simulated tour. Run nextAction exactly, as a standalone shell command. No sample content is shown until session isolation is acknowledged.\n"
7043
- );
7044
- if (recovery.length)
7045
- process.stderr.write(
7046
- "[prim] Earlier unfinished tours are listed in recoverableRuns; use their skipAction to clean up.\n"
7047
- );
7048
- printJson({ ...resultFor2(run), recoverableRuns: recovery });
7127
+ if (terminal) {
7128
+ const result = await terminalTour(run);
7129
+ if (!process.stdout.isTTY) printJson2(result);
7049
7130
  return;
7050
7131
  }
7051
- advanceDemo(run.id, "start");
7052
- if (!await askConfirmation("Adopt this fictional Decision?", process.stderr)) {
7053
- printJson(advanceDemo(run.id, "skip"));
7054
- return;
7055
- }
7056
- advanceDemo(run.id, "confirm");
7057
- if (await askConfirmation("Apply the shared repository correction?", process.stderr)) {
7058
- printJson(advanceDemo(run.id, "resolve", "repository"));
7059
- } else {
7060
- printJson(advanceDemo(run.id, "skip"));
7061
- }
7132
+ process.stderr.write("[prim] Tour ready \u2192 run nextAction to check session isolation.\n");
7133
+ printJson2({
7134
+ ...handoff(run),
7135
+ instructions: "Run nextAction exactly as a standalone command. Render presentation once, preserving diagrams. At awaitUserPrompt, wait for the user to enter that task before running attemptAction. At the block, wait for adhere or supersede; supersede requires the user's own reason and approval of the displayed replacement. Append --reason and the reason using the same single-quoted argv format (escape an apostrophe as '\\''). Never invent a reason, delegate this tour, or save fictional samples to memory or real Decisions. On completion display success before following welcome. A new session resumes passive capture.",
7136
+ recoverableRuns: recovery
7137
+ });
7062
7138
  } catch (error) {
7063
7139
  reportError(error);
7064
7140
  }
7065
7141
  });
7066
- for (const action of ["start", "confirm", "resolve", "skip"]) {
7067
- const subcommand = demo.command(`${action} ${action === "skip" ? "[runId]" : "<runId>"}`);
7142
+ for (const action of ["start", "attempt", "resolve", "status", "skip"]) {
7143
+ const sub = demo.command(`${action} ${action === "skip" ? "[runId]" : "<runId>"}`);
7068
7144
  if (action === "resolve")
7069
- subcommand.requiredOption("--choice <choice>", "repository or local-storage");
7070
- subcommand.action((id, options) => {
7071
- try {
7072
- if (action === "skip" && !id) {
7073
- finishOnboarding("skipped");
7074
- printJson({
7075
- simulated: true,
7076
- stage: "skipped",
7077
- message: "Tour skipped. Run prim welcome for real Decision seeding."
7078
- });
7079
- return;
7080
- }
7081
- if (action === "resolve" && options.choice !== "repository" && options.choice !== "local-storage") {
7082
- throw new Error("choose repository or local-storage");
7145
+ sub.requiredOption("--choice <choice>", "adhere or supersede").option("--reason <reason>", "your reason for the displayed replacement");
7146
+ sub.action(
7147
+ async (id, options) => {
7148
+ try {
7149
+ if (action === "skip" && !id) {
7150
+ finishOnboarding("skipped");
7151
+ printJson2({
7152
+ fictional: true,
7153
+ stage: "skipped",
7154
+ message: "Tour skipped. Run prim welcome for real Decisions."
7155
+ });
7156
+ return;
7157
+ }
7158
+ printJson2(await advanceDemo(id, action, options.choice, options.reason));
7159
+ } catch (error) {
7160
+ reportError(error);
7083
7161
  }
7084
- printJson(advanceDemo(id, action, options.choice));
7085
- } catch (error) {
7086
- reportError(error);
7087
7162
  }
7088
- });
7163
+ );
7089
7164
  }
7090
7165
  }
7091
7166
 
@@ -7286,10 +7361,10 @@ function stripBin(list, bin) {
7286
7361
  }
7287
7362
  function ensureReg(list, reg, force) {
7288
7363
  const entry = entryFor(reg);
7289
- const present = list.some(
7364
+ const present2 = list.some(
7290
7365
  (e) => e.command === entry.command && (e.matcher ?? "") === (entry.matcher ?? "") && (e.timeout ?? null) === (entry.timeout ?? null)
7291
7366
  );
7292
- if (present && !force) {
7367
+ if (present2 && !force) {
7293
7368
  return list;
7294
7369
  }
7295
7370
  return [...stripBin(list, reg.bin), entry];
@@ -8120,6 +8195,8 @@ function managedHookRemedy(inspection) {
8120
8195
  return `outside this repository \u2014 ${externalHookRemedy(inspection.hookName, inspection.gitRoot)}`;
8121
8196
  }
8122
8197
  return "run `prim hooks install`";
8198
+ case "unsupported_interpreter":
8199
+ return "verify the hook interpreter; direct shell hooks need a supported shebang (for example #!/bin/sh); Husky v9 must use its .husky/_ dispatcher";
8123
8200
  case "entrypoint_missing":
8124
8201
  return "run `prim enable` to stage the hook runtime";
8125
8202
  default:
@@ -8563,7 +8640,10 @@ var DEFAULT_DOCTOR_PROBES = {
8563
8640
  };
8564
8641
  async function collectChecks(options, probes) {
8565
8642
  const { before, after } = await probes.independent();
8566
- return [...before, ...classifyDelivery(await probes.delivery(), options), ...after];
8643
+ const checks = [...before, ...classifyDelivery(await probes.delivery(), options), ...after];
8644
+ return checks.filter(
8645
+ (check) => !(options.agent && options.agent !== "claude" && check.name === "feedback-hooks" && check.detail.startsWith("Claude lifecycle hooks missing"))
8646
+ );
8567
8647
  }
8568
8648
  function icon(status) {
8569
8649
  return status === "ok" ? "\u2713" : status === "warn" ? "\u26A0" : "\u2717";
@@ -8575,6 +8655,7 @@ async function runDoctor(options, probes) {
8575
8655
  process.stderr.write(`[prim] doctor: ${headline}
8576
8656
  `);
8577
8657
  for (const c of checks) {
8658
+ if (options.compact && c.status === "ok") continue;
8578
8659
  process.stderr.write(` ${icon(c.status)} ${c.name.padEnd(13)} ${c.detail}
8579
8660
  `);
8580
8661
  }
@@ -8586,9 +8667,9 @@ async function runDoctor(options, probes) {
8586
8667
  function registerDoctorCommands(program2, dependencies = {}) {
8587
8668
  program2.command("doctor").description(
8588
8669
  "Check capture and feedback health end to end (auth, supervisor, delivery, server)"
8589
- ).addOption(new Option4("--expect-backlog").hideHelp()).action(async (opts) => {
8670
+ ).addOption(new Option4("--expect-backlog").hideHelp()).addOption(new Option4("--agent <agent>").choices(["claude", "codex", "cursor", "hermes"])).option("--compact", "show only health warnings and failures on STDERR").action(async (opts) => {
8590
8671
  await runDoctor(
8591
- { backlogExpected: opts.expectBacklog === true },
8672
+ { backlogExpected: opts.expectBacklog === true, agent: opts.agent, compact: opts.compact },
8592
8673
  dependencies.probes ?? DEFAULT_DOCTOR_PROBES
8593
8674
  );
8594
8675
  });
@@ -8603,7 +8684,7 @@ import { createReadStream, renameSync as renameSync3, statSync as statSync3, unl
8603
8684
  import { dirname as dirname4, join as join9 } from "path";
8604
8685
 
8605
8686
  // src/dead-letter.ts
8606
- import { createHash as createHash3, randomBytes as randomBytes4 } from "crypto";
8687
+ import { createHash as createHash4, randomBytes as randomBytes4 } from "crypto";
8607
8688
  import {
8608
8689
  constants as constants3,
8609
8690
  chmodSync as chmodSync2,
@@ -8625,7 +8706,7 @@ function deadLetterDirectoryForRotation(flushingPath) {
8625
8706
  return join8(dirname3(flushingPath), DEAD_LETTER_DIRNAME);
8626
8707
  }
8627
8708
  function deadLetterPathForRawLine(flushingPath, rawLine) {
8628
- const quarantineId = createHash3("sha256").update(rawLine).digest("hex");
8709
+ const quarantineId = createHash4("sha256").update(rawLine).digest("hex");
8629
8710
  return join8(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
8630
8711
  }
8631
8712
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
@@ -8667,7 +8748,7 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
8667
8748
  const serializedMove = JSON.stringify(move);
8668
8749
  const record3 = {
8669
8750
  version: 1,
8670
- quarantineId: createHash3("sha256").update(serializedMove).digest("hex"),
8751
+ quarantineId: createHash4("sha256").update(serializedMove).digest("hex"),
8671
8752
  quarantinedAt: now(),
8672
8753
  reason,
8673
8754
  move
@@ -8683,7 +8764,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
8683
8764
  const record3 = {
8684
8765
  version: 1,
8685
8766
  recordKind: "raw_line_v1",
8686
- quarantineId: createHash3("sha256").update(bytes).digest("hex"),
8767
+ quarantineId: createHash4("sha256").update(bytes).digest("hex"),
8687
8768
  quarantinedAt: now(),
8688
8769
  reason: "invalid_move",
8689
8770
  rawLineEncoding: "base64",
@@ -9418,7 +9499,7 @@ function setupStepSpawnOptions(capture, env = process.env, options = {}) {
9418
9499
  // Unset rather than inherited when this setup starts no daemon.
9419
9500
  [SETUP_DAEMON_DRAINS_ENV]: options.startsDaemon === true ? "1" : void 0
9420
9501
  },
9421
- stdio: capture ? ["inherit", "pipe", "ignore"] : "inherit",
9502
+ stdio: capture ? ["inherit", "pipe", "ignore"] : options.compact ? ["inherit", "pipe", "inherit"] : "inherit",
9422
9503
  encoding: "utf-8"
9423
9504
  };
9424
9505
  }
@@ -9476,7 +9557,7 @@ function planSetupSteps(opts) {
9476
9557
  steps.push({
9477
9558
  key: "health",
9478
9559
  label: "Capture health",
9479
- args: ["doctor", "--expect-backlog"],
9560
+ args: ["doctor", "--expect-backlog", "--agent", opts.agent, "--compact"],
9480
9561
  required: true
9481
9562
  });
9482
9563
  }
@@ -9595,7 +9676,7 @@ function registerSetupCommand(program2, dependencies = {}) {
9595
9676
  ).option(
9596
9677
  "--migrate",
9597
9678
  "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
9598
- ).option("--no-daemon", "stop and disable the companion daemon").option("--skip-demo", "skip the local onboarding tour and remember that choice").action((opts) => {
9679
+ ).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full installation diagnostics and child output").option("--skip-demo", "skip the optional author story and remember that choice").action((opts) => {
9599
9680
  const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
9600
9681
  if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
9601
9682
  process.stderr.write(
@@ -9621,12 +9702,26 @@ function registerSetupCommand(program2, dependencies = {}) {
9621
9702
  const self = process.argv[1];
9622
9703
  const globals = program2.optsWithGlobals();
9623
9704
  const run = dependencies.run ?? ((args, capture = false) => {
9705
+ const compact = !opts.details;
9706
+ const structuredChild = args.includes("demo") || args[0] === "welcome";
9707
+ const childArgs = opts.details ? args.filter((arg) => arg !== "--compact") : args;
9624
9708
  const r = spawnSync2(
9625
9709
  process.execPath,
9626
- [self, ...args],
9627
- setupStepSpawnOptions(capture, process.env, { startsDaemon: opts.daemon })
9710
+ [self, ...childArgs],
9711
+ setupStepSpawnOptions(capture, process.env, {
9712
+ startsDaemon: opts.daemon,
9713
+ compact: compact || structuredChild
9714
+ })
9628
9715
  );
9629
- return { code: r.status ?? 1, stdout: capture ? r.stdout ?? "" : "" };
9716
+ if (!capture && opts.details && structuredChild && r.stdout)
9717
+ process.stdout.write(r.stdout);
9718
+ if (!capture && compact && r.status !== 0 && r.stdout) process.stderr.write(r.stdout);
9719
+ if (r.error) process.stderr.write(`[prim] ${r.error.message}
9720
+ `);
9721
+ return {
9722
+ code: r.status ?? 1,
9723
+ stdout: capture || compact || structuredChild ? r.stdout ?? "" : ""
9724
+ };
9630
9725
  });
9631
9726
  const results = {};
9632
9727
  const note = dependencies.note ?? ((msg) => {
@@ -9729,12 +9824,19 @@ function registerSetupCommand(program2, dependencies = {}) {
9729
9824
  note("demo \xB7 could not remember skip; installation remains configured");
9730
9825
  }
9731
9826
  note("welcome");
9732
- results.welcome = run(["welcome", "--agent", agent, ...tourDue ? ["--defer-seeding"] : []]).code === 0 ? "ok" : "failed";
9827
+ const welcomeResult = run([
9828
+ "welcome",
9829
+ "--agent",
9830
+ agent,
9831
+ ...tourDue ? ["--defer-seeding"] : []
9832
+ ]);
9833
+ results.welcome = welcomeResult.code === 0 ? "ok" : "failed";
9733
9834
  const failed = Object.entries(results).filter(([, v]) => v === "failed").map(([k]) => k);
9734
9835
  const trail = Object.entries(results).map(([k, v]) => `${k}:${v}`).join(" \xB7 ");
9735
9836
  note(
9736
9837
  `setup ${failed.length === 0 ? "complete" : `incomplete (failed: ${failed.join(", ")})`} \u2014 ${trail}`
9737
9838
  );
9839
+ let onboarding;
9738
9840
  if (failed.length === 0 && tourDue) {
9739
9841
  const agentDriven = Boolean(
9740
9842
  opts.agent || !process.stdin.isTTY || !process.stderr.isTTY || process.env.CLAUDECODE || process.env.CODEX_THREAD_ID || process.env.CURSOR_AGENT || process.env.HERMES_INTERACTIVE
@@ -9744,16 +9846,38 @@ function registerSetupCommand(program2, dependencies = {}) {
9744
9846
  "demo",
9745
9847
  ...agentDriven ? ["--agent", agent] : []
9746
9848
  ]);
9747
- if (demoResult.code !== 0)
9849
+ onboarding = setupChildPayload(demoResult.stdout) ?? {
9850
+ stage: "pending",
9851
+ message: "Run prim demo to recover the optional story"
9852
+ };
9853
+ if (demoResult.code !== 0) {
9854
+ onboarding = { ...onboarding, stage: "pending" };
9748
9855
  note("demo \xB7 pending after an error; setup succeeded. Run prim demo to retry");
9856
+ }
9749
9857
  }
9858
+ if (!process.stdout.isTTY || opts.agent || globals.nonInteractive || process.env.CLAUDECODE || process.env.CODEX_THREAD_ID || process.env.CURSOR_AGENT || process.env.HERMES_INTERACTIVE)
9859
+ printJson({
9860
+ setup: true,
9861
+ status: failed.length ? "incomplete" : "complete",
9862
+ steps: results,
9863
+ welcome: setupChildPayload(welcomeResult.stdout),
9864
+ ...onboarding ? { onboarding, nextAction: onboarding.nextAction } : {}
9865
+ });
9750
9866
  exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
9751
9867
  });
9752
9868
  }
9869
+ function setupChildPayload(stdout) {
9870
+ try {
9871
+ const value = JSON.parse(stdout);
9872
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9873
+ } catch {
9874
+ return void 0;
9875
+ }
9876
+ }
9753
9877
 
9754
9878
  // src/commands/statusline.ts
9755
9879
  import { readFileSync as readFileSync9 } from "fs";
9756
- import { dirname as dirname5, resolve as resolve3 } from "path";
9880
+ import { dirname as dirname5, resolve as resolve4 } from "path";
9757
9881
  import { fileURLToPath } from "url";
9758
9882
  var STATUSLINE_TIMEOUT_MS = 200;
9759
9883
  function readPackageVersion() {
@@ -9762,9 +9886,9 @@ function readPackageVersion() {
9762
9886
  const candidates = [
9763
9887
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
9764
9888
  // Keep resolving it while those legacy launchers transition to schema v3.
9765
- resolve3(here, "manifest.json"),
9766
- resolve3(here, "../../package.json"),
9767
- resolve3(here, "../package.json")
9889
+ resolve4(here, "manifest.json"),
9890
+ resolve4(here, "../../package.json"),
9891
+ resolve4(here, "../package.json")
9768
9892
  ];
9769
9893
  for (const path of candidates) {
9770
9894
  try {
@@ -10045,8 +10169,8 @@ function resolveWelcomeAgent(agentFlag, env) {
10045
10169
  var CAPTURE_LINES = {
10046
10170
  claude: ["Capture is automatic \u2014 keep coding; your decisions are recorded for you."],
10047
10171
  codex: [
10048
- "Capture starts once you trust the prim hooks \u2014 run /hooks in Codex;",
10049
- "until then nothing is recorded."
10172
+ "Capture starts once the prim hooks are active \u2014 check /hooks in Codex;",
10173
+ "approve them only if prompted."
10050
10174
  ],
10051
10175
  cursor: ["Capture is automatic in trusted Cursor workspaces; restart Cursor CLI for the footer."],
10052
10176
  hermes: [
@@ -10061,7 +10185,7 @@ var CAPTURE_LINES = {
10061
10185
  var PASSIVE_LINES = {
10062
10186
  claude: ["Otherwise Primitive captures decisions passively while you work."],
10063
10187
  codex: [
10064
- "Once you trust the prim hooks (/hooks in Codex), Primitive captures",
10188
+ "Once the prim hooks are active (/hooks in Codex), Primitive captures",
10065
10189
  "decisions passively while you work."
10066
10190
  ],
10067
10191
  cursor: ["In trusted Cursor workspaces, Primitive captures decisions passively while you work."],
@@ -10076,7 +10200,7 @@ var PASSIVE_LINES = {
10076
10200
  };
10077
10201
  var GUIDANCE_PASSIVE = {
10078
10202
  claude: "Otherwise, Primitive passively captures decisions in the background while you work.",
10079
- codex: "Otherwise, once you trust the prim hooks (run /hooks in Codex), Primitive passively captures decisions in the background while you work.",
10203
+ codex: "Otherwise, once the prim hooks are active (check /hooks in Codex), Primitive passively captures decisions in the background while you work.",
10080
10204
  cursor: "Otherwise, Primitive passively captures decisions in trusted Cursor workspaces while you work.",
10081
10205
  hermes: "Otherwise, once you approve the prim hooks when Hermes prompts, Primitive passively captures decisions in the background while you work.",
10082
10206
  generic: "Otherwise, once your agent's prim hooks are active, Primitive passively captures decisions in the background while you work."
@@ -10173,18 +10297,28 @@ function welcomeJson(state, agent, captureExcluded = false) {
10173
10297
  return { welcomed: true, org: "unknown" };
10174
10298
  }
10175
10299
  function registerWelcomeCommand(program2, deps = { getClient }) {
10176
- program2.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(
10300
+ program2.command("welcome").description("Print a brief orientation to Primitive's decision graph").option("--agent <agent>", "claude, codex, cursor, or hermes \u2014 tailors the capture guidance").option("--defer-seeding", "let setup's author story finish before proposing real Decisions").option("--after-demo", "return a short transition after the author story").option("--capture-excluded", "explain the demo session's passive capture exclusion").action(
10177
10301
  async (options) => {
10178
10302
  const agent = resolveWelcomeAgent(options.agent, process.env);
10179
10303
  if (options.deferSeeding) {
10180
10304
  process.stderr.write(
10181
- "Welcome to Primitive. Setup is complete; the optional simulated tour comes before real Decision seeding.\n"
10305
+ "Welcome to Primitive. Setup is complete; the optional author story comes before real Decision seeding.\n"
10182
10306
  );
10183
10307
  printJson({ welcomed: true, onboarding: "demo", seedingDeferred: true });
10184
10308
  return;
10185
10309
  }
10186
10310
  const result = await fetchRecent({ limit: RECENT_LIMIT }, deps);
10187
10311
  const state = welcomeStateFromRecent(result);
10312
+ if (options.afterDemo) {
10313
+ printJson({
10314
+ welcomed: true,
10315
+ org: state.org,
10316
+ presentation: state.org === "seed" ? "Ready for your first real Decision? I can propose one from shared repository memory for your approval. Approved Decisions are visible to your team." : state.org === "active" ? "Ready for real work. Ask your agent to add a Decision whenever you need one." : "Your Decision history is unavailable; no seeding assumptions were made. Retry welcome when the connection is available.",
10317
+ ...state.org === "seed" ? { seedGuidance: seedGuidanceFor(agent, options.captureExcluded) } : {},
10318
+ captureExcluded: options.captureExcluded === true
10319
+ });
10320
+ return;
10321
+ }
10188
10322
  process.stderr.write(`${formatWelcome(state, agent, options.captureExcluded)}
10189
10323
  `);
10190
10324
  printJson(welcomeJson(state, agent, options.captureExcluded));
@@ -10417,7 +10551,7 @@ function runStartupBackgroundWork(argv, env, work) {
10417
10551
 
10418
10552
  // src/index.ts
10419
10553
  var __dirname = dirname7(fileURLToPath2(import.meta.url));
10420
- var pkg = JSON.parse(readFileSync11(resolve4(__dirname, "../package.json"), "utf-8"));
10554
+ var pkg = JSON.parse(readFileSync11(resolve5(__dirname, "../package.json"), "utf-8"));
10421
10555
  runStartupBackgroundWork(process.argv.slice(2), process.env, {
10422
10556
  notify: () => updateNotifier({ pkg }).notify(),
10423
10557
  flush: () => startBackgroundFlush(),