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

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 +45 -9
  2. package/SKILL.md +7 -2
  3. package/dist/{chunk-P2O7NLVN.js → chunk-4GYJHN26.js} +117 -18
  4. package/dist/{chunk-VOC4KOOP.js → chunk-4M23K2KZ.js} +2 -2
  5. package/dist/{chunk-NQFRQ56V.js → chunk-4NUGCUQC.js} +2 -2
  6. package/dist/{chunk-GYQOZGGF.js → chunk-5ME3WD3P.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-D235RJNO.js → chunk-DQ4I3FLF.js} +3 -3
  10. package/dist/{chunk-R2NUH4B7.js → chunk-FT673ALA.js} +2 -2
  11. package/dist/{chunk-TC4FTRYO.js → chunk-HG7FJK7R.js} +2 -2
  12. package/dist/{chunk-5BQ2NEMP.js → chunk-HLMC7VS4.js} +2615 -941
  13. package/dist/{chunk-L52OD62C.js → chunk-JYPVPYW3.js} +14 -8
  14. package/dist/{chunk-2AKDX4RU.js → chunk-JZC2LHS6.js} +1 -1
  15. package/dist/{chunk-SLDZJD6Q.js → chunk-NMZSCSMY.js} +1 -1
  16. package/dist/{chunk-LTTF4MBE.js → chunk-OXW6PSPT.js} +2 -2
  17. package/dist/{chunk-EYBE724K.js → chunk-QG3GASJO.js} +4 -4
  18. package/dist/{chunk-A6M2M5A2.js → chunk-RRAC76LJ.js} +1 -1
  19. package/dist/{chunk-U67RBNIZ.js → chunk-S3ZIMGXV.js} +1 -1
  20. package/dist/{chunk-HXICZG5J.js → chunk-T2T45KF6.js} +4 -4
  21. package/dist/{chunk-LBCPRHNG.js → chunk-WN7OURQ3.js} +1 -1
  22. package/dist/{chunk-YTF6OCF3.js → chunk-ZQ7UK5US.js} +5 -5
  23. package/dist/daemon/server.js +2603 -867
  24. package/dist/hook-runtime/daemon/server.js +2603 -867
  25. package/dist/hook-runtime/hooks/post-commit.js +2671 -935
  26. package/dist/hook-runtime/hooks/post-rewrite.js +2664 -928
  27. package/dist/hook-runtime/hooks/post-tool-use.js +2606 -870
  28. package/dist/hook-runtime/hooks/pre-commit.js +9 -5
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +2625 -947
  30. package/dist/hook-runtime/hooks/prim-hook.js +2609 -873
  31. package/dist/hook-runtime/hooks/session-end.js +75 -13
  32. package/dist/hook-runtime/hooks/session-start.js +2801 -1056
  33. package/dist/hook-runtime/index.js +3741 -1556
  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 +419 -112
  44. package/dist/statusline-main.js +76 -14
  45. package/package.json +4 -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-RRAC76LJ.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-ZQ7UK5US.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-5ME3WD3P.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-JYPVPYW3.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-4NUGCUQC.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-HLMC7VS4.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);
