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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +19 -9
  2. package/SKILL.md +7 -2
  3. package/dist/{chunk-HXICZG5J.js → chunk-2DNC2MUN.js} +4 -4
  4. package/dist/{chunk-NQFRQ56V.js → chunk-2PFJJO2M.js} +2 -2
  5. package/dist/{chunk-P2O7NLVN.js → chunk-4GYJHN26.js} +117 -18
  6. package/dist/{chunk-5BQ2NEMP.js → chunk-6DEROXLM.js} +2 -2
  7. package/dist/{chunk-CCGFRNAA.js → chunk-7LXRFXZG.js} +248 -127
  8. package/dist/{chunk-MWNRXAEB.js → chunk-AKGRY7OU.js} +1 -1
  9. package/dist/{chunk-L52OD62C.js → chunk-BHT6X3T5.js} +14 -8
  10. package/dist/{chunk-D235RJNO.js → chunk-DQ4I3FLF.js} +3 -3
  11. package/dist/{chunk-VOC4KOOP.js → chunk-DVHD6LBQ.js} +2 -2
  12. package/dist/{chunk-TC4FTRYO.js → chunk-HG7FJK7R.js} +2 -2
  13. package/dist/{chunk-GYQOZGGF.js → chunk-JXRJLHE4.js} +2 -2
  14. package/dist/{chunk-2AKDX4RU.js → chunk-JZC2LHS6.js} +1 -1
  15. package/dist/{chunk-YTF6OCF3.js → chunk-LQLP26RL.js} +5 -5
  16. package/dist/{chunk-EYBE724K.js → chunk-M4NZJCPQ.js} +4 -4
  17. package/dist/{chunk-R2NUH4B7.js → chunk-MRDY7VQP.js} +2 -2
  18. package/dist/{chunk-SLDZJD6Q.js → chunk-NMZSCSMY.js} +1 -1
  19. package/dist/{chunk-A6M2M5A2.js → chunk-NQZLXYTW.js} +1 -1
  20. package/dist/{chunk-LTTF4MBE.js → chunk-OXW6PSPT.js} +2 -2
  21. package/dist/{chunk-U67RBNIZ.js → chunk-S3ZIMGXV.js} +1 -1
  22. package/dist/{chunk-LBCPRHNG.js → chunk-WN7OURQ3.js} +1 -1
  23. package/dist/daemon/server.js +78 -16
  24. package/dist/hook-runtime/daemon/server.js +78 -16
  25. package/dist/hook-runtime/hooks/post-commit.js +88 -26
  26. package/dist/hook-runtime/hooks/post-rewrite.js +82 -20
  27. package/dist/hook-runtime/hooks/post-tool-use.js +82 -20
  28. package/dist/hook-runtime/hooks/pre-commit.js +9 -5
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +12 -8
  30. package/dist/hook-runtime/hooks/prim-hook.js +85 -23
  31. package/dist/hook-runtime/hooks/session-end.js +75 -13
  32. package/dist/hook-runtime/hooks/session-start.js +247 -176
  33. package/dist/hook-runtime/index.js +1147 -692
  34. package/dist/hook-runtime/statusline-main.js +76 -14
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +15 -15
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +9 -9
  40. package/dist/hooks/prim-hook.js +17 -17
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +11 -11
  43. package/dist/index.js +349 -98
  44. package/dist/statusline-main.js +76 -14
  45. package/package.json +3 -2
  46. package/skills/prim-welcome/SKILL.md +197 -0
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import {
3
3
  bindRepository,
4
4
  bindRepositoryWithClient,
5
+ codexWelcomeSkillPath,
5
6
  ensureEffectiveGitHook,
6
7
  ensureGitHookAtPath,
7
8
  externalHookRemedy,
@@ -18,31 +19,33 @@ import {
18
19
  resolveEffectiveGitHook,
19
20
  resolveRepositoryBinding,
20
21
  uninstallGitHookAtPath,
21
- uninstallProjectGitHook
22
- } from "./chunk-CCGFRNAA.js";
22
+ uninstallProjectGitHook,
23
+ userTargetFor,
24
+ welcomeSkillPathFor
25
+ } from "./chunk-7LXRFXZG.js";
23
26
  import {
24
27
  requireDurableIngestAcknowledgement
25
- } from "./chunk-A6M2M5A2.js";
28
+ } from "./chunk-NQZLXYTW.js";
26
29
  import {
27
30
  checkAffectedDecisions,
28
31
  daemonOrDirectGet,
29
32
  formatDecisionsWarning
30
- } from "./chunk-D235RJNO.js";
33
+ } from "./chunk-DQ4I3FLF.js";
31
34
  import {
32
35
  hasCompleteCoverage,
33
36
  requestPreflight,
34
37
  waitForPreflight
35
- } from "./chunk-YTF6OCF3.js";
38
+ } from "./chunk-LQLP26RL.js";
36
39
  import {
37
40
  fetchFeedbackCapability
38
- } from "./chunk-2AKDX4RU.js";
41
+ } from "./chunk-JZC2LHS6.js";
39
42
  import {
40
43
  POST_COMMIT_GRACE_MS,
41
44
  clearHooksWired,
42
45
  inspectPostCommitFiring,
43
46
  lastConversationCaptured,
44
47
  recordHooksWired
45
- } from "./chunk-LBCPRHNG.js";
48
+ } from "./chunk-WN7OURQ3.js";
46
49
  import {
47
50
  isUnattended,
48
51
  unattendedEnv
@@ -55,7 +58,7 @@ import {
55
58
  formatStatusline,
56
59
  formatTeammates,
57
60
  repositoryBindingDiagnosticLabel
58
- } from "./chunk-GYQOZGGF.js";
61
+ } from "./chunk-JXRJLHE4.js";
59
62
  import {
60
63
  JOURNAL_DIR,
61
64
  SESSIONS_DIR,
@@ -70,15 +73,16 @@ import {
70
73
  rotationIdentity,
71
74
  sweepOrphanedDrainProgress,
72
75
  writeDrainCheckpoint
73
- } from "./chunk-LTTF4MBE.js";
76
+ } from "./chunk-OXW6PSPT.js";
74
77
  import {
75
78
  daemonIsLive,
76
79
  daemonRequest
77
- } from "./chunk-SLDZJD6Q.js";
80
+ } from "./chunk-NMZSCSMY.js";
78
81
  import {
79
82
  RUN_ID,
80
83
  demoCommand,
81
84
  demoDiagnosticCommand,
85
+ demoDirectory,
82
86
  demoResumeCommand,
83
87
  demoWelcomeCommand,
84
88
  exclusionPath,
@@ -92,8 +96,9 @@ import {
92
96
  prepareRun,
93
97
  readDemoJson,
94
98
  readRun,
99
+ runIds,
95
100
  saveRun
96
- } from "./chunk-L52OD62C.js";
101
+ } from "./chunk-BHT6X3T5.js";
97
102
  import {
98
103
  MANAGED_GIT_HOOK_NAMES,
99
104
  assertOwnedHookRuntime,
@@ -119,8 +124,8 @@ import {
119
124
  stableNodePath,
120
125
  stageHookRuntime,
121
126
  stripCommand
122
- } from "./chunk-MWNRXAEB.js";
123
- import "./chunk-NQFRQ56V.js";
127
+ } from "./chunk-AKGRY7OU.js";
128
+ import "./chunk-2PFJJO2M.js";
124
129
  import {
125
130
  bold,
126
131
  boundedHealthError,
@@ -145,7 +150,7 @@ import {
145
150
  isMoveIngestRequest,
146
151
  isReconcileResolutionResponse,
147
152
  stripAnsi
148
- } from "./chunk-5BQ2NEMP.js";
153
+ } from "./chunk-6DEROXLM.js";
149
154
  import {
150
155
  CliManagementResponseError,
151
156
  HttpError,
@@ -163,7 +168,7 @@ import {
163
168
  setStoredToken,
164
169
  stripControlChars,
165
170
  terminalSafeLine
166
- } from "./chunk-U67RBNIZ.js";
171
+ } from "./chunk-S3ZIMGXV.js";
167
172
  import {
168
173
  REFRESH_TOKEN_PATH,
169
174
  TOKEN_FILE_PATH,
@@ -172,21 +177,27 @@ import {
172
177
  binFile,
173
178
  canonicalGitRoot,
174
179
  canonicalRepositoryPath,
180
+ clearDemoPause,
175
181
  commandMatchesBin,
176
182
  compareSemver,
177
183
  decisionIngestionStatus,
178
184
  discoverWorkosConnect,
185
+ endDemoPause,
186
+ extendDemoPause,
179
187
  gitToplevel,
188
+ healDemoPause,
180
189
  hookCommandResolutions,
181
190
  isRepoActiveForCapture,
182
191
  isValidRepoSyncId,
183
192
  mainWorktreeRoot,
184
193
  packageRoot,
185
194
  packageVersion,
195
+ pauseCaptureForDemo,
186
196
  pinnedNpxArgs,
187
197
  pollWorkosDeviceAuthorization,
188
198
  primConfigDirectory,
189
199
  processIsAlive,
200
+ readDemoPause,
190
201
  repoActiveFlag,
191
202
  repoSyncId,
192
203
  repositoryBindingState,
@@ -197,12 +208,12 @@ import {
197
208
  syncDirectory,
198
209
  withFileLock,
199
210
  withFileLockSync
200
- } from "./chunk-P2O7NLVN.js";
211
+ } from "./chunk-4GYJHN26.js";
201
212
  import "./chunk-JSBRDJBE.js";
202
213
 
203
214
  // src/index.ts
204
215
  import { readFileSync as readFileSync12 } from "fs";
205
- import { dirname as dirname8, resolve as resolve6 } from "path";
216
+ import { dirname as dirname8, resolve as resolve7 } from "path";
206
217
  import { fileURLToPath as fileURLToPath3 } from "url";
207
218
  import { Command } from "commander";
208
219
  import updateNotifier from "update-notifier";
@@ -1085,8 +1096,8 @@ ${verificationUrl}`);
1085
1096
  const state = base64url(randomBytes2(16));
1086
1097
  const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
1087
1098
  let settle;
1088
- const outcome = new Promise((resolve7) => {
1089
- settle = resolve7;
1099
+ const outcome = new Promise((resolve8) => {
1100
+ settle = resolve8;
1090
1101
  });
1091
1102
  const server = createServer((req, res) => {
1092
1103
  const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
@@ -1100,12 +1111,12 @@ ${verificationUrl}`);
1100
1111
  res.end(page.html, () => settle(page.result));
