claude-code-session-manager 0.139.0 → 0.140.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 (150) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  3. package/dist/assets/History--JwsFnbn.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-ijEXs--3.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-CALyU0pe.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-sdlA-fUb.js} +1 -1
  7. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-DtRzghn5.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-DApeu7x8.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-B7qLXRAH.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-DtStfv1H.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-ydfnwepc.js} +1 -1
  14. package/dist/assets/index-CtxruO1L.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/develop/SKILL.md +26 -19
  23. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  32. package/scripts/README.md +1 -0
  33. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  34. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  35. package/scripts/ops-sweep.cjs +53 -23
  36. package/scripts/scheduler-mcp-server.cjs +200 -18
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/config.cjs +112 -8
  39. package/src/main/docEdit.cjs +6 -1
  40. package/src/main/files.cjs +7 -27
  41. package/src/main/health.cjs +48 -15
  42. package/src/main/historyAggregator.cjs +88 -5
  43. package/src/main/historyDashboard.cjs +69 -4
  44. package/src/main/index.cjs +56 -2
  45. package/src/main/ipcSchemas.cjs +112 -16
  46. package/src/main/lib/AGENTS.md +54 -0
  47. package/src/main/lib/CLAUDE.md +1 -54
  48. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  49. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  50. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  51. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  52. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  53. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  54. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  55. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  56. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  57. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  58. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  59. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  60. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  61. package/src/main/lib/ephemeralCwd.cjs +37 -2
  62. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  63. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  64. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  65. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  66. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  67. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  68. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  69. package/src/main/lib/externalContract.cjs +31 -5
  70. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  71. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  72. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  73. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  75. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  76. package/src/main/lib/git/branchSweep.cjs +209 -4
  77. package/src/main/lib/git/gitWorktree.cjs +41 -5
  78. package/src/main/lib/guardShims.cjs +1 -1
  79. package/src/main/lib/historyRollup.cjs +26 -0
  80. package/src/main/lib/insideHome.cjs +27 -1
  81. package/src/main/lib/mcpToolCatalog.cjs +122 -12
  82. package/src/main/lib/mdDocCensus.cjs +59 -78
  83. package/src/main/lib/mdDocRefs.cjs +71 -93
  84. package/src/main/lib/mdNetworkScan.cjs +245 -250
  85. package/src/main/lib/mdReviewRecord.cjs +22 -9
  86. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  87. package/src/main/lib/opsOwnership.cjs +18 -2
  88. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  89. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  90. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  91. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  92. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  93. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  96. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  97. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  98. package/src/main/lib/prd/prdCreate.cjs +351 -23
  99. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  100. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  101. package/src/main/lib/process/loginItem.cjs +171 -0
  102. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  103. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  104. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  105. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  106. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  107. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  108. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  109. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  110. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  111. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  112. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  113. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  114. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  115. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  116. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  117. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  118. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  119. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  120. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  121. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  122. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  123. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  124. package/src/main/lib/tasks/taskRun.cjs +313 -0
  125. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  126. package/src/main/loginItemIpc.cjs +35 -0
  127. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  128. package/src/main/projectPages.cjs +6 -15
  129. package/src/main/promptSessionEvents.cjs +9 -1
  130. package/src/main/queueOps.cjs +260 -3
  131. package/src/main/runVerify.cjs +53 -25
  132. package/src/main/scheduler/AGENTS.md +26 -0
  133. package/src/main/scheduler/CLAUDE.md +1 -26
  134. package/src/main/scheduler/budget.cjs +239 -9
  135. package/src/main/scheduler/cancelDependents.cjs +154 -0
  136. package/src/main/scheduler/prdParser.cjs +4 -1
  137. package/src/main/scheduler/starvation.cjs +20 -18
  138. package/src/main/scheduler.cjs +745 -64
  139. package/src/main/supervisor.cjs +5 -1
  140. package/src/main/templates/PRD_AUTHORING.md +6 -1
  141. package/src/main/validationQualityHandlers.cjs +199 -0
  142. package/src/main/webRemote.cjs +10 -2
  143. package/src/preload/api.d.ts +364 -21
  144. package/src/preload/apiSurface.json +89 -10
  145. package/src/preload/index.cjs +23 -2
  146. package/src/seed/agents/validator.md +19 -8
  147. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  148. package/dist/assets/History-DDnqaLyw.js +0 -2
  149. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  150. 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 };