@@ -4440,6 +4452,60 @@ function registerDaemonCommands(program2) {
4440
4452
  // src/commands/decisions.ts
4441
4453
  import { Option as Option3 } from "commander";
4442
4454
 
4455
+ // src/decisions/metadata.ts
4456
+ function decisionMakerName(row) {
4457
+ if (row.producerKind === "seed") {
4458
+ return row.decisionMaker?.kind === "external" ? terminalSafeLine(row.decisionMaker.displayName) : "Decision maker unknown";
4459
+ }
4460
+ return terminalSafeLine(row.authorName);
4461
+ }
4462
+ function validDate(at) {
4463
+ const date = new Date(at);
4464
+ return Number.isNaN(date.getTime()) ? void 0 : date;
4465
+ }
4466
+ function formatHistoricalAdoption(adoption) {
4467
+ if (!adoption) {
4468
+ return "date unknown";
4469
+ }
4470
+ const date = validDate(adoption.at);
4471
+ if (!date) {
4472
+ return "date unknown";
4473
+ }
4474
+ const iso = date.toISOString();
4475
+ const timestamp = adoption.precision === "day" ? iso.slice(0, 10) : `${iso.slice(0, adoption.precision === "minute" ? 16 : 19).replace("T", " ")} UTC`;
4476
+ switch (adoption.qualifier) {
4477
+ case "on_or_about":
4478
+ return `on or about ${timestamp}`;
4479
+ case "no_later_than":
4480
+ return `no later than ${timestamp}`;
4481
+ default:
4482
+ return timestamp;
4483
+ }
4484
+ }
4485
+ function formatDecidedAt(row) {
4486
+ if (row.producerKind === "seed") {
4487
+ return formatHistoricalAdoption(row.adoption);
4488
+ }
4489
+ return validDate(row.classifiedAt)?.toISOString() ?? "date unknown";
4490
+ }
4491
+ function pad2(value) {
4492
+ return String(value).padStart(2, "0");
4493
+ }
4494
+ function formatRecentDecisionDate(row, now) {
4495
+ if (row.producerKind === "seed") {
4496
+ return formatHistoricalAdoption(row.adoption);
4497
+ }
4498
+ const date = validDate(row.classifiedAt);
4499
+ if (!date) {
4500
+ return "date unknown";
4501
+ }
4502
+ const today = new Date(now);
4503
+ if (date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate()) {
4504
+ return `${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
4505
+ }
4506
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
4507
+ }
4508
+
4443
4509
  // src/decisions/recent.ts
4444
4510
  var RECENT_TIMEOUT_MS = 1e4;
4445
4511
  var defaultDeps = { getClient };
@@ -4499,15 +4565,10 @@ async function fetchRecent(args, deps = defaultDeps) {
4499
4565
  return { decisions: [], unavailable: `recent feed failed: ${detail}` };
4500
4566
  }
4501
4567
  }
4502
- var ZERO_PAD_TWO = 2;
4503
- function pad2(n) {
4504
- return n.toString().padStart(ZERO_PAD_TWO, "0");
4505
- }
4506
- function formatClock(ms) {
4507
- const d = new Date(ms);
4508
- return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
4509
- }
4510
4568
  function authorLabel(row) {
4569
+ if (row.producerKind === "seed") {
4570
+ return decisionMakerName(row);
4571
+ }
4511
4572
  if (!row.authorIsSelf) {
4512
4573
  return terminalSafeLine(row.authorName);
4513
4574
  }
@@ -4536,13 +4597,13 @@ function padRight(s, width) {
4536
4597
  return s.length >= width ? `${s.slice(0, width - 1)} ` : s.padEnd(width, " ");
4537
4598
  }
4538
4599
  function formatRecentRow(row) {
4539
- const clock = formatClock(row.classifiedAt);
4540
- const author = padRight(authorLabel(row), AUTHOR_WIDTH);
4600
+ const date = formatRecentDecisionDate(row, Date.now()).padEnd(10, " ");
4601
+ const author = authorLabel(row).padEnd(AUTHOR_WIDTH, " ");
4541
4602
  const area = terminalSafeLine(row.area ?? "");
4542
4603
  const areaText = area ? `\u2022 ${area}` : "\u2022";
4543
4604
  const areaPlain = padRight(areaText, AREA_WIDTH);
4544
4605
  const areaCol = area ? areaPlain.replace("\u2022", color("\u2022", colorForArea(area))) : areaPlain;
4545
- return ` ${clock} ${author}${areaCol}${terminalSafeLine(row.intent)}`;
4606
+ return ` ${date} ${author} ${areaCol}${terminalSafeLine(row.intent)}`;
4546
4607
  }
4547
4608
  var RECENT_LIMIT_CEILING = 100;
4548
4609
  function remainingHint(result) {
@@ -4758,7 +4819,8 @@ function renderCascade(result) {
4758
4819
  }
4759
4820
  const decisionLine = `\u2022 ${idColored} ${truncate(d.intent, INTENT_TRUNC)}`;
4760
4821
  const fanOutFragment = result.fanOut > 0 ? ` \xB7 ${String(result.fanOut)} decision(s) depend on this` : "";
4761
- const meta = ` ${terminalSafeLine(d.authorName)} \xB7 ${formatDate(d.classifiedAt)}${fanOutFragment} \xB7 ${terminalSafeLine(result.reversibility ?? "(unset)")} reversibility`;
4822
+ const date = d.producerKind === "seed" ? formatHistoricalAdoption(d.adoption) : formatDate(d.classifiedAt);
4823
+ const meta = ` ${decisionMakerName(d)} \xB7 ${date}${fanOutFragment} \xB7 ${terminalSafeLine(result.reversibility ?? "(unset)")} reversibility`;
4762
4824
  lines.push("", decisionLine, meta);
4763
4825
  lines.push("");
4764
4826
  lines.push("dependents");
@@ -6111,7 +6173,7 @@ function describeNode(node) {
6111
6173
  const id = renderIdentifier({ shortId: node.shortId, id: node.id });
6112
6174
  const safeArea = terminalSafeLine(node.area ?? "");
6113
6175
  const area = safeArea ? ` \u2022 ${safeArea}` : "";
6114
- return `${id}${area} ${terminalSafeLine(node.intent)} (${terminalSafeLine(node.authorName)})`;
6176
+ return `${id}${area} ${terminalSafeLine(node.intent)} (${decisionMakerName(node)})`;
6115
6177
  }
6116
6178
  function pushFiles(lines, files) {
6117
6179
  if (files.length === 0) {
@@ -6191,8 +6253,14 @@ function formatShowHuman(result) {
6191
6253
  const displayedStatus = d.stage ?? d.status;
6192
6254
  const lines = [
6193
6255
  `[prim] ${id} \u2014 ${terminalSafeLine(d.intent)}`,
6194
- ` status: ${colorStatus(displayedStatus)}${d.confirmed ? " (confirmed)" : ""} \xB7 confidence: ${terminalSafeLine(confidence)} \xB7 reversibility: ${terminalSafeLine(d.reversibility ?? "(unset)")}`
6256
+ ` status: ${colorStatus(displayedStatus)}${d.confirmed ? " (confirmed)" : ""} \xB7 confidence: ${terminalSafeLine(confidence)} \xB7 reversibility: ${terminalSafeLine(d.reversibility ?? "(unset)")}`,
6257
+ ` maker: ${decisionMakerName(d)}`,
6258
+ ` decided: ${formatDecidedAt(d)}`
6195
6259
  ];
6260
+ if (d.producerKind === "seed" && d.importedAt !== void 0) {
6261
+ const importer = d.importedByName ? ` by ${terminalSafeLine(d.importedByName)}` : "";
6262
+ lines.push(` imported: ${effectiveTimestamp(d.importedAt)}${importer}`);
6263
+ }
6196
6264
  if (d.supersededBy) {
6197
6265
  lines.push(` superseded by: ${terminalSafeLine(d.supersededBy)}`);
6198
6266
  }
@@ -6795,7 +6863,7 @@ function registerDecisionsCommands(program2) {
6795
6863
 
6796
6864
  // src/commands/demo.ts
6797
6865
  import { createHash as createHash3 } from "crypto";
6798
- import { resolve as resolve3 } from "path";
6866
+ import { join as join8, resolve as resolve3 } from "path";
6799
6867
  import { createInterface } from "readline/promises";
6800
6868
  import { diffLines } from "diff";
6801
6869
 
@@ -6877,10 +6945,10 @@ var WARNING_EDIT = 'export const loadOrders = () => fetch("/orders");\n';
6877
6945
  var REPOSITORY_EDIT = 'import { orders } from "./shared";\nexport const saveOrder = (order: unknown) => orders.save(order);\n';
6878
6946
 
6879
6947
  // 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";
6948
+ var DEMO_TASK = "Implement CSV export for user records, including name and email.";
6949
+ var DEMO_ORIGINAL = "Exclude user contact information e.g. email addresses from public-facing data pipelines";
6950
+ 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.";
6951
+ var DEMO_REPLACEMENT = "Allow user names and email addresses in CSV exports";
6884
6952
  var DEMO_INITIAL = '// Fictional customer export project.\nexport const customerCsv = "";\n';
6885
6953
  var DEMO_ADHERE = '// Fictional customer export project.\nexport const customerCsv = "name\\nAvery";\n';
6886
6954
  var DEMO_SUPERSEDE = '// Fictional customer export project.\nexport const customerCsv = "name,email\\nAvery,avery@example.invalid";\n';
@@ -6990,6 +7058,7 @@ function demoTrustGuidance(agent) {
6990
7058
  return "Activate the installed prim hooks in your agent, then retry the exact nextAction.";
6991
7059
  }
6992
7060
  function consumeAcknowledgment(run, action, choice, reason) {
7061
+ if (run.welcomeRepo) return isRepoActiveForCapture(run.welcomeRepo) ? "repo-active" : void 0;
6993
7062
  if (run.terminal)
6994
7063
  return process.stdin.isTTY && process.stderr.isTTY ? void 0 : "terminal-required";
6995
7064
  const ack = run.acknowledgment;
@@ -7029,7 +7098,7 @@ function present(run) {
7029
7098
  return `[DEMO] How Primitive Catches Conflicts
7030
7099
 
7031
7100
  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.
7101
+ And you've been tasked with implementing CSV export functionality for user records.
7033
7102
  Enter this prompt to do so:
7034
7103
  ${DEMO_TASK}`;
7035
7104
  if (run.stage === "conflict")
@@ -7167,6 +7236,7 @@ async function finishResolution(run, choice, reason) {
7167
7236
  run.stage = "completed";
7168
7237
  saveRun(run);
7169
7238
  finishOnboarding("completed");
7239
+ if (run.welcomeRepo) endDemoPause(run.welcomeRepo, run.id);
7170
7240
  }
7171
7241
  }
7172
7242
  async function pendingIsolation(run, isolation, action, choice, reason) {
@@ -7195,7 +7265,7 @@ ${action === "status" ? guidance : "The pre-tool hook has not verified isolation
7195
7265
  async function advanceDemo(id, action, choice, reason) {
7196
7266
  if (action === "status") {
7197
7267
  const run = readRun(id);
7198
- if (!run.terminal && !run.acknowledgment)
7268
+ if (!run.terminal && !run.welcomeRepo && !run.acknowledgment)
7199
7269
  return pendingIsolation(run, "acknowledgment-missing", action);
7200
7270
  }
7201
7271
  return await lockRunAsync(id, async (run) => {
@@ -7209,13 +7279,14 @@ async function advanceDemo(id, action, choice, reason) {
7209
7279
  run.stage = "skipped";
7210
7280
  saveRun(run);
7211
7281
  finishOnboarding("skipped");
7282
+ if (run.welcomeRepo) endDemoPause(run.welcomeRepo, run.id);
7212
7283
  return handoff(run);
7213
7284
  }
7214
7285
  if (run.version === 1)
7215
7286
  throw new Error(
7216
7287
  `Legacy tour: clean up with ${demoCommand(run, "skip")}, then run prim demo again`
7217
7288
  );
7218
- const isolation = action === "status" && !run.terminal && !run.acknowledgment ? "acknowledgment-missing" : consumeAcknowledgment(run, action, choice, reason);
7289
+ const isolation = action === "status" && !run.terminal && !run.welcomeRepo && !run.acknowledgment ? "acknowledgment-missing" : consumeAcknowledgment(run, action, choice, reason);
7219
7290
  if (isolation) return pendingIsolation(run, isolation, action, choice, reason);
7220
7291
  if (action === "status") {
7221
7292
  const server = run.server ? await demoStatus(run.server.runId) : void 0;
@@ -7262,6 +7333,7 @@ async function advanceDemo(id, action, choice, reason) {
7262
7333
  return {
7263
7334
  ...resultFor2(run),
7264
7335
  stage: "pending",
7336
+ detail: run.server.reasonCode ?? "evaluation in progress",
7265
7337
  nextAction: demoCommand(run, action, choice, reason),
7266
7338
  presentation: `${label}
7267
7339
 
@@ -7274,6 +7346,7 @@ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File uncha
7274
7346
  return {
7275
7347
  ...resultFor2(run),
7276
7348
  stage: "pending",
7349
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error)),
7277
7350
  nextAction: demoCommand(run, action, choice, reason),
7278
7351
  presentation: `Tour pending: ${terminalSafeLine(error instanceof Error ? error.message : String(error))}`,
7279
7352
  ...run.stage === "cleanup" ? { outcomePresentation: present(run) } : {}
@@ -7281,6 +7354,103 @@ Check pending (${run.server.reasonCode ?? "evaluation in progress"}). File uncha
7281
7354
  }
7282
7355
  });