1101
1112
  });
1102
1113
  try {
1103
- await new Promise((resolve7, reject) => {
1114
+ await new Promise((resolve8, reject) => {
1104
1115
  const onError = (err) => reject(err);
1105
1116
  server.once("error", onError);
1106
1117
  server.listen(CALLBACK_PORT, LOCALHOST, () => {
1107
1118
  server.removeListener("error", onError);
1108
- resolve7();
1119
+ resolve8();
1109
1120
  });
1110
1121
  });
1111
1122
  } catch (err) {
@@ -2088,6 +2099,7 @@ async function applyActivation(active, globals = {}) {
2088
2099
  }
2089
2100
  }
2090
2101
  phase = "local activation";
2102
+ clearDemoPause(root);
2091
2103
  setRepoActive(root, active);
2092
2104
  if (!active) clearHooksWired(root);
2093
2105
  if (active) {
@@ -2156,7 +2168,7 @@ async function inspectCodexHost(reload = false) {
2156
2168
  } catch {
2157
2169
  return unavailable("host-socket-unavailable");
2158
2170
  }
2159
- return new Promise((resolve7) => {
2171
+ return new Promise((resolve8) => {
2160
2172
  let finished = false;
2161
2173
  let refreshed = false;
2162
2174
  let requestId = 0;
@@ -2172,7 +2184,7 @@ async function inspectCodexHost(reload = false) {
2172
2184
  finished = true;
2173
2185
  clearTimeout(timer);
2174
2186
  socket.terminate();
2175
- resolve7(value);
2187
+ resolve8(value);
2176
2188
  };
2177
2189
  const fail = (reason) => finish({ ...unavailable(reason), ...refreshed ? { reload: "refreshed" } : {} });
2178
2190
  const timer = setTimeout(() => fail("host-timeout"), TIMEOUT_MS);
@@ -2483,7 +2495,7 @@ async function runPinnedEnsure(options) {
2483
2495
  npm_config_fetch_retry_maxtimeout: "5000",
2484
2496
  npm_config_fetch_timeout: "15000"
2485
2497
  };
2486
- return await new Promise((resolve7) => {
2498
+ return await new Promise((resolve8) => {
2487
2499
  let settled = false;
2488
2500
  let child;
2489
2501
  try {
@@ -2493,7 +2505,7 @@ async function runPinnedEnsure(options) {
2493
2505
  { env, stdio: "ignore" }
2494
2506
  );
2495
2507
  } catch {
2496
- resolve7(false);
2508
+ resolve8(false);
2497
2509
  return;
2498
2510
  }
2499
2511
  const timer = setTimeout(() => {
@@ -2504,7 +2516,7 @@ async function runPinnedEnsure(options) {
2504
2516
  if (settled) return;
2505
2517
  settled = true;
2506
2518
  clearTimeout(timer);
2507
- resolve7(result);
2519
+ resolve8(result);
2508
2520
  };
2509
2521
  timer.unref();
2510
2522
  child.once("error", () => finish(false));
@@ -3766,7 +3778,7 @@ function clearStaleArtifacts() {
3766
3778
  }
3767
3779
  }
3768
3780
  function sleep(ms) {
3769
- return new Promise((resolve7) => setTimeout(resolve7, ms));
3781
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
3770
3782
  }
3771
3783
  function spawnDaemon(options) {
3772
3784
  const file = binFile(DAEMON_BIN);
@@ -6795,7 +6807,7 @@ function registerDecisionsCommands(program2) {
6795
6807
 
6796
6808
  // src/commands/demo.ts
6797
6809
  import { createHash as createHash3 } from "crypto";
6798
- import { resolve as resolve3 } from "path";
6810
+ import { join as join8, resolve as resolve3 } from "path";
6799
6811
  import { createInterface } from "readline/promises";
6800
6812
  import { diffLines } from "diff";
6801
6813
 
@@ -6877,10 +6889,10 @@ var WARNING_EDIT = 'export const loadOrders = () => fetch("/orders");\n';
6877
6889
  var REPOSITORY_EDIT = 'import { orders } from "./shared";\nexport const saveOrder = (order: unknown) => orders.save(order);\n';
6878
6890
 
6879
6891
  // src/demo/story.ts
6880
- var DEMO_TASK = "Implement CSV export for customer records, including name and email.";
6881
- var DEMO_ORIGINAL = "Exclude customer contact information e.g. email addresses from public-facing data pipelines";
6882
- var DEMO_RATIONALE = "Customer contact details are collected for account communication, not public distribution. Keeping them out of public-facing pipelines supports our data-minimization and purpose-limitation obligations and reduces the risk of unauthorized disclosure.";
6883
- var DEMO_REPLACEMENT = "Allow customer names and email addresses in CSV exports";
6892
+ var DEMO_TASK = "Implement CSV export for user records, including name and email.";
6893
+ var DEMO_ORIGINAL = "Exclude user contact information e.g. email addresses from public-facing data pipelines";
6894
+ var DEMO_RATIONALE = "User contact details are collected for account communication, not public distribution. Keeping them out of public-facing pipelines supports our data-minimization and purpose-limitation obligations and reduces the risk of unauthorized disclosure.";
6895
+ var DEMO_REPLACEMENT = "Allow user names and email addresses in CSV exports";
6884
6896
  var DEMO_INITIAL = '// Fictional customer export project.\nexport const customerCsv = "";\n';
6885
6897
  var DEMO_ADHERE = '// Fictional customer export project.\nexport const customerCsv = "name\\nAvery";\n';
6886
6898
  var DEMO_SUPERSEDE = '// Fictional customer export project.\nexport const customerCsv = "name,email\\nAvery,avery@example.invalid";\n';
@@ -6990,6 +7002,7 @@ function demoTrustGuidance(agent) {
6990
7002
  return "Activate the installed prim hooks in your agent, then retry the exact nextAction.";
6991
7003
  }
6992
7004
  function consumeAcknowledgment(run, action, choice, reason) {
7005
+ if (run.welcomeRepo) return isRepoActiveForCapture(run.welcomeRepo) ? "repo-active" : void 0;
6993
7006
  if (run.terminal)
6994
7007
  return process.stdin.isTTY && process.stderr.isTTY ? void 0 : "terminal-required";
6995
7008
  const ack = run.acknowledgment;
@@ -7029,7 +7042,7 @@ function present(run) {
7029
7042
  return `[DEMO] How Primitive Catches Conflicts
7030
7043
 
7031
7044
  You're a new engineer on ${safeMarkdown(server.story.orgName)}'s team.
7032
- And you've been tasked with implementing CSV export functionality for customer records.
7045
+ And you've been tasked with implementing CSV export functionality for user records.
7033
7046
  Enter this prompt to do so:
7034
7047
  ${DEMO_TASK}`;
7035
7048
  if (run.stage === "conflict")
@@ -7167,6 +7180,7 @@ async function finishResolution(run, choice, reason) {
7167
7180
  run.stage = "completed";
7168
7181
  saveRun(run);
7169
7182
  finishOnboarding("completed");
7183
+ if (run.welcomeRepo) endDemoPause(run.welcomeRepo, run.id);
7170
7184
  }
7171
7185
  }
7172
7186
  async function pendingIsolation(run, isolation, action, choice, reason) {
@@ -7195,7 +7209,7 @@ ${action === "status" ? guidance : "The pre-tool hook has not verified isolation
7195
7209
  async function advanceDemo(id, action, choice, reason) {
7196
7210
  if (action === "status") {
7197
7211
  const run = readRun(id);
7198
- if (!run.terminal && !run.acknowledgment)
7212
+ if (!run.terminal && !run.welcomeRepo && !run.acknowledgment)
7199
7213
  return pendingIsolation(run, "acknowledgment-missing", action);
7200
7214
  }
7201
7215
  return await lockRunAsync(id, async (run) => {
@@ -7209,13 +7223,14 @@ async function advanceDemo(id, action, choice, reason) {
7209
7223
  run.stage = "skipped";
7210
7224
  saveRun(run);
7211
7225
  finishOnboarding("skipped");
7226
+ if (run.welcomeRepo) endDemoPause(run.welcomeRepo, run.id);
7212
7227
  return handoff(run);
7213
7228
  }
7214
7229
  if (run.version === 1)
7215
7230
  throw new Error(
7216
7231
  `Legacy tour: clean up with ${demoCommand(run, "skip")}, then run prim demo again`
7217
7232
  );
7218
- const isolation = action === "status" && !run.terminal && !run.acknowledgment ? "acknowledgment-missing" : consumeAcknowledgment(run, action, choice, reason);
7233
+ const isolation = action === "status" && !run.terminal && !run.welcomeRepo && !run.acknowledgment ? "acknowledgment-missing" : consumeAcknowledgment(run, action, choice, reason);
7219
7234
  if (isolation) return pendingIsolation(run, isolation, action, choice, reason);
7220
7235
  if (action === "status") {
7221
7236
  const server = run.server ? await demoStatus(run.server.runId) : void 0;
@@ -7262,6 +7277,7 @@ async function advanceDemo(id, action, choice, reason) {
7262
7277
  return {
7263
7278
  ...resultFor2(run),
7264
7279
  stage: "pending",
7280
+ detail: run.server.reasonCode ?? "evaluation in progress",
7265
7281
  nextAction: demoCommand(run, action, choice, reason),
7266
7282
  presentation: `${label}
7267
7283
 
@@ -7274,6 +7290,7 @@ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File uncha
7274
7290
  return {
7275
7291
  ...resultFor2(run),
7276
7292
  stage: "pending",
7293
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error)),
7277
7294
  nextAction: demoCommand(run, action, choice, reason),
7278
7295
  presentation: `Tour pending: ${terminalSafeLine(error instanceof Error ? error.message : String(error))}`,
7279
7296
  ...run.stage === "cleanup" ? { outcomePresentation: present(run) } : {}
@@ -7281,6 +7298,103 @@ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File uncha
7281
7298
  }
7282
7299
  });
7283
7300
  }
7301
+ function welcomeDemoState(run, result) {
7302
+ if (result.isolation === "repo-active") return { stage: "error", reason: "repo-active" };
7303
+ const server = run.server;
7304
+ if (result.stage === "pending" || !server)
7305
+ return { stage: "pending", ...result.detail ? { detail: result.detail } : {} };
7306
+ if (run.stage === "prompt")
7307
+ return { stage: "prompt", story: { org: safeMarkdown(server.story.orgName), task: DEMO_TASK } };
7308
+ if (run.stage === "conflict")
7309
+ return {
7310
+ stage: "conflict",
7311
+ conflict: {
7312
+ author: safeMarkdown(server.authorName),
7313
+ date: safeMarkdown(server.story.decisionDate),
7314
+ intent: DEMO_ORIGINAL,
7315
+ rationale: DEMO_RATIONALE,
7316
+ file: "customers.ts",
7317
+ code: readSample(run, "customers.ts").trimEnd()
7318
+ }
7319
+ };
7320
+ if ((run.stage === "completed" || run.stage === "cleanup") && server.choice)
7321
+ return {
7322
+ stage: "completed",
7323
+ outcome: {
7324
+ choice: server.choice,
7325
+ ...server.reason ? { reason: server.reason } : {},
7326
+ author: safeMarkdown(server.authorName),
7327
+ recipient: safeMarkdown(server.story.recipient),
7328
+ email: server.email
7329
+ },
7330
+ diff: compactDiff(DEMO_INITIAL, server.choice === "adhere" ? DEMO_ADHERE : DEMO_SUPERSEDE)
7331
+ };
7332
+ if (run.stage === "skipped") return { stage: "skipped" };
7333
+ return { stage: "pending" };
7334
+ }
7335
+ async function endWelcomeRuns() {
7336
+ for (let stale = pendingWelcomeRun(); stale; stale = pendingWelcomeRun()) {
7337
+ await advanceDemo(stale.id, "skip").catch(() => {
7338
+ if (stale.welcomeRepo) endDemoPause(stale.welcomeRepo, stale.id);
7339
+ cleanSandbox(stale);
7340
+ stale.stage = "skipped";
7341
+ saveRun(stale);
7342
+ });
7343
+ }
7344
+ }
7345
+ function pendingWelcomeRun(repo) {
7346
+ for (const id of runIds()) {
7347
+ try {
7348
+ const run = readRun(id);
7349
+ if (run.welcomeRepo && (repo === void 0 || run.welcomeRepo === repo) && !["completed", "skipped"].includes(run.stage))
7350
+ return run;
7351
+ } catch {
7352
+ }
7353
+ }
7354
+ }
7355
+ async function advanceWelcomeDemo(action, choice, reason) {
7356
+ if (action === "start") {
7357
+ const root2 = gitToplevel();
7358
+ if (!root2) return { stage: "error", reason: "not-a-repo" };
7359
+ const run2 = await withFileLock(join8(demoDirectory(), "welcome.lock"), async () => {
7360
+ const existing = pendingWelcomeRun(root2);
7361
+ if (existing?.welcomeRepo === root2) {
7362
+ const active = isRepoActiveForCapture(root2);
7363
+ const pause = readDemoPause(root2);
7364
+ if (active || pause && (pause.runId !== existing.id || pause.ending))
7365
+ pauseCaptureForDemo(root2, existing.id);
7366
+ return existing;
7367
+ }
7368
+ await endWelcomeRuns();
7369
+ const run3 = prepareRun(void 0, false, root2);
7370
+ if (isRepoActiveForCapture(root2) || readDemoPause(root2)) pauseCaptureForDemo(root2, run3.id);
7371
+ return run3;
7372
+ });
7373
+ const result2 = await advanceDemo(
7374
+ run2.id,
7375
+ run2.stage === "prepared" || run2.stage === "prompt" ? "start" : "status"
7376
+ );
7377
+ return welcomeDemoState(readRun(run2.id), result2);
7378
+ }
7379
+ const root = gitToplevel();
7380
+ if (!root) return { stage: "error", reason: "not-a-repo" };
7381
+ const run = pendingWelcomeRun(root);
7382
+ if (!run?.welcomeRepo) return { stage: "error", reason: "not-started" };
7383
+ extendDemoPause(run.welcomeRepo, run.id);
7384
+ if (action === "resolve") {
7385
+ try {
7386
+ requireResolution(choice, reason);
7387
+ } catch (error) {
7388
+ return {
7389
+ stage: "error",
7390
+ reason: "invalid",
7391
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error))
7392
+ };
7393
+ }
7394
+ }
7395
+ const result = await advanceDemo(run.id, action, choice, reason);
7396
+ return welcomeDemoState(readRun(run.id), result);
7397
+ }
7284
7398
  function parseAgent(value) {
7285
7399
  if (value === "claude") return "claude_code";
7286
7400
  if (value === void 0 || ["claude_code", "codex", "cursor", "hermes"].includes(value))
@@ -7409,14 +7523,32 @@ function registerDemoCommands(program2) {
7409
7523
  }
7410
7524
  });
7411
7525
  for (const action of ["start", "attempt", "resolve", "status", "skip"]) {
7412
- const sub = demo.command(`${action} ${action === "skip" ? "[runId]" : "<runId>"}`);
7526
+ const sub = demo.command(`${action} ${action === "status" ? "<runId>" : "[runId]"}`);
7413
7527
  if (action === "resolve")
7414
7528
  sub.requiredOption("--choice <choice>", "adhere or supersede").option("--reason <reason>", "your reason for the displayed replacement");
7415
7529
  sub.action(
7416
7530
  async (id, options) => {
7417
7531
  try {
7532
+ if (action !== "skip" && action !== "status" && !id) {
7533
+ const state = await advanceWelcomeDemo(action, options.choice, options.reason).catch(
7534
+ (error) => ({
7535
+ stage: "error",
7536
+ reason: "invalid",
7537
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error))
7538
+ })
7539
+ );
7540
+ printJson2(state);
7541
+ if (state.stage === "error") process.exitCode = 1;
7542
+ return;
7543
+ }
7418
7544
  if (action === "skip" && !id) {
7419
- finishOnboarding("skipped");
7545
+ await endWelcomeRuns();
7546
+ let finished = false;
7547
+ try {
7548
+ finished = onboardingFinished();
7549
+ } catch {
7550
+ }
7551
+ if (!finished) finishOnboarding("skipped");
7420
7552
  printJson2({
7421
7553
  fictional: true,
7422
7554
  stage: "skipped",
@@ -7562,7 +7694,7 @@ async function inspectJournalDelivery(buckets, options = {}) {
7562
7694
  // src/commands/hermes-install.ts
7563
7695
  import { existsSync as existsSync6, readFileSync as readFileSync6, rmSync as rmSync2, statSync as statSync2 } from "fs";
7564
7696
  import { homedir as homedir5 } from "os";
7565
- import { join as join8 } from "path";
7697
+ import { join as join9 } from "path";
7566
7698
  import { Document, isMap, isSeq, parseAllDocuments, stringify, visit } from "yaml";
7567
7699
  var CAPTURE_BIN2 = "prim-hook";
7568
7700
  var GATE_BIN2 = "prim-pre-tool-use";
@@ -7575,13 +7707,13 @@ var JSON_INDENT2 = 2;
7575
7707
  var CONFIG_MODE = 384;
7576
7708
  var PRIM_BINS2 = [CAPTURE_BIN2, GATE_BIN2, POST_TOOL_USE_BIN2, SESSION_START_BIN2, SESSION_END_BIN];
7577
7709
  function hermesHome() {
7578
- return process.env.HERMES_HOME ?? join8(homedir5(), ".hermes");
7710
+ return process.env.HERMES_HOME ?? join9(homedir5(), ".hermes");
7579
7711
  }
7580
7712
  function configPath() {
7581
- return join8(hermesHome(), "config.yaml");
7713
+ return join9(hermesHome(), "config.yaml");
7582
7714
  }
7583
7715
  function legacyShimPath() {
7584
- return join8(hermesHome(), "agent-hooks", "prim-shim.sh");
7716
+ return join9(hermesHome(), "agent-hooks", "prim-shim.sh");
7585
7717
  }
7586
7718
  function commandFor(bin) {
7587
7719
  return stableHookCommand(bin, HERMES_ARGS);
@@ -7912,8 +8044,8 @@ function spliceHooks(raw, hooks) {
7912
8044
  const insertAt = endMarker?.index ?? raw.length;
7913
8045
  const beforeEnd = raw.slice(0, insertAt);
7914
8046
  const afterEnd = raw.slice(insertAt);
7915
- const sep = beforeEnd.length === 0 || beforeEnd.endsWith("\n") ? "" : newline2;
7916
- return `${beforeEnd}${sep}${normalizedBlock}${afterEnd}`;
8047
+ const sep2 = beforeEnd.length === 0 || beforeEnd.endsWith("\n") ? "" : newline2;
8048
+ return `${beforeEnd}${sep2}${normalizedBlock}${afterEnd}`;
7917
8049
  }
7918
8050
  const hooksRemovalEnd = doc.get("hooks", true)?.range?.[2] ?? loc.end;
7919
8051
  const hasHooks = reconcileHooksDocument(doc, hooks);
@@ -7938,8 +8070,8 @@ function setAutoAccept(raw) {
7938
8070
  throw new Error("hooks_auto_accept must be a block-style boolean value");
7939
8071
  }
7940
8072
  const newline = raw.includes("\r\n") ? "\r\n" : "\n";
7941
- const sep = raw.length === 0 || raw.endsWith("\n") ? "" : newline;
7942
- return `${raw}${sep}hooks_auto_accept: true${newline}`;
8073
+ const sep2 = raw.length === 0 || raw.endsWith("\n") ? "" : newline;
8074
+ return `${raw}${sep2}hooks_auto_accept: true${newline}`;
7943
8075
  }
7944
8076
  function mergeKeepsYamlValid(before, after) {
7945
8077
  try {
@@ -8612,7 +8744,7 @@ function classifyCodexHooks(statuses, uncoveredWorktree = null, capturedAt, host
8612
8744
  }
8613
8745
  return {
8614
8746
  name: "codex-hooks",
8615
- status: capturedAt === void 0 || host?.trust === "review-required" || host?.trust === "disabled" ? "warn" : "ok",
8747
+ status: capturedAt === void 0 || host?.trust !== "trusted" ? "warn" : "ok",
8616
8748
  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`
8617
8749
  };
8618
8750
  }
@@ -8902,12 +9034,42 @@ function checkPreflightHosts() {
8902
9034
  };
8903
9035
  });
8904
9036
  }
9037
+ function checkDemoPause(root, now = Date.now()) {
9038
+ const pause = root ? readDemoPause(root) : void 0;
9039
+ if (!root || !pause || healDemoPause(root, pause, { now })) return [];
9040
+ const minutes = String(Math.ceil((pause.until - now) / 6e4));
9041
+ return [
9042
+ {
9043
+ name: "demo-pause",
9044
+ status: "warn",
9045
+ detail: pause.ending ? `capture resumes with your next prompt (onboarding demo finished), or in ${minutes}m` : `capture paused for the onboarding demo; it resumes when the demo ends, or in ${minutes}m`
9046
+ }
9047
+ ];
9048
+ }
9049
+ function captureReadiness(agent, checks, root, now = Date.now()) {
9050
+ const name = agent === "claude" ? "feedback-hooks" : `${agent}-hooks`;
9051
+ const check = checks.find((item) => item.name === name);
9052
+ const hooks = check?.status === "fail" ? "blocked" : check?.status === "ok" && !check.detail.startsWith("not installed") ? "ready" : "unverified";
9053
+ const observedAt = root ? lastConversationCaptured(root, agent === "claude" ? "claude_code" : agent) : void 0;
9054
+ const pause = root ? readDemoPause(root) : void 0;
9055
+ const active = root ? isRepoActiveForCapture(root) : false;
9056
+ const state = pause && pause.until > now ? "paused" : !active ? "off" : hooks === "blocked" ? "blocked" : hooks === "ready" && observedAt !== void 0 ? "observed" : "unverified";
9057
+ return {
9058
+ agent,
9059
+ state,
9060
+ hooks,
9061
+ ...state === "paused" ? { resumeOnNextPrompt: pause?.ending === true } : {},
9062
+ ...observedAt === void 0 ? {} : { observedAt },
9063
+ detail: state === "paused" ? pause?.ending ? "demo finished; capture resumes on the next trusted user-prompt hook" : "capture paused for the fictional demo" : state === "off" ? "capture is disabled for this repository" : check?.detail ?? "agent hook execution has not been verified"
9064
+ };
9065
+ }
8905
9066
  async function independentChecks() {
8906
9067
  const backend = await checkBackend();
8907
9068
  const firing = inspectFiringHere();
8908
9069
  return {
8909
9070
  before: [checkAuth()],
8910
9071
  after: [
9072
+ ...checkDemoPause(gitToplevel()),
8911
9073
  await checkJournalOrganization(),
8912
9074
  checkFeedbackHooks(),
8913
9075
  ...await checkAgentHooks(),
@@ -8940,6 +9102,7 @@ function icon(status2) {
8940
9102
  async function runDoctor(options, probes) {
8941
9103
  const checks = await collectChecks(options, probes);
8942
9104
  const { json, exitCode } = classifyDoctor(checks);
9105
+ const capture = options.agent === "claude" || options.agent === "codex" || options.agent === "cursor" || options.agent === "hermes" ? captureReadiness(options.agent, checks, gitToplevel()) : void 0;
8943
9106
  const headline = json.status === "ok" ? "\u2713 healthy" : json.status === "warn" ? "\u26A0 degraded" : "\u2717 unhealthy";
8944
9107
  process.stderr.write(`[prim] doctor: ${headline}
8945
9108
  `);
@@ -8948,7 +9111,7 @@ async function runDoctor(options, probes) {
8948
9111
  process.stderr.write(` ${icon(c.status)} ${c.name.padEnd(13)} ${c.detail}
8949
9112
  `);
8950
9113
  }
8951
- console.log(JSON.stringify(json, null, 2));
9114
+ console.log(JSON.stringify({ ...json, ...capture ? { capture } : {} }, null, 2));
8952
9115
  if (exitCode !== 0 && !process.exitCode) {
8953
9116
  process.exitCode = exitCode;
8954
9117
  }
@@ -8968,7 +9131,7 @@ function registerDoctorCommands(program2, dependencies = {}) {
8968
9131
  import { createHash as createHash4 } from "crypto";
8969
9132
  import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync7, readdirSync as readdirSync4, rmdirSync as rmdirSync2, unlinkSync as unlinkSync4 } from "fs";
8970
9133
  import { homedir as homedir6 } from "os";
8971
- import { dirname as dirname3, join as join9, resolve as resolve4 } from "path";
9134
+ import { dirname as dirname3, join as join10, resolve as resolve4 } from "path";
8972
9135
  import { fileURLToPath } from "url";
8973
9136
  var __dirname = dirname3(fileURLToPath(import.meta.url));
8974
9137
  var SKILL_NAME = "primitive-gameplan";
@@ -8987,13 +9150,13 @@ ${END}`;
8987
9150
  function packageRoot2() {
8988
9151
  let directory = __dirname;
8989
9152
  while (directory !== dirname3(directory)) {
8990
- if (existsSync8(join9(directory, "assets", SKILL_NAME, "SKILL.md"))) return directory;
9153
+ if (existsSync8(join10(directory, "assets", SKILL_NAME, "SKILL.md"))) return directory;
8991
9154
  directory = dirname3(directory);
8992
9155
  }
8993
9156
  throw new Error("Primitive gameplan assets are missing from this CLI package");
8994
9157
  }
8995
9158
  function packageVersion2(root) {
8996
- const parsed = JSON.parse(readFileSync7(join9(root, "package.json"), "utf8"));
9159
+ const parsed = JSON.parse(readFileSync7(join10(root, "package.json"), "utf8"));
8997
9160
  if (typeof parsed.version !== "string") throw new Error("CLI package version is missing");
8998
9161
  return parsed.version;
8999
9162
  }
@@ -9003,15 +9166,15 @@ function sha256(content) {
9003
9166
  function pathsFor(cwd) {
9004
9167
  const root = gitToplevel(cwd);
9005
9168
  if (root === null) throw new Error("Run prim gameplan from a Git worktree");
9006
- const skillDir = join9(root, ".agents", "skills", SKILL_NAME);
9007
- const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join9(homedir6(), ".codex");
9169
+ const skillDir = join10(root, ".agents", "skills", SKILL_NAME);
9170
+ const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join10(homedir6(), ".codex");
9008
9171
  return {
9009
9172
  root,
9010
9173
  skillDir,
9011
- manifest: join9(skillDir, MANIFEST_NAME),
9012
- agents: join9(root, "AGENTS.md"),
9013
- agentsOverride: join9(root, "AGENTS.override.md"),
9014
- userHooks: join9(codexHome, "hooks.json")
9174
+ manifest: join10(skillDir, MANIFEST_NAME),
9175
+ agents: join10(root, "AGENTS.md"),
9176
+ agentsOverride: join10(root, "AGENTS.override.md"),
9177
+ userHooks: join10(codexHome, "hooks.json")
9015
9178
  };
9016
9179
  }
9017
9180
  function readRegularFile(path) {
@@ -9076,9 +9239,9 @@ function removeBlock(content, separator) {
9076
9239
  function publicSkillPath(paths) {
9077
9240
  const codexHome = dirname3(paths.userHooks);
9078
9241
  const candidates = [
9079
- join9(paths.root, ".agents", "skills", "write-gameplan", "SKILL.md"),
9080
- join9(codexHome, "skills", "write-gameplan", "SKILL.md"),
9081
- join9(homedir6(), ".agents", "skills", "write-gameplan", "SKILL.md")
9242
+ join10(paths.root, ".agents", "skills", "write-gameplan", "SKILL.md"),
9243
+ join10(codexHome, "skills", "write-gameplan", "SKILL.md"),
9244
+ join10(homedir6(), ".agents", "skills", "write-gameplan", "SKILL.md")
9082
9245
  ];
9083
9246
  for (const path of candidates) {
9084
9247
  try {
@@ -9092,7 +9255,7 @@ function publicSkillPath(paths) {
9092
9255
  function assetContents() {
9093
9256
  const root = packageRoot2();
9094
9257
  return Object.fromEntries(
9095
- ASSET_FILES.map((file) => [file, readFileSync7(join9(root, "assets", SKILL_NAME, file), "utf8")])
9258
+ ASSET_FILES.map((file) => [file, readFileSync7(join10(root, "assets", SKILL_NAME, file), "utf8")])
9096
9259
  );
9097
9260
  }
9098
9261
  function markedHookCommands(settings) {
@@ -9141,7 +9304,7 @@ function checkOwnedFiles(paths, manifest) {
9141
9304
  }
9142
9305
  if (manifest === null) return;
9143
9306
  for (const file of ASSET_FILES) {
9144
- const path = join9(paths.skillDir, file);
9307
+ const path = join10(paths.skillDir, file);
9145
9308
  const current = readRegularFile(path);
9146
9309
  if (current !== null && sha256(current) !== manifest.files[file] && sha256(current) !== manifest.previousFiles?.[file]) {
9147
9310
  throw new Error(`Refusing modified companion file at ${path}`);
@@ -9190,7 +9353,7 @@ function install(cwd) {
9190
9353
  ensureParent: true
9191
9354
  });
9192
9355
  for (const file of ASSET_FILES) {
9193
- const path = join9(paths.skillDir, file);
9356
+ const path = join10(paths.skillDir, file);
9194
9357
  if (readRegularFile(path) !== assets[file]) {
9195
9358
  atomicWriteFile(path, assets[file], { ensureParent: true });
9196
9359
  }
@@ -9210,7 +9373,7 @@ function status(cwd) {
9210
9373
  const publicSkill = publicSkillPath(paths);
9211
9374
  const files = Object.fromEntries(
9212
9375
  ASSET_FILES.map((file) => {
9213
- const current = readRegularFile(join9(paths.skillDir, file));
9376
+ const current = readRegularFile(join10(paths.skillDir, file));
9214
9377
  return [
9215
9378
  file,
9216
9379
  current !== null && manifest !== null && sha256(current) === manifest.files[file]
@@ -9244,7 +9407,7 @@ function uninstall(cwd, removeSharedHook) {
9244
9407
  checkOwnedFiles(paths, manifest);
9245
9408
  const expected = /* @__PURE__ */ new Set(["SKILL.md", "claude-hooks.json", "scripts", MANIFEST_NAME]);
9246
9409
  const extras = readdirSync4(paths.skillDir).filter((entry) => !expected.has(entry));
9247
- const scriptsPath = join9(paths.skillDir, "scripts");
9410
+ const scriptsPath = join10(paths.skillDir, "scripts");
9248
9411
  if (existsSync8(scriptsPath)) {
9249
9412
  extras.push(...readdirSync4(scriptsPath).filter((entry) => entry !== "activate.mjs"));
9250
9413
  }
@@ -9263,7 +9426,7 @@ function uninstall(cwd, removeSharedHook) {
9263
9426
  }
9264
9427
  }
9265
9428
  for (const file of ASSET_FILES) {
9266
- const path = join9(paths.skillDir, file);
9429
+ const path = join10(paths.skillDir, file);
9267
9430
  if (existsSync8(path)) unlinkSync4(path);
9268
9431
  }
9269
9432
  unlinkSync4(paths.manifest);
@@ -9321,11 +9484,11 @@ function registerGameplanCommands(program2) {
9321
9484
 
9322
9485
  // src/commands/moves.ts
9323
9486
  import { existsSync as existsSync10, mkdirSync as mkdirSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync4 } from "fs";
9324
- import { join as join12 } from "path";
9487
+ import { join as join13 } from "path";
9325
9488
 
9326
9489
  // src/flusher.ts
9327
9490
  import { createReadStream, renameSync as renameSync3, statSync as statSync3, unlinkSync as unlinkSync5 } from "fs";
9328
- import { dirname as dirname5, join as join11 } from "path";
9491
+ import { dirname as dirname5, join as join12 } from "path";
9329
9492
 
9330
9493
  // src/dead-letter.ts
9331
9494
  import { createHash as createHash5, randomBytes as randomBytes4 } from "crypto";
@@ -9342,16 +9505,16 @@ import {
9342
9505
  rmSync as rmSync3,
9343
9506
  writeFileSync as writeFileSync3
9344
9507
  } from "fs";
9345
- import { dirname as dirname4, join as join10 } from "path";
9508
+ import { dirname as dirname4, join as join11 } from "path";
9346
9509
  var DIRECTORY_MODE = 448;
9347
9510
  var FILE_MODE = 384;
9348
9511
  var DEAD_LETTER_DIRNAME = "dead-letter";
9349
9512
  function deadLetterDirectoryForRotation(flushingPath) {
9350
- return join10(dirname4(flushingPath), DEAD_LETTER_DIRNAME);
9513
+ return join11(dirname4(flushingPath), DEAD_LETTER_DIRNAME);
9351
9514
  }
9352
9515
  function deadLetterPathForRawLine(flushingPath, rawLine) {
9353
9516
  const quarantineId = createHash5("sha256").update(rawLine).digest("hex");
9354
- return join10(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
9517
+ return join11(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
9355
9518
  }
9356
9519
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
9357
9520
  const directory = deadLetterDirectoryForRotation(flushingPath);
@@ -9365,7 +9528,7 @@ function persistDeadLetter(directory, path, quarantineId, record3, persistDirect
9365
9528
  persistDirectory(directory);
9366
9529
  return;
9367
9530
  }
9368
- const temporaryPath = join10(
9531
+ const temporaryPath = join11(
9369
9532
  directory,
9370
9533
  `.${quarantineId}.${String(process.pid)}.${randomBytes4(8).toString("hex")}.tmp`
9371
9534
  );
@@ -9397,7 +9560,7 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
9397
9560
  reason,
9398
9561
  move
9399
9562
  };
9400
- const path = join10(directory, `${record3.quarantineId}.json`);
9563
+ const path = join11(directory, `${record3.quarantineId}.json`);
9401
9564
  persistDeadLetter(directory, path, record3.quarantineId, record3, persistDirectory);
9402
9565
  return record3;
9403
9566
  }
@@ -9792,7 +9955,7 @@ async function flushOnce() {
9792
9955
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
9793
9956
  }
9794
9957
  var flushInFlight;
9795
- var FLUSH_LOCK_PATH = join11(dirname5(JOURNAL_DIR), ".flush.lock");
9958
+ var FLUSH_LOCK_PATH = join12(dirname5(JOURNAL_DIR), ".flush.lock");
9796
9959
  var FLUSH_LOCK_TIMEOUT_MS = 250;
9797
9960
  function isFlushLockContended(error) {
9798
9961
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -9924,18 +10087,18 @@ function registerMovesCommands(program2) {
9924
10087
  }
9925
10088
  });
9926
10089
  moves.command("bind").description("Pin the current directory to an org via .prim/workspace.json").requiredOption("--orgId <orgId>", "Convex organization id").action((opts) => {
9927
- const dir = join12(process.cwd(), ".prim");
10090
+ const dir = join13(process.cwd(), ".prim");
9928
10091
  if (!existsSync10(dir)) {
9929
10092
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
9930
10093
  }
9931
- const file = join12(process.cwd(), WORKSPACE_FILE);
10094
+ const file = join13(process.cwd(), WORKSPACE_FILE);
9932
10095
  writeFileSync4(file, JSON.stringify({ orgId: opts.orgId, boundAt: Date.now() }, null, 2), {
9933
10096
  mode: FILE_MODE2
9934
10097
  });
9935
10098
  console.log(`[prim] bound ${process.cwd()} to org ${opts.orgId}`);
9936
10099
  });
9937
10100
  moves.command("drop").description("Remove the .prim/workspace.json binding from the cwd").action(() => {
9938
- const file = join12(process.cwd(), WORKSPACE_FILE);
10101
+ const file = join13(process.cwd(), WORKSPACE_FILE);
9939
10102
  if (!existsSync10(file)) {
9940
10103
  console.log("[prim] no workspace binding in cwd");
9941
10104
  return;
@@ -10021,7 +10184,7 @@ import {
10021
10184
  unlinkSync as unlinkSync7,
10022
10185
  writeFileSync as writeFileSync5
10023
10186
  } from "fs";
10024
- import { join as join13 } from "path";
10187
+ import { join as join14 } from "path";
10025
10188
  var DIR_MODE2 = 448;
10026
10189
  var FILE_MODE3 = 384;
10027
10190
  function ensureDir() {
@@ -10030,7 +10193,7 @@ function ensureDir() {
10030
10193
  }
10031
10194
  }
10032
10195
  function markerPath(sessionId) {
10033
- return join13(SESSIONS_DIR, `${sessionId}.json`);
10196
+ return join14(SESSIONS_DIR, `${sessionId}.json`);
10034
10197
  }
10035
10198
  function registerSessionCommands(program2) {
10036
10199
  const session = program2.command("session").description("Decision Event Pipeline \u2014 session binding markers");
@@ -10058,7 +10221,7 @@ function registerSessionCommands(program2) {
10058
10221
  for (const f of files) {
10059
10222
  const sessionId = f.replace(/\.json$/, "");
10060
10223
  try {
10061
- const m = JSON.parse(readFileSync8(join13(SESSIONS_DIR, f), "utf-8"));
10224
+ const m = JSON.parse(readFileSync8(join14(SESSIONS_DIR, f), "utf-8"));
10062
10225
  console.log(`${sessionId} org=${m.orgId}`);
10063
10226
  } catch {
10064
10227
  }
@@ -10078,8 +10241,10 @@ function registerSessionCommands(program2) {
10078
10241
  // src/commands/setup.ts
10079
10242
  import { spawnSync as spawnSync2 } from "child_process";
10080
10243
  import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
10081
- import { join as join14 } from "path";
10244
+ import { homedir as homedir7 } from "os";
10245
+ import { join as join15, resolve as resolve5, sep } from "path";
10082
10246
  var EXIT_INCOMPLETE = 1;
10247
+ var GITHUB_CONNECT_TIMEOUT_MS = 9e4;
10083
10248
  var EXIT_USAGE3 = 2;
10084
10249
  var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
10085
10250
  var SETUP_DAEMON_DRAINS_ENV = "PRIM_SETUP_DAEMON_DRAINS";
@@ -10216,7 +10381,7 @@ function detectProjectConflicts(agent, run, globalHooksActive) {
10216
10381
  let preCommit;
10217
10382
  try {
10218
10383
  const root = gitToplevel();
10219
- const path = root && join14(root, ".git", "hooks", "pre-commit");
10384
+ const path = root && join15(root, ".git", "hooks", "pre-commit");
10220
10385
  if (path && existsSync12(path)) preCommit = readFileSync9(path, "utf-8");
10221
10386
  } catch {
10222
10387
  }
@@ -10270,6 +10435,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10270
10435
  "--migrate",
10271
10436
  "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
10272
10437
  ).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full human installation diagnostics on STDERR").option("--skip-demo", "skip the optional author story and remember that choice").action((opts) => {
10438
+ const setupAt = Date.now();
10273
10439
  const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
10274
10440
  if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
10275
10441
  process.stderr.write(
@@ -10294,16 +10460,15 @@ function registerSetupCommand(program2, dependencies = {}) {
10294
10460
  const scope = opts.scope;
10295
10461
  const self = process.argv[1];
10296
10462
  const globals = program2.optsWithGlobals();
10297
- const run = dependencies.run ?? ((args, capture = false) => {
10463
+ const run = dependencies.run ?? ((args, capture = false, timeoutMs2) => {
10298
10464
  const childArgs = opts.details ? args.filter((arg) => arg !== "--compact") : args;
10299
- const r = spawnSync2(
10300
- process.execPath,
10301
- [self, ...childArgs],
10302
- setupStepSpawnOptions(capture, process.env, {
10465
+ const r = spawnSync2(process.execPath, [self, ...childArgs], {
10466
+ ...setupStepSpawnOptions(capture, process.env, {
10303
10467
  startsDaemon: opts.daemon,
10304
10468
  compact: true
10305
- })
10306
- );
10469
+ }),
10470
+ timeout: timeoutMs2
10471
+ });
10307
10472
  if (!capture && r.status !== 0 && r.stdout) process.stderr.write(r.stdout);
10308
10473
  if (r.error) process.stderr.write(`[prim] ${r.error.message}
10309
10474
  `);
@@ -10379,6 +10544,11 @@ function registerSetupCommand(program2, dependencies = {}) {
10379
10544
  );
10380
10545
  }
10381
10546
  }
10547
+ const welcomeHandoff = scope === "user" && (agent === "claude" && (opts.agent === "claude" || Boolean(process.env.CLAUDECODE)) || agent === "codex" && Boolean(process.env.CODEX_THREAD_ID));
10548
+ if (welcomeHandoff && gitToplevel() && !isNonInteractive(globals)) {
10549
+ note("GitHub \xB7 connecting this repository (finish in your browser)\u2026");
10550
+ results.github = run(["github", "connect"], false, GITHUB_CONNECT_TIMEOUT_MS).code === 0 ? "ok" : "skipped";
10551
+ }
10382
10552
  const enableStep = setupSteps.find((candidate) => candidate.key === "enable");
10383
10553
  if (enableStep) {
10384
10554
  note(`${enableStep.label} \xB7 installing\u2026`);
@@ -10398,6 +10568,45 @@ function registerSetupCommand(program2, dependencies = {}) {
10398
10568
  health = setupChildPayload(stdout);
10399
10569
  results[healthStep.key] = code !== 0 || health?.status === "fail" ? healthStep.required ? "failed" : "skipped" : health?.status === "warn" ? "warn" : "ok";
10400
10570
  }
10571
+ if (welcomeHandoff) {
10572
+ const welcomeSkill = agent === "codex" ? codexWelcomeSkillPath() : welcomeSkillPathFor(process.cwd(), scope);
10573
+ const mainSkill = agent === "codex" ? userTargetFor("codex") : join15(homedir7(), ".claude", "skills", "prim", "SKILL.md");
10574
+ const failed2 = Object.keys(results).filter((key) => results[key] === "failed");
10575
+ if (failed2.length === 0 && opts.skipDemo && run(["demo", "skip"]).code !== 0)
10576
+ note("demo \xB7 could not remember skip; installation remains configured");
10577
+ let demoDone = false;
10578
+ try {
10579
+ demoDone = onboardingFinished();
10580
+ } catch {
10581
+ }
10582
+ note(
10583
+ failed2.length === 0 ? `setup complete \xB7 ${welcomeSkill}` : `setup incomplete (failed: ${failed2.join(", ")})`
10584
+ );
10585
+ printJson({
10586
+ setup: true,
10587
+ status: failed2.length ? "incomplete" : "complete",
10588
+ steps: results,
10589
+ ...health ? { health } : {},
10590
+ readiness: {
10591
+ installation: failed2.length ? "incomplete" : "installed",
10592
+ health: results.health ?? "not-checked",
10593
+ passiveCapture: "not-verified"
10594
+ },
10595
+ ...failed2.length ? {} : {
10596
+ welcomeSkill,
10597
+ mainSkill,
10598
+ agent,
10599
+ setupAt,
10600
+ prim: primCommand(),
10601
+ demo: demoDone ? "done" : "due",
10602
+ // For agents following the earlier setup prompt, which expects
10603
+ // setup to say what comes next. Remove with the old fields.
10604
+ instructions: "Read the file at welcomeSkill and follow it."
10605
+ }
10606
+ });
10607
+ exit(failed2.length === 0 ? 0 : EXIT_INCOMPLETE);
10608
+ return;
10609
+ }
10401
10610
  const installationSucceeded = !Object.values(results).includes("failed");
10402
10611
  let tourDue = false;
10403
10612
  if (installationSucceeded && !opts.skipDemo) {
@@ -10468,6 +10677,12 @@ function registerSetupCommand(program2, dependencies = {}) {
10468
10677
  exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
10469
10678
  });
10470
10679
  }
10680
+ function primCommand(argv = process.argv, version = packageVersion()) {
10681
+ const script = resolve5(argv[1]);
10682
+ if (version && script.includes(`${sep}node_modules${sep}`))
10683
+ return `npx --yes @primitive.ai/prim@${version}`;
10684
+ return [process.execPath, script].map((part) => `'${part.replaceAll("'", "'\\''")}'`).join(" ");
10685
+ }
10471
10686
  function setupChildPayload(stdout) {
10472
10687
  try {
10473
10688
  const value = JSON.parse(stdout);
@@ -10479,7 +10694,7 @@ function setupChildPayload(stdout) {
10479
10694
 
10480
10695
  // src/commands/statusline.ts
10481
10696
  import { readFileSync as readFileSync10 } from "fs";
10482
- import { dirname as dirname6, resolve as resolve5 } from "path";
10697
+ import { dirname as dirname6, resolve as resolve6 } from "path";
10483
10698
  import { fileURLToPath as fileURLToPath2 } from "url";
10484
10699
  var STATUSLINE_TIMEOUT_MS = 200;
10485
10700
  function readPackageVersion() {
@@ -10488,9 +10703,9 @@ function readPackageVersion() {
10488
10703
  const candidates = [
10489
10704
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
10490
10705
  // Keep resolving it while those legacy launchers transition to schema v3.
10491
- resolve5(here, "manifest.json"),
10492
- resolve5(here, "../../package.json"),
10493
- resolve5(here, "../package.json")
10706
+ resolve6(here, "manifest.json"),
10707
+ resolve6(here, "../../package.json"),
10708
+ resolve6(here, "../package.json")
10494
10709
  ];
10495
10710
  for (const path of candidates) {
10496
10711
  try {
@@ -10826,6 +11041,36 @@ function welcomeStateFromRecent(result) {
10826
11041
  }
10827
11042
  return { org: "active", recent };
10828
11043
  }
11044
+ var SAMPLE_WINDOW = 50;
11045
+ var escapeLinkText = (text) => text.replace(/\s+/gu, " ").replace(/[[\]\\]/gu, "\\$&");
11046
+ function sampleTeamDecisions(rows) {
11047
+ const byAuthor = /* @__PURE__ */ new Map();
11048
+ for (const row of rows) {
11049
+ if (row.status === "superseded") continue;
11050
+ byAuthor.set(row.authorName, [...byAuthor.get(row.authorName) ?? [], row]);
11051
+ }
11052
+ const picked = [];
11053
+ for (let round = 0; picked.length < RECENT_LIMIT; round++) {
11054
+ const next = [...byAuthor.values()].map((authored) => authored[round]).filter(Boolean);
11055
+ if (next.length === 0) break;
11056
+ picked.push(...next.slice(0, RECENT_LIMIT - picked.length));
11057
+ }
11058
+ return picked.sort((a, b) => b.classifiedAt - a.classifiedAt).flatMap((row) => {
11059
+ const id = decisionIdentifier(row.id, row.shortId);
11060
+ return id ? [
11061
+ {
11062
+ intent: escapeLinkText(row.intent),
11063
+ author: escapeLinkText(row.authorName),
11064
+ ...row.area ? { area: escapeLinkText(row.area) } : {},
11065
+ date: new Date(row.classifiedAt).toLocaleDateString("en-US", {
11066
+ month: "short",
11067
+ day: "numeric"
11068
+ }),
11069
+ url: `https://app.getprimitive.ai/decisions/${id}`
11070
+ }
11071
+ ] : [];
11072
+ });
11073
+ }
10829
11074
  function formatWelcome(state, agent, captureExcluded = false) {
10830
11075
  const cmd = (command, desc) => ` ${dim(command.padEnd(CMD_GUTTER))}${desc}`;
10831
11076
  const bullet = (text) => ` ${color("\u2022", "green")} ${text}`;
@@ -10899,7 +11144,7 @@ function welcomeJson(state, agent, captureExcluded = false) {
10899
11144
  return { welcomed: true, org: "unknown" };
10900
11145
  }
10901
11146
  function registerWelcomeCommand(program2, deps = { getClient }) {
10902
- 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(
11147
+ 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").option("--team-sample", "with --after-demo, add recent decisions spread across authors").action(
10903
11148
  async (options) => {
10904
11149
  const agent = resolveWelcomeAgent(options.agent, process.env);
10905
11150
  if (options.deferSeeding) {
@@ -10909,7 +11154,10 @@ function registerWelcomeCommand(program2, deps = { getClient }) {
10909
11154
  printJson({ welcomed: true, onboarding: "demo", seedingDeferred: true });
10910
11155
  return;
10911
11156
  }
10912
- const result = await fetchRecent({ limit: RECENT_LIMIT }, deps);
11157
+ const result = await fetchRecent(
11158
+ { limit: options.teamSample ? SAMPLE_WINDOW : RECENT_LIMIT },
11159
+ deps
11160
+ );
10913
11161
  const state = welcomeStateFromRecent(result);
10914
11162
  if (options.afterDemo) {
10915
11163
  printJson({
@@ -10917,7 +11165,10 @@ function registerWelcomeCommand(program2, deps = { getClient }) {
10917
11165
  org: state.org,
10918
11166
  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.",
10919
11167
  ...state.org === "seed" ? { seedGuidance: seedGuidanceFor(agent, options.captureExcluded) } : {},
10920
- captureExcluded: options.captureExcluded === true
11168
+ captureExcluded: options.captureExcluded === true,
11169
+ ...options.teamSample ? {
11170
+ recent: result.unavailable === void 0 ? sampleTeamDecisions(result.decisions) : []
11171
+ } : {}
10921
11172
  });
10922
11173
  return;
10923
11174
  }
@@ -11023,9 +11274,9 @@ import { readFileSync as readFileSync11 } from "fs";
11023
11274
 
11024
11275
  // src/daemon/health.ts
11025
11276
  import { chmodSync as chmodSync3, existsSync as existsSync13, mkdirSync as mkdirSync7, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
11026
- import { dirname as dirname7, join as join15 } from "path";
11277
+ import { dirname as dirname7, join as join16 } from "path";
11027
11278
  var HEARTBEAT_FRESH_MS = 9e4;
11028
- var DAEMON_HEALTH_PATH = join15(primConfigDirectory(), "daemon-health.json");
11279
+ var DAEMON_HEALTH_PATH = join16(primConfigDirectory(), "daemon-health.json");
11029
11280
 
11030
11281
  // src/lib/background-flush.ts
11031
11282
  function record2(value) {
@@ -11153,7 +11404,7 @@ function runStartupBackgroundWork(argv, env, work) {
11153
11404
 
11154
11405
  // src/index.ts
11155
11406
  var __dirname2 = dirname8(fileURLToPath3(import.meta.url));
11156
- var pkg = JSON.parse(readFileSync12(resolve6(__dirname2, "../package.json"), "utf-8"));
11407
+ var pkg = JSON.parse(readFileSync12(resolve7(__dirname2, "../package.json"), "utf-8"));
11157
11408
  runStartupBackgroundWork(process.argv.slice(2), process.env, {
11158
11409
  notify: () => updateNotifier({ pkg }).notify(),
11159
11410
  flush: () => startBackgroundFlush(),