claude-code-session-manager 0.139.0 → 0.141.0

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 (154) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
  3. package/dist/assets/History-DJMiuXyK.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
  7. package/dist/assets/Scheduler-cyr61UAC.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
  14. package/dist/assets/index-B2TQz3nd.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  33. package/scripts/README.md +1 -0
  34. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  35. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  36. package/scripts/ops-sweep.cjs +53 -23
  37. package/scripts/scheduler-mcp-server.cjs +205 -18
  38. package/src/main/build-info.json +4 -4
  39. package/src/main/config.cjs +112 -8
  40. package/src/main/docEdit.cjs +6 -1
  41. package/src/main/files.cjs +7 -27
  42. package/src/main/health.cjs +48 -15
  43. package/src/main/historyAggregator.cjs +88 -5
  44. package/src/main/historyDashboard.cjs +69 -4
  45. package/src/main/index.cjs +56 -2
  46. package/src/main/ipcSchemas.cjs +122 -16
  47. package/src/main/lib/AGENTS.md +54 -0
  48. package/src/main/lib/CLAUDE.md +1 -54
  49. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  50. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  51. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  52. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  53. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  54. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  55. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  56. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  57. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  58. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  59. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  60. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  61. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  62. package/src/main/lib/ephemeralCwd.cjs +37 -2
  63. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  64. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  65. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  66. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  67. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  68. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  69. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  70. package/src/main/lib/externalContract.cjs +31 -5
  71. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  72. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  73. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  74. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  75. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  76. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  77. package/src/main/lib/git/branchSweep.cjs +209 -4
  78. package/src/main/lib/git/gitWorktree.cjs +41 -5
  79. package/src/main/lib/guardShims.cjs +1 -1
  80. package/src/main/lib/historyRollup.cjs +26 -0
  81. package/src/main/lib/insideHome.cjs +27 -1
  82. package/src/main/lib/mcpToolCatalog.cjs +132 -13
  83. package/src/main/lib/mdDocCensus.cjs +59 -78
  84. package/src/main/lib/mdDocRefs.cjs +71 -93
  85. package/src/main/lib/mdNetworkScan.cjs +245 -250
  86. package/src/main/lib/mdReviewRecord.cjs +22 -9
  87. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  88. package/src/main/lib/opsOwnership.cjs +18 -2
  89. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  90. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  91. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  92. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  93. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  94. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  95. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  96. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  97. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  98. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  99. package/src/main/lib/prd/prdCreate.cjs +377 -23
  100. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  101. package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
  102. package/src/main/lib/process/loginItem.cjs +171 -0
  103. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  104. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  105. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  106. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  107. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  108. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  109. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  110. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  111. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  112. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  113. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  114. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  115. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  116. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  117. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  118. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  119. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  120. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  121. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  122. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  123. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  124. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  125. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  126. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  127. package/src/main/lib/tasks/taskRun.cjs +313 -0
  128. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  129. package/src/main/loginItemIpc.cjs +35 -0
  130. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  131. package/src/main/projectPages.cjs +6 -15
  132. package/src/main/promptSessionEvents.cjs +9 -1
  133. package/src/main/queueOps.cjs +260 -3
  134. package/src/main/runVerify.cjs +53 -25
  135. package/src/main/scheduler/AGENTS.md +26 -0
  136. package/src/main/scheduler/CLAUDE.md +1 -26
  137. package/src/main/scheduler/budget.cjs +239 -9
  138. package/src/main/scheduler/cancelDependents.cjs +154 -0
  139. package/src/main/scheduler/prdParser.cjs +19 -1
  140. package/src/main/scheduler/reviewLadder.cjs +36 -3
  141. package/src/main/scheduler/starvation.cjs +89 -18
  142. package/src/main/scheduler.cjs +1080 -89
  143. package/src/main/supervisor.cjs +5 -1
  144. package/src/main/templates/PRD_AUTHORING.md +14 -1
  145. package/src/main/validationQualityHandlers.cjs +199 -0
  146. package/src/main/webRemote.cjs +10 -2
  147. package/src/preload/api.d.ts +364 -21
  148. package/src/preload/apiSurface.json +89 -10
  149. package/src/preload/index.cjs +23 -2
  150. package/src/seed/agents/validator.md +19 -8
  151. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  152. package/dist/assets/History-DDnqaLyw.js +0 -2
  153. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  154. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -63,13 +63,14 @@ function resolveIsFixPlan(slug, isFixPlan) {
63
63
 
64
64
  /**
65
65
  * The ONE repo-relative path a fix plan may name for a validation record
66
- * (PRD 2883). Lives under the authored `reviews/` namespace — never under the
67
- * gitignored `scheduler/` runtime folder, where the fix-plan PRD file itself
66
+ * (PRD 2883). Lives under the `plan-records/` runtime namespace, which the
67
+ * scheduler harvests from the job worktree into the main checkout — never
68
+ * under the `scheduler/` runtime folder, where the fix-plan PRD file itself
68
69
  * sits. An unsafe/missing epicId drops the epic segment rather than
69
70
  * concatenating it into a path.
70
71
  */
71
72
  function fixPlanRecordPath(epicId, fixSlug) {
72
- const base = 'session-manager-operations/reviews/validation';
73
+ const base = 'session-manager-operations/plan-records';
73
74
  return isSafeEpicId(epicId) ? `${base}/${epicId}/${fixSlug}.md` : `${base}/${fixSlug}.md`;
74
75
  }
75
76
 
@@ -47,6 +47,16 @@ const MOSTLY_IDLE_BUSY = 0.5;
47
47
  // Both bars use Math.min(threshold, bar) so a strict threshold stays strict.
48
48
  const SATURATED_BUSY = 0.85;
49
49
 
50
+ // The busy fraction every band above judges is NET of this app's own process
51
+ // tree (PRD 3495; cpuSample.cjs readOwnProcessTicks) — the app must not gate on
52
+ // its own renderer/main load. Raw and own shares are still reported. A sampler
53
+ // without a net figure (non-Linux, legacy injection) falls back to raw.
54
+ function busyOf(sample) {
55
+ if (!sample) return null;
56
+ return Number.isFinite(sample.netBusyFraction) ? sample.netBusyFraction : sample.busyFraction;
57
+ }
58
+ const round3 = (n) => (Number.isFinite(n) ? Number(n.toFixed(3)) : null);
59
+
50
60
  // One audit row per this interval while continuously gated — the poll loop
51
61
  // ticks every 60 s and a saturated box stays saturated for a while; auditing
52
62
  // every tick would bury the signal in its own noise.
@@ -111,7 +121,8 @@ function topCpuConsumers(n = 3, { execImpl = execFileSync, platform = process.pl
111
121
  /**
112
122
  * createLoadGate(opts) → { evaluate, observe, snapshot, endHold }
113
123
  *
114
- * Decision: loadavg over threshold AND the CPU sample not mostly idle (busy
124
+ * Decision: loadavg over threshold AND the CPU sample (net of the app's own
125
+ * processes, see busyOf) not mostly idle (busy
115
126
  * fraction >= min(threshold, MOSTLY_IDLE_BUSY)) holds; over threshold with a
116
127
  * mostly idle sample stands down (standDown:true); no sample keeps the loadavg
117
128
  * verdict. observe() feeds the sampler and must run every tick.
@@ -172,6 +183,9 @@ function createLoadGate({
172
183
  threshold: typeof threshold === 'function' ? threshold() : threshold,
173
184
  loadavg1: null,
174
185
  cpuBusy: null,
186
+ cpuBusyRaw: null,
187
+ cpuBusyNet: null,
188
+ cpuOwnBusy: null,
175
189
  cpuIowait: null,
176
190
  cpuWindowMs: null,
177
191
  standDown: false,
@@ -188,8 +202,9 @@ function createLoadGate({
188
202
  const th = typeof threshold === 'function' ? threshold() : threshold;
189
203
  const ratio = c > 0 && Number.isFinite(l1) ? l1 / c : 0;
190
204
  const sample = cpu.sample();
205
+ const busy = busyOf(sample);
191
206
  const overLoad = isLoadGated(l1, c, th);
192
- const standDown = overLoad && sample !== null && sample.busyFraction < Math.min(th, MOSTLY_IDLE_BUSY);
207
+ const standDown = overLoad && busy !== null && busy < Math.min(th, MOSTLY_IDLE_BUSY);
193
208
  const wouldGate = overLoad && !standDown;
194
209
 
195
210
  const holding = wouldGate && !bypass;
@@ -198,7 +213,7 @@ function createLoadGate({
198
213
  lastHeldAt = t;
199
214
  }
200
215
  // A yield stays armed until the caller proves a launch with endHold().
201
- const saturated = sample !== null && sample.busyFraction >= Math.min(th, SATURATED_BUSY);
216
+ const saturated = busy !== null && busy >= Math.min(th, SATURATED_BUSY);
202
217
  const atLimit = holding && heldMs >= yieldAfterMs;
203
218
  const yielded = atLimit && !saturated;
204
219
  const gated = holding && !yielded;
@@ -225,7 +240,10 @@ function createLoadGate({
225
240
  ratio: Number(ratio.toFixed(3)),
226
241
  threshold: th,
227
242
  loadavg1: Number.isFinite(l1) ? Number(l1.toFixed(2)) : null,
228
- cpuBusy: sample ? Number(sample.busyFraction.toFixed(3)) : null,
243
+ cpuBusy: round3(busy), // the decision value (net of own processes)
244
+ cpuBusyRaw: sample ? round3(sample.busyFraction) : null,
245
+ cpuBusyNet: round3(busy),
246
+ cpuOwnBusy: sample && Number.isFinite(sample.ownFraction) ? round3(sample.ownFraction) : null,
229
247
  cpuIowait: sample ? Number(sample.iowaitFraction.toFixed(3)) : null,
230
248
  cpuWindowMs: sample ? sample.windowMs : null,
231
249
  standDown,
@@ -257,8 +275,8 @@ function createLoadGate({
257
275
  const [l1] = loadavg();
258
276
  const th = typeof threshold === 'function' ? threshold() : threshold;
259
277
  if (!isLoadGated(l1, cores(), th)) return false;
260
- const sample = cpu.sample();
261
- return sample !== null && sample.busyFraction >= Math.min(th, SATURATED_BUSY);
278
+ const busy = busyOf(cpu.sample());
279
+ return busy !== null && busy >= Math.min(th, SATURATED_BUSY);
262
280
  }
263
281
 
264
282
  return { evaluate, observe, snapshot, endHold, isSaturated };
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * planRecordHarvest.cjs — copy the plan records a job wrote inside its git
5
+ * worktree (`<ops>/plan-records/<epic-id>/*.md`, never committed) into the
6
+ * main checkout's `plan-records/<epic-id>/`, writing as the namespace owner
7
+ * ('scheduler'), so they survive worktree teardown without a commit.
8
+ *
9
+ * Never throws: every refusal is reported in `skipped` with a reason.
10
+ */
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+ const { OPS_ROOT_DIR, opsPath, checkOpsWrite, assertOpsWrite } = require('../opsOwnership.cjs');
15
+ const { writeTextAtomicSync } = require('../util/atomicFs.cjs');
16
+
17
+ const NAMESPACE = 'plan-records';
18
+ const WRITER = 'scheduler';
19
+ const MAX_BYTES = 1024 * 1024;
20
+ const NAME_RE = /^[A-Za-z0-9._-]+\.md$/;
21
+ const EPIC_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
22
+
23
+ function errMsg(e) {
24
+ return e && e.message ? e.message : String(e);
25
+ }
26
+
27
+ /**
28
+ * harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl })
29
+ * → { copied: string[], skipped: { path, reason }[] }
30
+ * `copied` holds destination absolute paths.
31
+ */
32
+ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl = fs } = {}) {
33
+ /** @type {string[]} */
34
+ const copied = [];
35
+ /** @type {{ path: string, reason: string }[]} */
36
+ const skipped = [];
37
+ try {
38
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) {
39
+ skipped.push({ path: String(epicId), reason: 'unsafe epicId' });
40
+ return { copied, skipped };
41
+ }
42
+ if (typeof worktreeDir !== 'string' || !path.isAbsolute(worktreeDir)
43
+ || typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
44
+ skipped.push({ path: String(worktreeDir), reason: 'worktreeDir and projectRoot must be absolute paths' });
45
+ return { copied, skipped };
46
+ }
47
+ if (path.resolve(worktreeDir) === path.resolve(projectRoot)) return { copied, skipped };
48
+
49
+ const srcDir = path.join(path.resolve(worktreeDir), OPS_ROOT_DIR, NAMESPACE, epicId);
50
+ let destDir;
51
+ try {
52
+ destDir = path.resolve(opsPath(projectRoot, NAMESPACE, epicId));
53
+ } catch (e) {
54
+ skipped.push({ path: srcDir, reason: `destination refused: ${errMsg(e)}` });
55
+ return { copied, skipped };
56
+ }
57
+ if (destDir === srcDir) return { copied, skipped };
58
+
59
+ let srcStat;
60
+ try {
61
+ srcStat = fsImpl.lstatSync(srcDir);
62
+ } catch {
63
+ return { copied, skipped }; // no records written by this job
64
+ }
65
+ if (!srcStat.isDirectory()) {
66
+ skipped.push({ path: srcDir, reason: 'source is not a directory' });
67
+ return { copied, skipped };
68
+ }
69
+
70
+ let names;
71
+ try {
72
+ names = fsImpl.readdirSync(srcDir).map(String).sort();
73
+ } catch (e) {
74
+ skipped.push({ path: srcDir, reason: `cannot list source: ${errMsg(e)}` });
75
+ return { copied, skipped };
76
+ }
77
+
78
+ for (const name of names) {
79
+ const src = path.join(srcDir, name);
80
+ try {
81
+ if (!NAME_RE.test(name)) { skipped.push({ path: src, reason: 'name not allowed' }); continue; }
82
+ const st = fsImpl.lstatSync(src);
83
+ if (st.isSymbolicLink()) { skipped.push({ path: src, reason: 'symlink' }); continue; }
84
+ if (st.isDirectory()) { skipped.push({ path: src, reason: 'directory' }); continue; }
85
+ if (!st.isFile()) { skipped.push({ path: src, reason: 'not a regular file' }); continue; }
86
+ if (st.size > MAX_BYTES) { skipped.push({ path: src, reason: `oversize (${st.size} > ${MAX_BYTES} bytes)` }); continue; }
87
+
88
+ const dest = path.resolve(opsPath(projectRoot, NAMESPACE, epicId, name));
89
+ if (path.dirname(dest) !== destDir) { skipped.push({ path: src, reason: 'destination escapes plan-records folder' }); continue; }
90
+ const verdict = checkOpsWrite(dest, WRITER);
91
+ if (!verdict.ok) { skipped.push({ path: src, reason: `write refused: ${verdict.error}` }); continue; }
92
+ assertOpsWrite(dest, WRITER);
93
+
94
+ const text = fsImpl.readFileSync(src, 'utf8');
95
+ if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) { skipped.push({ path: src, reason: 'oversize after read' }); continue; }
96
+ writeTextAtomicSync(dest, text);
97
+ copied.push(dest);
98
+ } catch (e) {
99
+ skipped.push({ path: src, reason: `copy failed: ${errMsg(e)}` });
100
+ }
101
+ }
102
+ } catch (e) {
103
+ skipped.push({ path: String(worktreeDir), reason: `harvest failed: ${errMsg(e)}` });
104
+ }
105
+ return { copied, skipped };
106
+ }
107
+
108
+ module.exports = { harvestPlanRecords, MAX_BYTES, NAME_RE, EPIC_ID_RE };
@@ -0,0 +1,144 @@
1
+ /**
2
+ * planRecordRetention — retention sweep for `session-manager-operations/plan-records/<epic-id>/`.
3
+ *
4
+ * prunePlanRecords({ projectRoot, epicStatus, now, days, dryRun, fsImpl })
5
+ * → { removed: string[] (epic ids), kept: number }. Never throws.
6
+ *
7
+ * A folder is removed when:
8
+ * - epicStatus(id) → { status: 'completed', completedAt } with completedAt older than `days`, or
9
+ * - epicStatus(id) → null (orphan) and its newest file mtime is older than `days`.
10
+ * Never removed: proposed/active (any non-completed) Epics, a completed Epic with no
11
+ * parseable completedAt, README.md / .gitignore (or any non-directory), symlinks, and
12
+ * folder names that fail SAFE_ID_RE. A throwing epicStatus keeps the folder.
13
+ * dryRun reports the exact same list and deletes nothing.
14
+ *
15
+ * Writes go through opsPath(projectRoot, 'plan-records', id) and the opsOwnership write
16
+ * guard as writer 'scheduler' (the namespace owner). epicStatus and fsImpl are injected
17
+ * so the module is pure; defaultEpicStatus(projectRoot) reads prompt-sessions/<id>.json.
18
+ * days defaults to opsRetentionSettings.read().planRecordsDays.
19
+ */
20
+ 'use strict';
21
+
22
+ const nodeFs = require('node:fs');
23
+ const path = require('node:path');
24
+ const opsOwnership = require('../opsOwnership.cjs');
25
+ const { readJsonOrSync } = require('../util/atomicFs.cjs');
26
+
27
+ const WRITER = 'scheduler';
28
+ const NS = 'plan-records';
29
+ const DAY_MS = 86400000;
30
+ const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
31
+ const RESERVED = new Set(['README.md', '.gitignore']);
32
+
33
+ function toMs(v) {
34
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
35
+ if (typeof v === 'string' && v) {
36
+ const ms = Date.parse(v);
37
+ if (Number.isFinite(ms)) return ms;
38
+ }
39
+ return null;
40
+ }
41
+
42
+ function isSafeId(name) {
43
+ return typeof name === 'string' && SAFE_ID_RE.test(name) && name !== '.' && name !== '..' && !RESERVED.has(name);
44
+ }
45
+
46
+ /** Newest mtime of any file under dir (recursive, symlinks not followed); dir mtime when empty. */
47
+ function newestMtime(fsImpl, dir) {
48
+ let newest = null;
49
+ const walk = (d) => {
50
+ let entries;
51
+ try { entries = fsImpl.readdirSync(d, { withFileTypes: true }); } catch { return; }
52
+ for (const e of entries) {
53
+ const p = path.join(d, e.name);
54
+ if (e.isDirectory()) { walk(p); continue; }
55
+ try {
56
+ const st = fsImpl.lstatSync(p);
57
+ if (newest === null || st.mtimeMs > newest) newest = st.mtimeMs;
58
+ } catch { /* vanished */ }
59
+ }
60
+ };
61
+ walk(dir);
62
+ if (newest === null) {
63
+ try { newest = fsImpl.lstatSync(dir).mtimeMs; } catch { /* vanished */ }
64
+ }
65
+ return newest;
66
+ }
67
+
68
+ function resolveDays(days) {
69
+ if (typeof days === 'number' && Number.isFinite(days) && days > 0) return days;
70
+ try {
71
+ return require('../opsRetentionSettings.cjs').read().planRecordsDays;
72
+ } catch {
73
+ return 14;
74
+ }
75
+ }
76
+
77
+ function isEligible({ id, dir, epicStatus, cutoffMs, fsImpl }) {
78
+ let st;
79
+ try { st = epicStatus(id); } catch { return false; }
80
+ if (st === null || st === undefined) {
81
+ const m = newestMtime(fsImpl, dir);
82
+ return m !== null && m < cutoffMs;
83
+ }
84
+ if (!st || typeof st !== 'object' || st.status !== 'completed') return false;
85
+ const done = toMs(st.completedAt);
86
+ return done !== null && done < cutoffMs;
87
+ }
88
+
89
+ function prunePlanRecords(opts) {
90
+ const result = { removed: [], kept: 0 };
91
+ try {
92
+ const o = opts || {};
93
+ const fsImpl = o.fsImpl || nodeFs;
94
+ if (typeof o.epicStatus !== 'function') return result;
95
+ const now = typeof o.now === 'number' && Number.isFinite(o.now) ? o.now : Date.now();
96
+ const cutoffMs = now - resolveDays(o.days) * DAY_MS;
97
+ const root = opsOwnership.opsPath(o.projectRoot, NS);
98
+ let entries;
99
+ try { entries = fsImpl.readdirSync(root, { withFileTypes: true }); } catch { return result; }
100
+ for (const e of entries) {
101
+ if (!e.isDirectory() || e.isSymbolicLink() || !isSafeId(e.name)) continue;
102
+ const id = e.name;
103
+ let target;
104
+ try {
105
+ target = opsOwnership.opsPath(o.projectRoot, NS, id);
106
+ if (!isEligible({ id, dir: target, epicStatus: o.epicStatus, cutoffMs, fsImpl })) {
107
+ result.kept += 1;
108
+ continue;
109
+ }
110
+ opsOwnership.assertOpsWrite(target, WRITER);
111
+ if (!o.dryRun) fsImpl.rmSync(target, { recursive: true, force: true });
112
+ result.removed.push(id);
113
+ } catch (err) {
114
+ console.warn(`[planRecordRetention] keep ${id}:`, err && err.message);
115
+ result.kept += 1;
116
+ }
117
+ }
118
+ } catch (err) {
119
+ console.warn('[planRecordRetention] sweep skipped:', err && err.message);
120
+ }
121
+ return result;
122
+ }
123
+
124
+ /**
125
+ * defaultEpicStatus(projectRoot) → epicStatus(id) reading prompt-sessions/<id>.json
126
+ * (live mirror is flat; a completed archive nests the record under `session`).
127
+ * Returns null when the file is absent/unreadable or carries no status. Never throws.
128
+ */
129
+ function defaultEpicStatus(projectRoot) {
130
+ return (id) => {
131
+ try {
132
+ if (!isSafeId(id)) return null;
133
+ const doc = readJsonOrSync(opsOwnership.opsPath(projectRoot, 'prompt-sessions', `${id}.json`), null);
134
+ if (!doc || typeof doc !== 'object') return null;
135
+ const rec = doc.session && typeof doc.session === 'object' ? doc.session : doc;
136
+ if (typeof rec.status !== 'string') return null;
137
+ return { status: rec.status, completedAt: rec.completedAt ?? null };
138
+ } catch {
139
+ return null;
140
+ }
141
+ };
142
+ }
143
+
144
+ module.exports = { prunePlanRecords, defaultEpicStatus };
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+ /**
3
+ * preflightCheck — the optional PRD precondition command (`preflight`).
4
+ *
5
+ * A PRD whose work needs an external precondition a person controls (a store
6
+ * agreement, billing, DNS, OAuth consent) declares one cheap, read-only
7
+ * command. The scheduler holds the job while it exits non-zero and resumes it
8
+ * once it exits 0. This module is the pure-plus-runner core; wiring lives in
9
+ * the scheduler.
10
+ *
11
+ * No second gate grammar: a preflight is validated by prdGateFiles'
12
+ * validateGate (as a one-entry gate) and run by definitionOfDone's
13
+ * runIsolatedSequence — the same no-shell tokenizer + spawner the gate shadow
14
+ * uses. The read-only contract is not enforced beyond that validator.
15
+ */
16
+
17
+ const { validateGate } = require('../prd/prdGateFiles.cjs');
18
+ const { parseChain, isNoneGate, runIsolatedSequence } = require('./definitionOfDone.cjs');
19
+
20
+ const PREFLIGHT_MAX_CHARS = 500;
21
+ const OUTPUT_TAIL_CHARS = 500;
22
+ const DEFAULT_TIMEOUT_MS = 60_000;
23
+ const MIN_MS = 60 * 1000;
24
+ const DELAY_LADDER_MS = [10 * MIN_MS, 20 * MIN_MS, 40 * MIN_MS, 60 * MIN_MS];
25
+
26
+ /**
27
+ * @param {unknown} value
28
+ * @returns {string|null} trimmed command, or null when empty/absent.
29
+ * @throws {Error} for a multi-line, over-long or gate-invalid value.
30
+ */
31
+ function normalizePreflight(value) {
32
+ if (value === undefined || value === null) return null;
33
+ if (typeof value !== 'string') throw new Error('preflight must be a string command.');
34
+ const cmd = value.trim();
35
+ if (!cmd) return null;
36
+ if (/[\r\n]/.test(cmd)) throw new Error('preflight must be one line (no newline).');
37
+ if (cmd.length > PREFLIGHT_MAX_CHARS) {
38
+ throw new Error(`preflight must be at most ${PREFLIGHT_MAX_CHARS} chars (got ${cmd.length}).`);
39
+ }
40
+ if (isNoneGate(cmd)) throw new Error('preflight "none" is not a command — omit preflight instead.');
41
+ const v = validateGate([cmd]);
42
+ if (!v.ok) throw new Error(`preflight is not a valid command: ${v.error.replace(/^gate /, '')}`);
43
+ return cmd;
44
+ }
45
+
46
+ /** Re-check delay for the Nth failed check: 10, 20, 40, then 60 minutes. */
47
+ function preflightDelayMs(attempt) {
48
+ const n = Number.isFinite(attempt) && attempt >= 1 ? Math.floor(attempt) : 1;
49
+ return DELAY_LADDER_MS[Math.min(n, DELAY_LADDER_MS.length) - 1];
50
+ }
51
+
52
+ /**
53
+ * Run the preflight command once, without a shell.
54
+ * Every step's timeout is capped at timeoutMs.
55
+ *
56
+ * @returns {Promise<{ok:boolean, exitCode:number|null, timedOut:boolean, outputTail:string}>}
57
+ */
58
+ async function runPreflight({ command, cwd, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
59
+ const steps = typeof command === 'string' ? parseChain(command.trim()) : [];
60
+ if (!steps.length) {
61
+ return { ok: false, exitCode: null, timedOut: false, outputTail: 'preflight command could not be parsed' };
62
+ }
63
+ const sequence = steps.map((s) => ({ ...s, timeoutMs: Math.min(s.timeoutMs, timeoutMs) }));
64
+ const r = await runIsolatedSequence(sequence, { cwd });
65
+ const results = Array.isArray(r.results) ? r.results : [];
66
+ const last = results[results.length - 1];
67
+ const combined = results.map((x) => x.outputTail || '').join('');
68
+ const timedOut = results.some((x) => x.timedOut === true);
69
+ return {
70
+ ok: r.status === 'green' && !timedOut,
71
+ exitCode: last && typeof last.code === 'number' ? last.code : null,
72
+ timedOut,
73
+ outputTail: combined.slice(-OUTPUT_TAIL_CHARS),
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Next hold state after a failed preflight check.
79
+ *
80
+ * @param {object|null|undefined} prev previous hold (or none)
81
+ * @param {{exitCode:number|null, outputTail:string}} result runPreflight result
82
+ * @param {number} now epoch ms
83
+ * @param {string} failText the person-facing "what to do" text
84
+ */
85
+ function armPreflightHold(prev, result, now, failText) {
86
+ const attempts = prev && Number.isFinite(prev.attempts) ? prev.attempts + 1 : 1;
87
+ return {
88
+ since: prev && prev.since ? prev.since : new Date(now).toISOString(),
89
+ attempts,
90
+ nextAt: new Date(now + preflightDelayMs(attempts)).toISOString(),
91
+ lastExit: result && typeof result.exitCode === 'number' ? result.exitCode : null,
92
+ lastOutputTail: result && typeof result.outputTail === 'string' ? result.outputTail : '',
93
+ failText,
94
+ };
95
+ }
96
+
97
+ module.exports = { normalizePreflight, preflightDelayMs, runPreflight, armPreflightHold };
@@ -570,6 +570,13 @@ async function writeSplit(state, defaultCwd) {
570
570
  byCwd.get(cwd).push(job);
571
571
  }
572
572
  for (const [cwd, jobs] of byCwd) {
573
+ // Never materialize a missing project root: a deleted cwd remembered only
574
+ // as a transcript dir got {"jobs": []} recreated every reconcile pass
575
+ // (2026-11-22, /tmp/sm-sbx-probe-*/work + ~/.sm-sbx-chk-*/work).
576
+ if (typeof cwd === 'string' && path.isAbsolute(cwd) && !fs.existsSync(cwd)) {
577
+ console.warn('[queueStore] skip queue write for missing cwd', cwd);
578
+ continue;
579
+ }
573
580
  const file = queuePathOrSkip(cwd, 'writeSplit');
574
581
  if (!file) continue;
575
582
  try {
@@ -168,6 +168,26 @@ const SENTINEL_PASS_RE = /SCHEDULER_VERDICT:\s*PASS/;
168
168
  const STUCK_LOOP_WINDOW = 40; // "final lines" per AC
169
169
  const POST_AC_OVERRUN_MIN_TAIL_FRACTION = 0.3;
170
170
 
171
+ /**
172
+ * True when a log line is a stream-json result event whose `--json-schema`
173
+ * structured_output says schedulerVerdict PASS — judged by runVerify.cjs's
174
+ * scanSentinel (the one SCHEDULER_VERDICT parser). Under --json-schema the
175
+ * result text is the JSON string, so SENTINEL_PASS_RE never sees a PASS line.
176
+ */
177
+ function structuredPassLine(line) {
178
+ if (!line.includes('"type":"result"') || !line.includes('"structured_output"')) return false;
179
+ try {
180
+ const obj = JSON.parse(line.trim());
181
+ const so = obj && obj.type === 'result' ? obj.structured_output : null;
182
+ if (!so || typeof so !== 'object' || Array.isArray(so)) return false;
183
+ // Lazy require: runVerify.cjs is large; only result lines pay for it.
184
+ const { scanSentinel } = require('../../runVerify.cjs');
185
+ return scanSentinel({ resultText: '', structuredOutput: so }, []) === 'pass';
186
+ } catch {
187
+ return false;
188
+ }
189
+ }
190
+
171
191
  /**
172
192
  * Drop every stream-json harness init event (`"type":"system"` +
173
193
  * `"subtype":"init"`) from a log tail. That line names every available tool
@@ -247,7 +267,7 @@ function classifyFailure({ verdict, logTail: rawLogTail }) {
247
267
  });
248
268
  if (lastAcIdx >= 0 && lines.length > 0) {
249
269
  const tailAfterAc = lines.slice(lastAcIdx + 1);
250
- const passSeenAfter = tailAfterAc.some((l) => SENTINEL_PASS_RE.test(l));
270
+ const passSeenAfter = tailAfterAc.some((l) => SENTINEL_PASS_RE.test(l) || structuredPassLine(l));
251
271
  const remainingFraction = tailAfterAc.length / lines.length;
252
272
  if (!passSeenAfter && remainingFraction > POST_AC_OVERRUN_MIN_TAIL_FRACTION) {
253
273
  return FAILURE_CLASSES.POST_AC_OVERRUN;
@@ -289,12 +289,18 @@ function mapOutcomeToGateOutcome(outcome) {
289
289
  * was stamped 'passed'). 'passed' requires the run's own LAST
290
290
  * `SCHEDULER_VERDICT:` line to say PASS. Each line is classified by
291
291
  * runVerify.cjs's scanSentinel (the one SCHEDULER_VERDICT parser), scanned
292
- * from the end so the final say wins.
292
+ * from the end so the final say wins. A `--json-schema` run's
293
+ * structured_output.schedulerVerdict (same scanSentinel) is checked first.
293
294
  */
294
- function lastVerdictLine(resultText) {
295
- if (typeof resultText !== 'string' || !resultText) return null;
295
+ function lastVerdictLine(resultText, structuredOutput) {
296
296
  // Lazy require: runVerify.cjs is a larger module; keep this lib cheap to load.
297
297
  const { scanSentinel } = require('../../runVerify.cjs');
298
+ const so = structuredOf(resultText, structuredOutput);
299
+ if (so) {
300
+ const v = scanSentinel({ resultText: '', structuredOutput: so }, []);
301
+ if (v) return v;
302
+ }
303
+ if (typeof resultText !== 'string' || !resultText) return null;
298
304
  const lines = resultText.split('\n');
299
305
  for (let i = lines.length - 1; i >= 0; i--) {
300
306
  const v = scanSentinel({ resultText: lines[i].replace(/\r$/, '') }, []);
@@ -303,11 +309,35 @@ function lastVerdictLine(resultText) {
303
309
  return null;
304
310
  }
305
311
 
306
- function resolveReapGateOutcome(outcome, resultText) {
312
+ /**
313
+ * The run's `--json-schema` structured output: the explicit object when the
314
+ * caller has it, else the result text parsed as a JSON object (under
315
+ * `--json-schema` the CLI's `result` is the structured output's string form).
316
+ * null for text-only runs.
317
+ */
318
+ function structuredOf(resultText, structuredOutput) {
319
+ if (structuredOutput && typeof structuredOutput === 'object' && !Array.isArray(structuredOutput)) return structuredOutput;
320
+ if (typeof resultText !== 'string') return null;
321
+ const t = resultText.trim();
322
+ if (!t.startsWith('{')) return null;
323
+ try {
324
+ const obj = JSON.parse(t);
325
+ return obj && typeof obj === 'object' && !Array.isArray(obj) ? obj : null;
326
+ } catch {
327
+ return null;
328
+ }
329
+ }
330
+
331
+ /**
332
+ * @param {string} outcome classifyRunOutcome() result
333
+ * @param {string|null} resultText the last result event's `result` string
334
+ * @param {object|null} [structuredOutput] the last result event's `structured_output`
335
+ */
336
+ function resolveReapGateOutcome(outcome, resultText, structuredOutput) {
307
337
  if (outcome === 'failed') return 'failed';
308
338
  if (outcome === 'no_result') return 'never_ran';
309
339
  if (outcome !== 'success') return 'unknown';
310
- const verdict = lastVerdictLine(resultText);
340
+ const verdict = lastVerdictLine(resultText, structuredOutput);
311
341
  if (verdict === 'pass') return 'passed';
312
342
  if (verdict === 'fail') return 'failed';
313
343
  return 'unknown';
@@ -306,10 +306,49 @@ function holdMsFromEnv(env = process.env) {
306
306
  return minutes * 60000;
307
307
  }
308
308
 
309
+ /**
310
+ * buildPreflightHoldNotice({ slug, failText, preflight, heldSlugs, nextAt })
311
+ * → plain-text body for the ONE informational notice an Epic gets the moment
312
+ * a PRD is held on a failing preflight. It states what is missing (failText,
313
+ * quoted verbatim), the preflight command, which PRDs it holds, when the next
314
+ * re-check runs, and that the hold clears on its own. Pure, no I/O. It never
315
+ * asks a question and never carries SM_NEEDS_INPUT — nothing waits on a reply.
316
+ * (failText is quoted as-is; the builder's own wording has no '?'.)
317
+ */
318
+ function buildPreflightHoldNotice({ slug, failText, preflight, heldSlugs, nextAt } = {}) {
319
+ const name = (typeof slug === 'string' && slug.trim()) || 'this PRD';
320
+ const cmd = oneLine(preflight);
321
+ const cmdLabel = cmd ? `\`${cmd}\`` : 'the preflight';
322
+ const missing = typeof failText === 'string' && failText.trim()
323
+ ? `Missing: "${failText}"`
324
+ : `Missing: the preflight exited non-zero with no output.`;
325
+ const held = Array.isArray(heldSlugs) ? heldSlugs.filter((x) => typeof x === 'string' && x) : [];
326
+ const heldList = held.length ? held : [name];
327
+ const when = typeof nextAt === 'string' && nextAt ? nextAt : 'the next scheduler pass';
328
+ return [
329
+ `PRECONDITION HOLD: ${name} is waiting on its preflight.`,
330
+ missing,
331
+ `Preflight: ${cmdLabel}`,
332
+ `Held: ${heldList.join(', ')}`,
333
+ `Next re-check: ${when}.`,
334
+ `The scheduler re-checks on its own and resumes the chain when ${cmdLabel} exits 0. Reset on ${name} re-checks at once.`,
335
+ ].join('\n');
336
+ }
337
+
338
+ /**
339
+ * preflightHoldNoticeKey(slug, since) → dedup key for one preflight hold.
340
+ * Same slug + same hold start = same key, so each hold sends one notice.
341
+ */
342
+ function preflightHoldNoticeKey(slug, since) {
343
+ return `preflight-hold\u0000${slug ?? ''}\u0000${since ?? ''}`;
344
+ }
345
+
309
346
  module.exports = {
310
347
  DEFAULT_HOLD_MINUTES,
311
348
  buildReviewNotice,
312
349
  selectDueReviewNotices,
313
350
  formatReviewNotice,
314
351
  holdMsFromEnv,
352
+ buildPreflightHoldNotice,
353
+ preflightHoldNoticeKey,
315
354
  };