7283
7356
  }
7357
+ function welcomeDemoState(run, result) {
7358
+ if (result.isolation === "repo-active") return { stage: "error", reason: "repo-active" };
7359
+ const server = run.server;
7360
+ if (result.stage === "pending" || !server)
7361
+ return { stage: "pending", ...result.detail ? { detail: result.detail } : {} };
7362
+ if (run.stage === "prompt")
7363
+ return { stage: "prompt", story: { org: safeMarkdown(server.story.orgName), task: DEMO_TASK } };
7364
+ if (run.stage === "conflict")
7365
+ return {
7366
+ stage: "conflict",
7367
+ conflict: {
7368
+ author: safeMarkdown(server.authorName),
7369
+ date: safeMarkdown(server.story.decisionDate),
7370
+ intent: DEMO_ORIGINAL,
7371
+ rationale: DEMO_RATIONALE,
7372
+ file: "customers.ts",
7373
+ code: readSample(run, "customers.ts").trimEnd()
7374
+ }
7375
+ };
7376
+ if ((run.stage === "completed" || run.stage === "cleanup") && server.choice)
7377
+ return {
7378
+ stage: "completed",
7379
+ outcome: {
7380
+ choice: server.choice,
7381
+ ...server.reason ? { reason: server.reason } : {},
7382
+ author: safeMarkdown(server.authorName),
7383
+ recipient: safeMarkdown(server.story.recipient),
7384
+ email: server.email
7385
+ },
7386
+ diff: compactDiff(DEMO_INITIAL, server.choice === "adhere" ? DEMO_ADHERE : DEMO_SUPERSEDE)
7387
+ };
7388
+ if (run.stage === "skipped") return { stage: "skipped" };
7389
+ return { stage: "pending" };
7390
+ }
7391
+ async function endWelcomeRuns() {
7392
+ for (let stale = pendingWelcomeRun(); stale; stale = pendingWelcomeRun()) {
7393
+ await advanceDemo(stale.id, "skip").catch(() => {
7394
+ if (stale.welcomeRepo) endDemoPause(stale.welcomeRepo, stale.id);
7395
+ cleanSandbox(stale);
7396
+ stale.stage = "skipped";
7397
+ saveRun(stale);
7398
+ });
7399
+ }
7400
+ }
7401
+ function pendingWelcomeRun(repo) {
7402
+ for (const id of runIds()) {
7403
+ try {
7404
+ const run = readRun(id);
7405
+ if (run.welcomeRepo && (repo === void 0 || run.welcomeRepo === repo) && !["completed", "skipped"].includes(run.stage))
7406
+ return run;
7407
+ } catch {
7408
+ }
7409
+ }
7410
+ }
7411
+ async function advanceWelcomeDemo(action, choice, reason) {
7412
+ if (action === "start") {
7413
+ const root2 = gitToplevel();
7414
+ if (!root2) return { stage: "error", reason: "not-a-repo" };
7415
+ const run2 = await withFileLock(join8(demoDirectory(), "welcome.lock"), async () => {
7416
+ const existing = pendingWelcomeRun(root2);
7417
+ if (existing?.welcomeRepo === root2) {
7418
+ const active = isRepoActiveForCapture(root2);
7419
+ const pause = readDemoPause(root2);
7420
+ if (active || pause && (pause.runId !== existing.id || pause.ending))
7421
+ pauseCaptureForDemo(root2, existing.id);
7422
+ return existing;
7423
+ }
7424
+ await endWelcomeRuns();
7425
+ const run3 = prepareRun(void 0, false, root2);
7426
+ if (isRepoActiveForCapture(root2) || readDemoPause(root2)) pauseCaptureForDemo(root2, run3.id);
7427
+ return run3;
7428
+ });
7429
+ const result2 = await advanceDemo(
7430
+ run2.id,
7431
+ run2.stage === "prepared" || run2.stage === "prompt" ? "start" : "status"
7432
+ );
7433
+ return welcomeDemoState(readRun(run2.id), result2);
7434
+ }
7435
+ const root = gitToplevel();
7436
+ if (!root) return { stage: "error", reason: "not-a-repo" };
7437
+ const run = pendingWelcomeRun(root);
7438
+ if (!run?.welcomeRepo) return { stage: "error", reason: "not-started" };
7439
+ extendDemoPause(run.welcomeRepo, run.id);
7440
+ if (action === "resolve") {
7441
+ try {
7442
+ requireResolution(choice, reason);
7443
+ } catch (error) {
7444
+ return {
7445
+ stage: "error",
7446
+ reason: "invalid",
7447
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error))
7448
+ };
7449
+ }
7450
+ }
7451
+ const result = await advanceDemo(run.id, action, choice, reason);
7452
+ return welcomeDemoState(readRun(run.id), result);
7453
+ }
7284
7454
  function parseAgent(value) {
7285
7455
  if (value === "claude") return "claude_code";
7286
7456
  if (value === void 0 || ["claude_code", "codex", "cursor", "hermes"].includes(value))
@@ -7409,14 +7579,32 @@ function registerDemoCommands(program2) {
7409
7579
  }
7410
7580
  });