@@ -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';
@@ -532,14 +532,113 @@ function applyRetention(runsDir, settings, opts) {
532
532
  * happens unless the read config opts out with
533
533
  * schedulerRunLogRetention.enabled === false (see isRetentionEnabled).
534
534
  *
535
- * Intended to be called once per app boot (see index.cjs's deferred 30s
536
- * startup timer, alongside finalizeClosedDays) — never on its own timer.
535
+ * Called by index.cjs's runRunLogRetentionPass: once on the deferred boot
536
+ * pass, then every 24h from that pass's setInterval timer.
537
537
  */
538
538
  function runBootSweep(opts) {
539
539
  const runsDir = (opts && opts.runsDir) || schedulerPaths.runsDir();
540
540
  const queueStore = require('./queueStore.cjs');
541
541
  const state = queueStore.readMergedSync();
542
- return applyRetention(runsDir, state.config || {}, { jobs: state.jobs || [] });
542
+ const result = applyRetention(runsDir, state.config || {}, { jobs: state.jobs || [] });
543
+ // Same pass, same project list: the cwds readMergedSync just swept (state.sourceCwds,
544
+ // from queueStore's cached stateCwds) — never a fresh allProjectCwds() scan.
545
+ result.planRecords = runPlanRecordSweep({ cwds: Array.isArray(state.sourceCwds) ? state.sourceCwds : [] });
546
+ return result;
547
+ }
548
+
549
+ const INDEX_UNREADABLE = Symbol('active-index-unreadable');
550
+
551
+ /**
552
+ * readIndexSessions(projectRoot) → the active-index.json `sessions` map, {} when the
553
+ * file is absent, or INDEX_UNREADABLE when it exists but cannot be read/parsed into an
554
+ * object carrying an object `sessions` field. Deliberately NOT epicMint.readActiveIndex:
555
+ * that reader folds every error into an empty index, which would make every live Epic
556
+ * look like an orphan to the plan-records sweep.
557
+ */
558
+ function readIndexSessions(projectRoot) {
559
+ const { opsPath } = require('../opsOwnership.cjs');
560
+ const { readJsonOrSync } = require('../util/atomicFs.cjs');
561
+ const file = opsPath(projectRoot, 'prompt-sessions', 'active-index.json');
562
+ if (!fs.existsSync(file)) return {};
563
+ const parsed = readJsonOrSync(file, INDEX_UNREADABLE);
564
+ if (parsed === INDEX_UNREADABLE || !parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
565
+ return INDEX_UNREADABLE;
566
+ }
567
+ const sessions = parsed.sessions;
568
+ if (!sessions || typeof sessions !== 'object' || Array.isArray(sessions)) return INDEX_UNREADABLE;
569
+ return sessions;
570
+ }
571
+
572
+ /**
573
+ * epicStatusFor(projectRoot, deps) → epicStatus(id) for prunePlanRecords. Reads the
574
+ * active-index.json row (read once per call) first, else the per-Epic
575
+ * prompt-sessions/<id>.json archive/mirror (planRecordRetention.defaultEpicStatus).
576
+ * Returns null for an unknown Epic (orphan).
577
+ *
578
+ * FAILS CLOSED: when active-index.json exists but is unreadable/corrupt, the returned
579
+ * function throws for every id, so prunePlanRecords keeps every folder in that project.
580
+ * A missing index means no rows: ids fall through to the archive, unknown ids are orphans.
581
+ * deps: { readActiveIndex, defaultEpicStatus } for tests (readActiveIndex replaces the
582
+ * canonical read; its result is trusted as-is).
583
+ */
584
+ function epicStatusFor(projectRoot, deps) {
585
+ const d = deps || {};
586
+ const archiveStatus = (d.defaultEpicStatus || require('./planRecordRetention.cjs').defaultEpicStatus)(projectRoot);
587
+ let sessions;
588
+ if (d.readActiveIndex) {
589
+ const idx = d.readActiveIndex(projectRoot);
590
+ sessions = idx && idx.sessions && typeof idx.sessions === 'object' ? idx.sessions : {};
591
+ } else {
592
+ let read;
593
+ try { read = readIndexSessions(projectRoot); } catch { read = INDEX_UNREADABLE; }
594
+ if (read === INDEX_UNREADABLE) {
595
+ return () => { throw new Error('active-index unreadable'); };
596
+ }
597
+ sessions = read;
598
+ }
599
+ return (id) => {
600
+ try {
601
+ const row = Object.prototype.hasOwnProperty.call(sessions, id) ? sessions[id] : null;
602
+ if (row && typeof row === 'object' && typeof row.status === 'string') {
603
+ return { status: row.status, completedAt: row.completedAt ?? null };
604
+ }
605
+ return archiveStatus(id);
606
+ } catch {
607
+ return null;
608
+ }
609
+ };
610
+ }
611
+
612
+ /**
613
+ * Prune plan-records/<epic-id>/ in every given project root with planRecordsDays from
614
+ * opsRetentionSettings. Per-project failures are logged and skipped — never throws.
615
+ * deps: { prune, readSettings, epicStatusFor, now } for tests.
616
+ */
617
+ function runPlanRecordSweep(opts) {
618
+ const o = opts || {};
619
+ const out = { projects: 0, removed: 0, errors: 0 };
620
+ let days;
621
+ try {
622
+ days = (o.readSettings || require('../opsRetentionSettings.cjs').read)().planRecordsDays;
623
+ } catch {
624
+ days = undefined; // prunePlanRecords falls back to its own default
625
+ }
626
+ const prune = o.prune || require('./planRecordRetention.cjs').prunePlanRecords;
627
+ const statusFor = o.epicStatusFor || epicStatusFor;
628
+ const seen = new Set();
629
+ for (const cwd of o.cwds || []) {
630
+ if (typeof cwd !== 'string' || !cwd || seen.has(cwd)) continue;
631
+ seen.add(cwd);
632
+ try {
633
+ const r = prune({ projectRoot: cwd, epicStatus: statusFor(cwd), days, now: o.now });
634
+ out.projects += 1;
635
+ out.removed += (r && Array.isArray(r.removed)) ? r.removed.length : 0;
636
+ } catch (e) {
637
+ out.errors += 1;
638
+ console.warn(`[runLogRetention] plan-records sweep skipped ${cwd}:`, e && e.message);
639
+ }
640
+ }
641
+ return out;
543
642
  }
544
643
 
545
644
  module.exports = {
@@ -556,4 +655,6 @@ module.exports = {
556
655
  isRetentionEnabled,
557
656
  applyRetention,
558
657
  runBootSweep,
658
+ runPlanRecordSweep,
659
+ epicStatusFor,
559
660
  };
@@ -101,6 +101,9 @@ const ScheduleJobSchema = z
101
101
  // PRD frontmatter `effort` — a per-run level from a macro press (outranks the persona's).
102
102
  effort: z.string().nullable().optional(),
103
103
  statusHistory: z.array(ScheduleJobStatusHistoryEntrySchema).optional(),
104
+ // PRD frontmatter `fixes` — the earlier PRDs this one repairs, copied onto
105
+ // the row at discovery by reconcile() (validationQuality.cjs reads it).
106
+ fixes: z.array(z.object({ prd: z.string(), missKind: z.string(), reason: z.string() }).passthrough()).optional(),
104
107
  // Opt-in exclusive-lease PRD flag (PRD 1107) — serializes this job against
105
108
  // every other job machine-wide for its run so a timing-sensitive gate
106
109
  // (frame time, performance fence) measures without CPU contention. See