7411
7581
  for (const action of ["start", "attempt", "resolve", "status", "skip"]) {
7412
- const sub = demo.command(`${action} ${action === "skip" ? "[runId]" : "<runId>"}`);
7582
+ const sub = demo.command(`${action} ${action === "status" ? "<runId>" : "[runId]"}`);
7413
7583
  if (action === "resolve")
7414
7584
  sub.requiredOption("--choice <choice>", "adhere or supersede").option("--reason <reason>", "your reason for the displayed replacement");
7415
7585
  sub.action(
7416
7586
  async (id, options) => {
7417
7587
  try {
7588
+ if (action !== "skip" && action !== "status" && !id) {
7589
+ const state = await advanceWelcomeDemo(action, options.choice, options.reason).catch(
7590
+ (error) => ({
7591
+ stage: "error",
7592
+ reason: "invalid",
7593
+ detail: terminalSafeLine(error instanceof Error ? error.message : String(error))
7594
+ })
7595
+ );
7596
+ printJson2(state);
7597
+ if (state.stage === "error") process.exitCode = 1;
7598
+ return;
7599
+ }
7418
7600
  if (action === "skip" && !id) {
7419
- finishOnboarding("skipped");
7601
+ await endWelcomeRuns();
7602
+ let finished = false;
7603
+ try {
7604
+ finished = onboardingFinished();
7605
+ } catch {
7606
+ }
7607
+ if (!finished) finishOnboarding("skipped");
7420
7608
  printJson2({
7421
7609
  fictional: true,
7422
7610
  stage: "skipped",
@@ -7562,7 +7750,7 @@ async function inspectJournalDelivery(buckets, options = {}) {
7562
7750
  // src/commands/hermes-install.ts
7563
7751
  import { existsSync as existsSync6, readFileSync as readFileSync6, rmSync as rmSync2, statSync as statSync2 } from "fs";
7564
7752
  import { homedir as homedir5 } from "os";
7565
- import { join as join8 } from "path";
7753
+ import { join as join9 } from "path";
7566
7754
  import { Document, isMap, isSeq, parseAllDocuments, stringify, visit } from "yaml";
7567
7755
  var CAPTURE_BIN2 = "prim-hook";
7568
7756
  var GATE_BIN2 = "prim-pre-tool-use";
@@ -7575,13 +7763,13 @@ var JSON_INDENT2 = 2;
7575
7763
  var CONFIG_MODE = 384;
7576
7764
  var PRIM_BINS2 = [CAPTURE_BIN2, GATE_BIN2, POST_TOOL_USE_BIN2, SESSION_START_BIN2, SESSION_END_BIN];
7577
7765
  function hermesHome() {
7578
- return process.env.HERMES_HOME ?? join8(homedir5(), ".hermes");
7766
+ return process.env.HERMES_HOME ?? join9(homedir5(), ".hermes");
7579
7767
  }
7580
7768
  function configPath() {
7581
- return join8(hermesHome(), "config.yaml");
7769
+ return join9(hermesHome(), "config.yaml");
7582
7770
  }
7583
7771
  function legacyShimPath() {
7584
- return join8(hermesHome(), "agent-hooks", "prim-shim.sh");
7772
+ return join9(hermesHome(), "agent-hooks", "prim-shim.sh");
7585
7773
  }
7586
7774
  function commandFor(bin) {
7587
7775
  return stableHookCommand(bin, HERMES_ARGS);
@@ -7912,8 +8100,8 @@ function spliceHooks(raw, hooks) {
7912
8100
  const insertAt = endMarker?.index ?? raw.length;
7913
8101
  const beforeEnd = raw.slice(0, insertAt);
7914
8102
  const afterEnd = raw.slice(insertAt);
7915
- const sep = beforeEnd.length === 0 || beforeEnd.endsWith("\n") ? "" : newline2;
7916
- return `${beforeEnd}${sep}${normalizedBlock}${afterEnd}`;
8103
+ const sep2 = beforeEnd.length === 0 || beforeEnd.endsWith("\n") ? "" : newline2;
8104
+ return `${beforeEnd}${sep2}${normalizedBlock}${afterEnd}`;
7917
8105
  }
7918
8106
  const hooksRemovalEnd = doc.get("hooks", true)?.range?.[2] ?? loc.end;
7919
8107
  const hasHooks = reconcileHooksDocument(doc, hooks);
@@ -7938,8 +8126,8 @@ function setAutoAccept(raw) {
7938
8126
  throw new Error("hooks_auto_accept must be a block-style boolean value");
7939
8127
  }
7940
8128
  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}`;
8129
+ const sep2 = raw.length === 0 || raw.endsWith("\n") ? "" : newline;
8130
+ return `${raw}${sep2}hooks_auto_accept: true${newline}`;
7943
8131
  }
7944
8132
  function mergeKeepsYamlValid(before, after) {
7945
8133
  try {
@@ -8612,7 +8800,7 @@ function classifyCodexHooks(statuses, uncoveredWorktree = null, capturedAt, host
8612
8800
  }
8613
8801
  return {
8614
8802
  name: "codex-hooks",
8615
- status: capturedAt === void 0 || host?.trust === "review-required" || host?.trust === "disabled" ? "warn" : "ok",
8803
+ status: capturedAt === void 0 || host?.trust !== "trusted" ? "warn" : "ok",
8616
8804
  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
8805
  };
8618
8806
  }
@@ -8902,12 +9090,42 @@ function checkPreflightHosts() {
8902
9090
  };
8903
9091
  });
8904
9092
  }
9093
+ function checkDemoPause(root, now = Date.now()) {
9094
+ const pause = root ? readDemoPause(root) : void 0;
9095
+ if (!root || !pause || healDemoPause(root, pause, { now })) return [];
9096
+ const minutes = String(Math.ceil((pause.until - now) / 6e4));
9097
+ return [
9098
+ {
9099
+ name: "demo-pause",
9100
+ status: "warn",
9101
+ 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`
9102
+ }
9103
+ ];
9104
+ }
9105
+ function captureReadiness(agent, checks, root, now = Date.now()) {
9106
+ const name = agent === "claude" ? "feedback-hooks" : `${agent}-hooks`;
9107
+ const check = checks.find((item) => item.name === name);
9108
+ const hooks = check?.status === "fail" ? "blocked" : check?.status === "ok" && !check.detail.startsWith("not installed") ? "ready" : "unverified";
9109
+ const observedAt = root ? lastConversationCaptured(root, agent === "claude" ? "claude_code" : agent) : void 0;
9110
+ const pause = root ? readDemoPause(root) : void 0;
9111
+ const active = root ? isRepoActiveForCapture(root) : false;
9112
+ const state = pause && pause.until > now ? "paused" : !active ? "off" : hooks === "blocked" ? "blocked" : hooks === "ready" && observedAt !== void 0 ? "observed" : "unverified";
9113
+ return {
9114
+ agent,
9115
+ state,
9116
+ hooks,
9117
+ ...state === "paused" ? { resumeOnNextPrompt: pause?.ending === true } : {},
9118
+ ...observedAt === void 0 ? {} : { observedAt },
9119
+ 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"
9120
+ };
9121
+ }
8905
9122
  async function independentChecks() {
8906
9123
  const backend = await checkBackend();
8907
9124
  const firing = inspectFiringHere();
8908
9125
  return {
8909
9126
  before: [checkAuth()],
8910
9127
  after: [
9128
+ ...checkDemoPause(gitToplevel()),
8911
9129
  await checkJournalOrganization(),
8912
9130
  checkFeedbackHooks(),
8913
9131
  ...await checkAgentHooks(),
@@ -8940,6 +9158,7 @@ function icon(status2) {
8940
9158
  async function runDoctor(options, probes) {
8941
9159
  const checks = await collectChecks(options, probes);
8942
9160
  const { json, exitCode } = classifyDoctor(checks);
9161
+ const capture = options.agent === "claude" || options.agent === "codex" || options.agent === "cursor" || options.agent === "hermes" ? captureReadiness(options.agent, checks, gitToplevel()) : void 0;
8943
9162
  const headline = json.status === "ok" ? "\u2713 healthy" : json.status === "warn" ? "\u26A0 degraded" : "\u2717 unhealthy";
8944
9163
  process.stderr.write(`[prim] doctor: ${headline}
8945
9164
  `);
@@ -8948,7 +9167,7 @@ async function runDoctor(options, probes) {
8948
9167
  process.stderr.write(` ${icon(c.status)} ${c.name.padEnd(13)} ${c.detail}
8949
9168
  `);
8950
9169
  }
8951
- console.log(JSON.stringify(json, null, 2));
9170
+ console.log(JSON.stringify({ ...json, ...capture ? { capture } : {} }, null, 2));
8952
9171
  if (exitCode !== 0 && !process.exitCode) {
8953
9172
  process.exitCode = exitCode;
8954
9173
  }
@@ -8968,7 +9187,7 @@ function registerDoctorCommands(program2, dependencies = {}) {
8968
9187
  import { createHash as createHash4 } from "crypto";
8969
9188
  import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync7, readdirSync as readdirSync4, rmdirSync as rmdirSync2, unlinkSync as unlinkSync4 } from "fs";
8970
9189
  import { homedir as homedir6 } from "os";
8971
- import { dirname as dirname3, join as join9, resolve as resolve4 } from "path";
9190
+ import { dirname as dirname3, join as join10, resolve as resolve4 } from "path";
8972
9191
  import { fileURLToPath } from "url";
8973
9192
  var __dirname = dirname3(fileURLToPath(import.meta.url));
8974
9193
  var SKILL_NAME = "primitive-gameplan";
@@ -8987,13 +9206,13 @@ ${END}`;
8987
9206
  function packageRoot2() {
8988
9207
  let directory = __dirname;
8989
9208
  while (directory !== dirname3(directory)) {
8990
- if (existsSync8(join9(directory, "assets", SKILL_NAME, "SKILL.md"))) return directory;
9209
+ if (existsSync8(join10(directory, "assets", SKILL_NAME, "SKILL.md"))) return directory;
8991
9210
  directory = dirname3(directory);
8992
9211
  }
8993
9212
  throw new Error("Primitive gameplan assets are missing from this CLI package");
8994
9213
  }
8995
9214
  function packageVersion2(root) {
8996
- const parsed = JSON.parse(readFileSync7(join9(root, "package.json"), "utf8"));
9215
+ const parsed = JSON.parse(readFileSync7(join10(root, "package.json"), "utf8"));
8997
9216
  if (typeof parsed.version !== "string") throw new Error("CLI package version is missing");
8998
9217
  return parsed.version;
8999
9218
  }
@@ -9003,15 +9222,15 @@ function sha256(content) {
9003
9222
  function pathsFor(cwd) {
9004
9223
  const root = gitToplevel(cwd);
9005
9224
  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");
9225
+ const skillDir = join10(root, ".agents", "skills", SKILL_NAME);
9226
+ const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join10(homedir6(), ".codex");
9008
9227
  return {
9009
9228
  root,
9010
9229
  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")
9230
+ manifest: join10(skillDir, MANIFEST_NAME),
9231
+ agents: join10(root, "AGENTS.md"),
9232
+ agentsOverride: join10(root, "AGENTS.override.md"),
9233
+ userHooks: join10(codexHome, "hooks.json")
9015
9234
  };
9016
9235
  }
9017
9236
  function readRegularFile(path) {
@@ -9076,9 +9295,9 @@ function removeBlock(content, separator) {
9076
9295
  function publicSkillPath(paths) {
9077
9296
  const codexHome = dirname3(paths.userHooks);
9078
9297
  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")
9298
+ join10(paths.root, ".agents", "skills", "write-gameplan", "SKILL.md"),
9299
+ join10(codexHome, "skills", "write-gameplan", "SKILL.md"),
9300
+ join10(homedir6(), ".agents", "skills", "write-gameplan", "SKILL.md")
9082
9301
  ];
9083
9302
  for (const path of candidates) {
9084
9303
  try {
@@ -9092,7 +9311,7 @@ function publicSkillPath(paths) {
9092
9311
  function assetContents() {
9093
9312
  const root = packageRoot2();
9094
9313
  return Object.fromEntries(
9095
- ASSET_FILES.map((file) => [file, readFileSync7(join9(root, "assets", SKILL_NAME, file), "utf8")])
9314
+ ASSET_FILES.map((file) => [file, readFileSync7(join10(root, "assets", SKILL_NAME, file), "utf8")])
9096
9315
  );
9097
9316
  }
9098
9317
  function markedHookCommands(settings) {
@@ -9141,7 +9360,7 @@ function checkOwnedFiles(paths, manifest) {
9141
9360
  }
9142
9361
  if (manifest === null) return;
9143
9362
  for (const file of ASSET_FILES) {
9144
- const path = join9(paths.skillDir, file);
9363
+ const path = join10(paths.skillDir, file);
9145
9364
  const current = readRegularFile(path);
9146
9365
  if (current !== null && sha256(current) !== manifest.files[file] && sha256(current) !== manifest.previousFiles?.[file]) {
9147
9366
  throw new Error(`Refusing modified companion file at ${path}`);
@@ -9190,7 +9409,7 @@ function install(cwd) {
9190
9409
  ensureParent: true
9191
9410
  });
9192
9411
  for (const file of ASSET_FILES) {
9193
- const path = join9(paths.skillDir, file);
9412
+ const path = join10(paths.skillDir, file);
9194
9413
  if (readRegularFile(path) !== assets[file]) {
9195
9414
  atomicWriteFile(path, assets[file], { ensureParent: true });
9196
9415
  }
@@ -9210,7 +9429,7 @@ function status(cwd) {
9210
9429
  const publicSkill = publicSkillPath(paths);
9211
9430
  const files = Object.fromEntries(
9212
9431
  ASSET_FILES.map((file) => {
9213
- const current = readRegularFile(join9(paths.skillDir, file));
9432
+ const current = readRegularFile(join10(paths.skillDir, file));
9214
9433
  return [
9215
9434
  file,
9216
9435
  current !== null && manifest !== null && sha256(current) === manifest.files[file]
@@ -9244,7 +9463,7 @@ function uninstall(cwd, removeSharedHook) {
9244
9463
  checkOwnedFiles(paths, manifest);
9245
9464
  const expected = /* @__PURE__ */ new Set(["SKILL.md", "claude-hooks.json", "scripts", MANIFEST_NAME]);
9246
9465
  const extras = readdirSync4(paths.skillDir).filter((entry) => !expected.has(entry));
9247
- const scriptsPath = join9(paths.skillDir, "scripts");
9466
+ const scriptsPath = join10(paths.skillDir, "scripts");
9248
9467
  if (existsSync8(scriptsPath)) {
9249
9468
  extras.push(...readdirSync4(scriptsPath).filter((entry) => entry !== "activate.mjs"));
9250
9469
  }
@@ -9263,7 +9482,7 @@ function uninstall(cwd, removeSharedHook) {
9263
9482
  }
9264
9483
  }
9265
9484
  for (const file of ASSET_FILES) {
9266
- const path = join9(paths.skillDir, file);
9485
+ const path = join10(paths.skillDir, file);
9267
9486
  if (existsSync8(path)) unlinkSync4(path);
9268
9487
  }
9269
9488
  unlinkSync4(paths.manifest);
@@ -9321,11 +9540,11 @@ function registerGameplanCommands(program2) {
9321
9540
 
9322
9541
  // src/commands/moves.ts
9323
9542
  import { existsSync as existsSync10, mkdirSync as mkdirSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync4 } from "fs";
9324
- import { join as join12 } from "path";
9543
+ import { join as join13 } from "path";
9325
9544
 
9326
9545
  // src/flusher.ts
9327
9546
  import { createReadStream, renameSync as renameSync3, statSync as statSync3, unlinkSync as unlinkSync5 } from "fs";
9328
- import { dirname as dirname5, join as join11 } from "path";
9547
+ import { dirname as dirname5, join as join12 } from "path";
9329
9548
 
9330
9549
  // src/dead-letter.ts
9331
9550
  import { createHash as createHash5, randomBytes as randomBytes4 } from "crypto";
@@ -9342,16 +9561,16 @@ import {
9342
9561
  rmSync as rmSync3,
9343
9562
  writeFileSync as writeFileSync3
9344
9563
  } from "fs";
9345
- import { dirname as dirname4, join as join10 } from "path";
9564
+ import { dirname as dirname4, join as join11 } from "path";
9346
9565
  var DIRECTORY_MODE = 448;
9347
9566
  var FILE_MODE = 384;
9348
9567
  var DEAD_LETTER_DIRNAME = "dead-letter";
9349
9568
  function deadLetterDirectoryForRotation(flushingPath) {
9350
- return join10(dirname4(flushingPath), DEAD_LETTER_DIRNAME);
9569
+ return join11(dirname4(flushingPath), DEAD_LETTER_DIRNAME);
9351
9570
  }
9352
9571
  function deadLetterPathForRawLine(flushingPath, rawLine) {
9353
9572
  const quarantineId = createHash5("sha256").update(rawLine).digest("hex");
9354
- return join10(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
9573
+ return join11(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
9355
9574
  }
9356
9575
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
9357
9576
  const directory = deadLetterDirectoryForRotation(flushingPath);
@@ -9365,7 +9584,7 @@ function persistDeadLetter(directory, path, quarantineId, record3, persistDirect
9365
9584
  persistDirectory(directory);
9366
9585
  return;
9367
9586
  }
9368
- const temporaryPath = join10(
9587
+ const temporaryPath = join11(
9369
9588
  directory,
9370
9589
  `.${quarantineId}.${String(process.pid)}.${randomBytes4(8).toString("hex")}.tmp`
9371
9590
  );
@@ -9397,7 +9616,7 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
9397
9616
  reason,
9398
9617
  move
9399
9618
  };
9400
- const path = join10(directory, `${record3.quarantineId}.json`);
9619
+ const path = join11(directory, `${record3.quarantineId}.json`);
9401
9620
  persistDeadLetter(directory, path, record3.quarantineId, record3, persistDirectory);
9402
9621
  return record3;
9403
9622
  }
@@ -9792,7 +10011,7 @@ async function flushOnce() {
9792
10011
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
9793
10012
  }
9794
10013
  var flushInFlight;
9795
- var FLUSH_LOCK_PATH = join11(dirname5(JOURNAL_DIR), ".flush.lock");
10014
+ var FLUSH_LOCK_PATH = join12(dirname5(JOURNAL_DIR), ".flush.lock");
9796
10015
  var FLUSH_LOCK_TIMEOUT_MS = 250;
9797
10016
  function isFlushLockContended(error) {
9798
10017
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -9924,18 +10143,18 @@ function registerMovesCommands(program2) {
9924
10143
  }
9925
10144
  });
9926
10145
  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");
10146
+ const dir = join13(process.cwd(), ".prim");
9928
10147
  if (!existsSync10(dir)) {
9929
10148
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
9930
10149
  }
9931
- const file = join12(process.cwd(), WORKSPACE_FILE);
10150
+ const file = join13(process.cwd(), WORKSPACE_FILE);
9932
10151
  writeFileSync4(file, JSON.stringify({ orgId: opts.orgId, boundAt: Date.now() }, null, 2), {
9933
10152
  mode: FILE_MODE2
9934
10153
  });
9935
10154
  console.log(`[prim] bound ${process.cwd()} to org ${opts.orgId}`);
9936
10155
  });
9937
10156
  moves.command("drop").description("Remove the .prim/workspace.json binding from the cwd").action(() => {
9938
- const file = join12(process.cwd(), WORKSPACE_FILE);
10157
+ const file = join13(process.cwd(), WORKSPACE_FILE);
9939
10158
  if (!existsSync10(file)) {
9940
10159
  console.log("[prim] no workspace binding in cwd");
9941
10160
  return;
@@ -10021,7 +10240,7 @@ import {
10021
10240
  unlinkSync as unlinkSync7,
10022
10241
  writeFileSync as writeFileSync5
10023
10242
  } from "fs";
10024
- import { join as join13 } from "path";
10243
+ import { join as join14 } from "path";
10025
10244
  var DIR_MODE2 = 448;
10026
10245
  var FILE_MODE3 = 384;
10027
10246
  function ensureDir() {
@@ -10030,7 +10249,7 @@ function ensureDir() {
10030
10249
  }
10031
10250
  }
10032
10251
  function markerPath(sessionId) {
10033
- return join13(SESSIONS_DIR, `${sessionId}.json`);
10252
+ return join14(SESSIONS_DIR, `${sessionId}.json`);
10034
10253
  }
10035
10254
  function registerSessionCommands(program2) {
10036
10255
  const session = program2.command("session").description("Decision Event Pipeline \u2014 session binding markers");
@@ -10058,7 +10277,7 @@ function registerSessionCommands(program2) {
10058
10277
  for (const f of files) {
10059
10278
  const sessionId = f.replace(/\.json$/, "");
10060
10279
  try {
10061
- const m = JSON.parse(readFileSync8(join13(SESSIONS_DIR, f), "utf-8"));
10280
+ const m = JSON.parse(readFileSync8(join14(SESSIONS_DIR, f), "utf-8"));
10062
10281
  console.log(`${sessionId} org=${m.orgId}`);
10063
10282
  } catch {
10064
10283
  }
@@ -10078,8 +10297,10 @@ function registerSessionCommands(program2) {
10078
10297
  // src/commands/setup.ts
10079
10298
  import { spawnSync as spawnSync2 } from "child_process";
10080
10299
  import { existsSync as existsSync12, readFileSync as readFileSync9 } from "fs";
10081
- import { join as join14 } from "path";
10300
+ import { homedir as homedir7 } from "os";
10301
+ import { join as join15, resolve as resolve5, sep } from "path";
10082
10302
  var EXIT_INCOMPLETE = 1;
10303
+ var GITHUB_CONNECT_TIMEOUT_MS = 9e4;
10083
10304
  var EXIT_USAGE3 = 2;
10084
10305
  var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
10085
10306
  var SETUP_DAEMON_DRAINS_ENV = "PRIM_SETUP_DAEMON_DRAINS";
@@ -10216,7 +10437,7 @@ function detectProjectConflicts(agent, run, globalHooksActive) {
10216
10437
  let preCommit;
10217
10438
  try {
10218
10439
  const root = gitToplevel();
10219
- const path = root && join14(root, ".git", "hooks", "pre-commit");
10440
+ const path = root && join15(root, ".git", "hooks", "pre-commit");
10220
10441
  if (path && existsSync12(path)) preCommit = readFileSync9(path, "utf-8");
10221
10442
  } catch {
10222
10443
  }
@@ -10270,6 +10491,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10270
10491
  "--migrate",
10271
10492
  "with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
10272
10493
  ).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) => {
10494
+ const setupAt = Date.now();
10273
10495
  const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
10274
10496
  if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
10275
10497
  process.stderr.write(
@@ -10294,16 +10516,15 @@ function registerSetupCommand(program2, dependencies = {}) {
10294
10516
  const scope = opts.scope;
10295
10517
  const self = process.argv[1];
10296
10518
  const globals = program2.optsWithGlobals();
10297
- const run = dependencies.run ?? ((args, capture = false) => {
10519
+ const run = dependencies.run ?? ((args, capture = false, timeoutMs2) => {
10298
10520
  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, {
10521
+ const r = spawnSync2(process.execPath, [self, ...childArgs], {
10522
+ ...setupStepSpawnOptions(capture, process.env, {
10303
10523
  startsDaemon: opts.daemon,
10304
10524
  compact: true
10305
- })
10306
- );
10525
+ }),
10526
+ timeout: timeoutMs2
10527
+ });
10307
10528
  if (!capture && r.status !== 0 && r.stdout) process.stderr.write(r.stdout);
10308
10529
  if (r.error) process.stderr.write(`[prim] ${r.error.message}
10309
10530
  `);
@@ -10379,6 +10600,11 @@ function registerSetupCommand(program2, dependencies = {}) {
10379
10600
  );
10380
10601
  }
10381
10602
  }
10603
+ const welcomeHandoff = scope === "user" && (agent === "claude" && (opts.agent === "claude" || Boolean(process.env.CLAUDECODE)) || agent === "codex" && Boolean(process.env.CODEX_THREAD_ID));
10604
+ if (welcomeHandoff && gitToplevel() && !isNonInteractive(globals)) {
10605
+ note("GitHub \xB7 connecting this repository (finish in your browser)\u2026");
10606
+ results.github = run(["github", "connect"], false, GITHUB_CONNECT_TIMEOUT_MS).code === 0 ? "ok" : "skipped";
10607
+ }
10382
10608
  const enableStep = setupSteps.find((candidate) => candidate.key === "enable");
10383
10609
  if (enableStep) {
10384
10610
  note(`${enableStep.label} \xB7 installing\u2026`);
@@ -10398,6 +10624,45 @@ function registerSetupCommand(program2, dependencies = {}) {
10398
10624
  health = setupChildPayload(stdout);
10399
10625
  results[healthStep.key] = code !== 0 || health?.status === "fail" ? healthStep.required ? "failed" : "skipped" : health?.status === "warn" ? "warn" : "ok";
10400
10626
  }
10627
+ if (welcomeHandoff) {
10628
+ const welcomeSkill = agent === "codex" ? codexWelcomeSkillPath() : welcomeSkillPathFor(process.cwd(), scope);
10629
+ const mainSkill = agent === "codex" ? userTargetFor("codex") : join15(homedir7(), ".claude", "skills", "prim", "SKILL.md");
10630
+ const failed2 = Object.keys(results).filter((key) => results[key] === "failed");
10631
+ if (failed2.length === 0 && opts.skipDemo && run(["demo", "skip"]).code !== 0)
10632
+ note("demo \xB7 could not remember skip; installation remains configured");
10633
+ let demoDone = false;
10634
+ try {
10635
+ demoDone = onboardingFinished();
10636
+ } catch {
10637
+ }
10638
+ note(
10639
+ failed2.length === 0 ? `setup complete \xB7 ${welcomeSkill}` : `setup incomplete (failed: ${failed2.join(", ")})`
10640
+ );
10641
+ printJson({
10642
+ setup: true,
10643
+ status: failed2.length ? "incomplete" : "complete",
10644
+ steps: results,
10645
+ ...health ? { health } : {},
10646
+ readiness: {
10647
+ installation: failed2.length ? "incomplete" : "installed",
10648
+ health: results.health ?? "not-checked",
10649
+ passiveCapture: "not-verified"
10650
+ },
10651
+ ...failed2.length ? {} : {
10652
+ welcomeSkill,
10653
+ mainSkill,
10654
+ agent,
10655
+ setupAt,
10656
+ prim: primCommand(),
10657
+ demo: demoDone ? "done" : "due",
10658
+ // For agents following the earlier setup prompt, which expects
10659
+ // setup to say what comes next. Remove with the old fields.
10660
+ instructions: "Read the file at welcomeSkill and follow it."
10661
+ }
10662
+ });
10663
+ exit(failed2.length === 0 ? 0 : EXIT_INCOMPLETE);
10664
+ return;
10665
+ }
10401
10666
  const installationSucceeded = !Object.values(results).includes("failed");
10402
10667
  let tourDue = false;
10403
10668
  if (installationSucceeded && !opts.skipDemo) {
@@ -10468,6 +10733,12 @@ function registerSetupCommand(program2, dependencies = {}) {
10468
10733
  exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE);
10469
10734
  });
10470
10735
  }
10736
+ function primCommand(argv = process.argv, version = packageVersion()) {
10737
+ const script = resolve5(argv[1]);
10738
+ if (version && script.includes(`${sep}node_modules${sep}`))
10739
+ return `npx --yes @primitive.ai/prim@${version}`;
10740
+ return [process.execPath, script].map((part) => `'${part.replaceAll("'", "'\\''")}'`).join(" ");
10741
+ }
10471
10742
  function setupChildPayload(stdout) {
10472
10743
  try {
10473
10744
  const value = JSON.parse(stdout);
@@ -10479,7 +10750,7 @@ function setupChildPayload(stdout) {
10479
10750
 
10480
10751
  // src/commands/statusline.ts
10481
10752
  import { readFileSync as readFileSync10 } from "fs";
10482
- import { dirname as dirname6, resolve as resolve5 } from "path";
10753
+ import { dirname as dirname6, resolve as resolve6 } from "path";
10483
10754
  import { fileURLToPath as fileURLToPath2 } from "url";
10484
10755
  var STATUSLINE_TIMEOUT_MS = 200;
10485
10756
  function readPackageVersion() {
@@ -10488,9 +10759,9 @@ function readPackageVersion() {
10488
10759
  const candidates = [
10489
10760
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
10490
10761
  // 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")
10762
+ resolve6(here, "manifest.json"),
10763
+ resolve6(here, "../../package.json"),
10764
+ resolve6(here, "../package.json")
10494
10765
  ];
10495
10766
  for (const path of candidates) {
10496
10767
  try {
@@ -10826,6 +11097,36 @@ function welcomeStateFromRecent(result) {
10826
11097
  }
10827
11098
  return { org: "active", recent };
10828
11099
  }
11100
+ var SAMPLE_WINDOW = 50;
11101
+ var escapeLinkText = (text) => text.replace(/\s+/gu, " ").replace(/[[\]\\]/gu, "\\$&");
11102
+ function sampleTeamDecisions(rows) {
11103
+ const byAuthor = /* @__PURE__ */ new Map();
11104
+ for (const row of rows) {
11105
+ if (row.status === "superseded") continue;
11106
+ byAuthor.set(row.authorName, [...byAuthor.get(row.authorName) ?? [], row]);
11107
+ }
11108
+ const picked = [];
11109
+ for (let round = 0; picked.length < RECENT_LIMIT; round++) {
11110
+ const next = [...byAuthor.values()].map((authored) => authored[round]).filter(Boolean);
11111
+ if (next.length === 0) break;
11112
+ picked.push(...next.slice(0, RECENT_LIMIT - picked.length));
11113
+ }
11114
+ return picked.sort((a, b) => b.classifiedAt - a.classifiedAt).flatMap((row) => {
11115
+ const id = decisionIdentifier(row.id, row.shortId);
11116
+ return id ? [
11117
+ {
11118
+ intent: escapeLinkText(row.intent),
11119
+ author: escapeLinkText(row.authorName),
11120
+ ...row.area ? { area: escapeLinkText(row.area) } : {},
11121
+ date: new Date(row.classifiedAt).toLocaleDateString("en-US", {
11122
+ month: "short",
11123
+ day: "numeric"
11124
+ }),
11125
+ url: `https://app.getprimitive.ai/decisions/${id}`
11126
+ }
11127
+ ] : [];
11128
+ });
11129
+ }
10829
11130
  function formatWelcome(state, agent, captureExcluded = false) {
10830
11131
  const cmd = (command, desc) => ` ${dim(command.padEnd(CMD_GUTTER))}${desc}`;
10831
11132
  const bullet = (text) => ` ${color("\u2022", "green")} ${text}`;
@@ -10899,7 +11200,7 @@ function welcomeJson(state, agent, captureExcluded = false) {
10899
11200
  return { welcomed: true, org: "unknown" };
10900
11201
  }
10901
11202
  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(
11203
+ 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
11204
  async (options) => {
10904
11205
  const agent = resolveWelcomeAgent(options.agent, process.env);
10905
11206
  if (options.deferSeeding) {
@@ -10909,7 +11210,10 @@ function registerWelcomeCommand(program2, deps = { getClient }) {
10909
11210
  printJson({ welcomed: true, onboarding: "demo", seedingDeferred: true });
10910
11211
  return;
10911
11212
  }
10912
- const result = await fetchRecent({ limit: RECENT_LIMIT }, deps);
11213
+ const result = await fetchRecent(
11214
+ { limit: options.teamSample ? SAMPLE_WINDOW : RECENT_LIMIT },
11215
+ deps
11216
+ );
10913
11217
  const state = welcomeStateFromRecent(result);
10914
11218
  if (options.afterDemo) {
10915
11219
  printJson({
@@ -10917,7 +11221,10 @@ function registerWelcomeCommand(program2, deps = { getClient }) {
10917
11221
  org: state.org,
10918
11222
  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
11223
  ...state.org === "seed" ? { seedGuidance: seedGuidanceFor(agent, options.captureExcluded) } : {},
10920
- captureExcluded: options.captureExcluded === true
11224
+ captureExcluded: options.captureExcluded === true,
11225
+ ...options.teamSample ? {
11226
+ recent: result.unavailable === void 0 ? sampleTeamDecisions(result.decisions) : []
11227
+ } : {}
10921
11228
  });
10922
11229
  return;
10923
11230
  }
@@ -11023,9 +11330,9 @@ import { readFileSync as readFileSync11 } from "fs";
11023
11330
 
11024
11331
  // src/daemon/health.ts
11025
11332
  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";
11333
+ import { dirname as dirname7, join as join16 } from "path";
11027
11334
  var HEARTBEAT_FRESH_MS = 9e4;
11028
- var DAEMON_HEALTH_PATH = join15(primConfigDirectory(), "daemon-health.json");
11335
+ var DAEMON_HEALTH_PATH = join16(primConfigDirectory(), "daemon-health.json");
11029
11336
 
11030
11337
  // src/lib/background-flush.ts
11031
11338
  function record2(value) {
@@ -11153,7 +11460,7 @@ function runStartupBackgroundWork(argv, env, work) {
11153
11460
 
11154
11461
  // src/index.ts
11155
11462
  var __dirname2 = dirname8(fileURLToPath3(import.meta.url));
11156
- var pkg = JSON.parse(readFileSync12(resolve6(__dirname2, "../package.json"), "utf-8"));
11463
+ var pkg = JSON.parse(readFileSync12(resolve7(__dirname2, "../package.json"), "utf-8"));
11157
11464
  runStartupBackgroundWork(process.argv.slice(2), process.env, {
11158
11465
  notify: () => updateNotifier({ pkg }).notify(),
11159
11466
  flush: () => startBackgroundFlush(),