claude-code-session-manager 0.140.0 → 0.142.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 (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -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 };
@@ -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
  };
@@ -542,7 +542,9 @@ function runBootSweep(opts) {
542
542
  const result = applyRetention(runsDir, state.config || {}, { jobs: state.jobs || [] });
543
543
  // Same pass, same project list: the cwds readMergedSync just swept (state.sourceCwds,
544
544
  // from queueStore's cached stateCwds) — never a fresh allProjectCwds() scan.
545
- result.planRecords = runPlanRecordSweep({ cwds: Array.isArray(state.sourceCwds) ? state.sourceCwds : [] });
545
+ const cwds = Array.isArray(state.sourceCwds) ? state.sourceCwds : [];
546
+ result.planRecords = runPlanRecordSweep({ cwds });
547
+ result.artifacts = runArtifactSweep({ cwds });
546
548
  return result;
547
549
  }
548
550
 
@@ -641,6 +643,44 @@ function runPlanRecordSweep(opts) {
641
643
  return out;
642
644
  }
643
645
 
646
+ /**
647
+ * Prune artifacts/<epic-id>/ + artifacts/_tasks/ in every given project root with
648
+ * artifactsDays + tasksDays from opsRetentionSettings (lib/epic/artifactRetention.cjs).
649
+ * Same per-project epicStatus as the plan-records sweep. Then, once per pass, prune the
650
+ * machine-wide staging base <worktreeBase>/artifact-staging (pruneArtifactStaging, with
651
+ * artifactsDays); its result is logged, not returned. Never throws.
652
+ * deps: { prune, pruneStaging, readSettings, epicStatusFor, now } for tests.
653
+ */
654
+ function runArtifactSweep(opts) {
655
+ const o = opts || {};
656
+ const out = { projects: 0, removed: 0, errors: 0 };
657
+ let s = {};
658
+ try { s = (o.readSettings || require('../opsRetentionSettings.cjs').read)() || {}; } catch { /* module defaults */ }
659
+ const prune = o.prune || require('../epic/artifactRetention.cjs').pruneArtifacts;
660
+ const statusFor = o.epicStatusFor || epicStatusFor;
661
+ const seen = new Set();
662
+ for (const cwd of o.cwds || []) {
663
+ if (typeof cwd !== 'string' || !cwd || seen.has(cwd)) continue;
664
+ seen.add(cwd);
665
+ try {
666
+ const r = prune({ projectRoot: cwd, epicStatus: statusFor(cwd), days: s.artifactsDays, tasksDays: s.tasksDays, now: o.now });
667
+ out.projects += 1;
668
+ out.removed += (r && Array.isArray(r.removed)) ? r.removed.length : 0;
669
+ } catch (e) {
670
+ out.errors += 1;
671
+ console.warn(`[runLogRetention] artifacts sweep skipped ${cwd}:`, e && e.message);
672
+ }
673
+ }
674
+ try {
675
+ const pruneStaging = o.pruneStaging || require('../epic/artifactRetention.cjs').pruneArtifactStaging;
676
+ pruneStaging({ now: o.now, days: s.artifactsDays }); // logs what it deletes
677
+ } catch (e) {
678
+ out.errors += 1;
679
+ console.warn('[runLogRetention] artifact staging sweep skipped:', e && e.message);
680
+ }
681
+ return out;
682
+ }
683
+
644
684
  module.exports = {
645
685
  DEFAULT_RUN_LOG_RETENTION,
646
686
  resolveRetentionConfig,
@@ -656,5 +696,6 @@ module.exports = {
656
696
  applyRetention,
657
697
  runBootSweep,
658
698
  runPlanRecordSweep,
699
+ runArtifactSweep,
659
700
  epicStatusFor,
660
701
  };
@@ -100,6 +100,8 @@ const ScheduleJobSchema = z
100
100
  artifactPaths: z.array(z.string()).nullable().optional(),
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
+ // PRD frontmatter `voiceId` — a per-run library voice; executeJob sets SM_VOICE_ID from it.
104
+ voiceId: z.string().nullable().optional(),
103
105
  statusHistory: z.array(ScheduleJobStatusHistoryEntrySchema).optional(),
104
106
  // PRD frontmatter `fixes` — the earlier PRDs this one repairs, copied onto
105
107
  // the row at discovery by reconcile() (validationQuality.cjs reads it).
@@ -147,6 +149,9 @@ const ScheduleJobSchema = z
147
149
  // at entry, deleted at resolution).
148
150
  needsReviewEntryRunId: z.string().nullable().optional(),
149
151
  needsReviewEnteredAt: z.string().nullable().optional(),
152
+ // Content id of the AgentSnapshot (agentSnapshot.cjs) the job's first
153
+ // dispatch pinned; every later dispatch (resume) re-runs that snapshot.
154
+ agentSnapshotId: z.string().optional(),
150
155
  })
151
156
  .passthrough();
152
157
 
@@ -34,6 +34,10 @@ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
34
34
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
35
35
  const queueHistory = require('./queueHistory.cjs');
36
36
  const { buildNeedsReviewEntryLine, buildNeedsReviewResolutionLine } = require('./needsReviewLedger.cjs');
37
+ // Module objects (not destructured) so the per-Epic event emit below can be
38
+ // stubbed in tests and so a load-order cycle can never capture a stale ref.
39
+ const epicEventLog = require('../epic/epicEventLog.cjs');
40
+ const opsErrorLog = require('../telemetry/opsErrorLog.cjs');
37
41
 
38
42
  // A run genuinely finished when it leaves 'running' for one of these —
39
43
  // distinct from every other legal edge in LEGAL_TRANSITIONS (retries,
@@ -126,6 +130,39 @@ const LEGAL_TRANSITIONS = {
126
130
 
127
131
  let refusedTransitionCount = 0;
128
132
 
133
+ /**
134
+ * emitJobEvent(job, event) → void. Appends one summary-only event to the
135
+ * job's Epic event log (lib/epic/epicEventLog.cjs) when the job carries both
136
+ * an epicId and a cwd; a job without either appends nothing. Fire-and-forget:
137
+ * a sync throw or async rejection is logged via opsErrorLog and never
138
+ * propagates — an event-log failure must never block a transition or a
139
+ * queue insert.
140
+ */
141
+ function emitJobEvent(job, event) {
142
+ if (!job || typeof job !== 'object') return;
143
+ const epicId = job.epicId;
144
+ const cwd = job.cwd;
145
+ if (typeof epicId !== 'string' || !epicId || typeof cwd !== 'string' || !cwd) return;
146
+ const onError = (err) => {
147
+ try {
148
+ opsErrorLog.appendError({
149
+ cwd,
150
+ scope: 'scheduler',
151
+ level: 'error',
152
+ epicId,
153
+ message: `epic event append failed (${event?.kind ?? 'unknown'}) for ${job.slug ?? '(unknown)'}: ${err?.message ?? String(err)}`,
154
+ meta: { slug: job.slug ?? null, kind: event?.kind ?? null },
155
+ });
156
+ } catch { /* logging must never be the thing that fails */ }
157
+ };
158
+ try {
159
+ const p = epicEventLog.appendEpicEvent(cwd, epicId, event);
160
+ if (p && typeof p.catch === 'function') p.catch(onError);
161
+ } catch (err) {
162
+ onError(err);
163
+ }
164
+ }
165
+
129
166
  function isLegalTransition(from, to) {
130
167
  if (from === to) return true;
131
168
  const edges = LEGAL_TRANSITIONS[from];
@@ -194,6 +231,15 @@ function transitionJob(job, toStatus, { reason, source, allowAnyFrom = false } =
194
231
  cwd: job.cwd ?? null,
195
232
  });
196
233
 
234
+ emitJobEvent(job, {
235
+ kind: 'job.status_changed',
236
+ slug: job.slug ?? null,
237
+ from: from ?? null,
238
+ to: toStatus,
239
+ reason: reason ?? null,
240
+ source: source ?? null,
241
+ });
242
+
197
243
  if (from === 'running' && FINISH_STATUSES.has(toStatus)) {
198
244
  telemetryCounters.trackSchedulerJobFinish({ status: toStatus });
199
245
  }
@@ -270,6 +316,7 @@ function _resetRefusedTransitionCountForTests() {
270
316
 
271
317
  module.exports = {
272
318
  transitionJob,
319
+ emitJobEvent,
273
320
  LEGAL_TRANSITIONS,
274
321
  STATUS_HISTORY_CAP,
275
322
  getRefusedTransitionCount,
@@ -181,8 +181,55 @@ module.exports = {
181
181
  // SM_QUIET_MACHINE_WAIT_MINUTES (integer minutes, clamped to [1, 1440]).
182
182
  DEFAULT_QUIET_MACHINE_WAIT_MS: 30 * 60_000,
183
183
  quietMachineWaitMs,
184
+
185
+ // Environment enforcement (jobSandboxPolicy.cjs + guard-tool-risk): what a
186
+ // job's environment profile would block — OS sandbox required but
187
+ // unavailable, WebFetch/WebSearch not allowed, host off the allow-list.
188
+ // 'report' (the default for a machine's first week, PRD 3942): appends an
189
+ // 'environment_would_block' audit record and blocks nothing. The week runs
190
+ // from environmentReportSince, persisted once in scheduler runtime state
191
+ // (schedulerRuntimeState.ensureEnvironmentReportSince) the first time this
192
+ // is evaluated; ENVIRONMENT_REPORT_WINDOW_MS later the machine switches to
193
+ // 'enforce' by itself: a job whose environment needs the OS sandbox and
194
+ // cannot get it parks needs_review 'environment_unavailable: <missing
195
+ // deps>', and the hook denies WebFetch/WebSearch the environment
196
+ // disallows. The readiness banner names the switch date and any missing
197
+ // packages. SM_ENVIRONMENT_ENFORCEMENT=report|enforce overrides both ways
198
+ // ('report' always wins); anything else follows the persisted week.
199
+ DEFAULT_ENVIRONMENT_ENFORCEMENT: 'report',
200
+ ENVIRONMENT_REPORT_WINDOW_MS: 7 * 24 * 60 * 60_000,
201
+ environmentEnforcement,
202
+ environmentEnforcementStatus,
184
203
  };
185
204
 
205
+ /**
206
+ * @param {{ now?: number, statePath?: string }} [opts]
207
+ * @returns {{ mode: 'report'|'enforce', source: 'env'|'report-week'|'unpersisted', reportSince: number|null, enforceFrom: number|null }}
208
+ */
209
+ function environmentEnforcementStatus({ now = Date.now(), statePath } = {}) {
210
+ const raw = String(process.env.SM_ENVIRONMENT_ENFORCEMENT || '').trim().toLowerCase();
211
+ if (raw === 'report') return { mode: 'report', source: 'env', reportSince: null, enforceFrom: null };
212
+ if (raw === 'enforce') return { mode: 'enforce', source: 'env', reportSince: null, enforceFrom: null };
213
+ let since;
214
+ try {
215
+ since = require('./schedulerRuntimeState.cjs').ensureEnvironmentReportSince({ now, ...(statePath ? { statePath } : {}) });
216
+ } catch {
217
+ // Cannot persist the start of the week: stay in the safe default rather
218
+ // than park every sandbox-required job.
219
+ return { mode: module.exports.DEFAULT_ENVIRONMENT_ENFORCEMENT, source: 'unpersisted', reportSince: null, enforceFrom: null };
220
+ }
221
+ const enforceFrom = since + module.exports.ENVIRONMENT_REPORT_WINDOW_MS;
222
+ return { mode: now >= enforceFrom ? 'enforce' : 'report', source: 'report-week', reportSince: since, enforceFrom };
223
+ }
224
+
225
+ /**
226
+ * @param {{ now?: number, statePath?: string }} [opts]
227
+ * @returns {'report'|'enforce'}
228
+ */
229
+ function environmentEnforcement(opts) {
230
+ return environmentEnforcementStatus(opts).mode;
231
+ }
232
+
186
233
  function quietMachineWaitMs() {
187
234
  const raw = process.env.SM_QUIET_MACHINE_WAIT_MINUTES;
188
235
  if (raw === undefined || raw === '') return module.exports.DEFAULT_QUIET_MACHINE_WAIT_MS;
@@ -113,8 +113,6 @@ function taskSwitchesPath() { return assertNotLiveRoot(path.join(schedulerHome()
113
113
  function externalRefIndexPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'external-refs.json'), 'externalRefIndexPath'); }
114
114
  /** Machine-level "Needs you" items posted by outside apps (feedback-remote/needsYouStore.cjs). */
115
115
  function needsYouPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'needs-you.json'), 'needsYouPath'); }
116
- /** Last-seen outside-facing state of every open Epic (epic/epicStateWatcher.cjs). */
117
- function epicStateSnapshotPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'epic-state-snapshot.json'), 'epicStateSnapshotPath'); }
118
116
  function watchdogLogsDir() { return assertNotLiveRoot(path.join(schedulerHome(), 'logs'), 'watchdogLogsDir'); }
119
117
  function restartRequestPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restart-request.json'), 'restartRequestPath'); }
120
118
  function restartingMarkerPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restarting.json'), 'restartingMarkerPath'); }
@@ -209,7 +207,6 @@ module.exports = {
209
207
  taskSwitchesPath,
210
208
  externalRefIndexPath,
211
209
  needsYouPath,
212
- epicStateSnapshotPath,
213
210
  adminTokenPath,
214
211
  machineStateLogCwd,
215
212
  worktreeBase,
@@ -7,11 +7,58 @@
7
7
  */
8
8
  'use strict';
9
9
 
10
+ const fs = require('node:fs');
11
+ const path = require('node:path');
12
+ const { readJsonOrSync, writeJsonAtomicSync } = require('../util/atomicFs.cjs');
10
13
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
11
14
  const { isProvablyDead, DEFAULT_GRACE_MS } = require('./reservationExpiry.cjs');
12
15
 
13
16
  const investigations = new Map(); // slug -> { claimedAt, pid }
14
17
 
18
+ /*
19
+ * Persisted machine runtime state (survives restarts), unlike the
20
+ * process-local reservations above: <schedulerHome>/scheduler-runtime-state.json.
21
+ * Today it holds one key, `environmentReportSince` — epoch ms of the first
22
+ * time environment enforcement was evaluated on this machine. The report-only
23
+ * week (schedulerConfig.environmentEnforcement) is measured from it. Written
24
+ * once, atomically, and never reset: a restart re-reads the same value.
25
+ */
26
+ const RUNTIME_STATE_FILE = 'scheduler-runtime-state.json';
27
+
28
+ function runtimeStatePath() {
29
+ const { schedulerHome } = require('./schedulerPaths.cjs');
30
+ return path.join(schedulerHome(), RUNTIME_STATE_FILE);
31
+ }
32
+
33
+ /** @type {Map<string, number>} statePath -> environmentReportSince (memo; the value never changes once written) */
34
+ const reportSinceMemo = new Map();
35
+
36
+ function validStamp(v) {
37
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null;
38
+ }
39
+
40
+ /**
41
+ * The persisted environmentReportSince (epoch ms), writing `now` first if no
42
+ * valid value is on disk yet. Never overwrites an existing value. Throws only
43
+ * if the state file cannot be written.
44
+ * @param {{ now?: number, statePath?: string }} [opts]
45
+ * @returns {number}
46
+ */
47
+ function ensureEnvironmentReportSince({ now = Date.now(), statePath = runtimeStatePath() } = {}) {
48
+ const memo = reportSinceMemo.get(statePath);
49
+ if (memo) return memo;
50
+ const state = readJsonOrSync(statePath, null);
51
+ const obj = state && typeof state === 'object' && !Array.isArray(state) ? state : {};
52
+ let since = validStamp(obj.environmentReportSince);
53
+ if (!since) {
54
+ since = now;
55
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
56
+ writeJsonAtomicSync(statePath, { ...obj, environmentReportSince: since });
57
+ }
58
+ reportSinceMemo.set(statePath, since);
59
+ return since;
60
+ }
61
+
15
62
  function investigationCount() { return investigations.size; }
16
63
 
17
64
  /** reserveInvestigation(slug) — false if already reserved. Cap checks stay with the caller. */
@@ -47,7 +94,7 @@ function expireDeadInvestigations({ liveSlugs, pidAlive, now = Date.now(), grace
47
94
  return expired;
48
95
  }
49
96
 
50
- function __resetForTests() { investigations.clear(); }
97
+ function __resetForTests() { investigations.clear(); reportSinceMemo.clear(); }
51
98
 
52
99
  module.exports = {
53
100
  investigationCount,
@@ -55,5 +102,7 @@ module.exports = {
55
102
  stampInvestigationPid,
56
103
  releaseInvestigation,
57
104
  expireDeadInvestigations,
105
+ runtimeStatePath,
106
+ ensureEnvironmentReportSince,
58
107
  __resetForTests,
59
108
  };
@@ -167,8 +167,12 @@ function notify() {
167
167
  }
168
168
  }
169
169
 
170
- /** Turn the held interactive slot on/off (default off). Grants any waiter it unblocks. */
170
+ /**
171
+ * Turn the held interactive slot on/off (default off). Grants any waiter it unblocks.
172
+ * An unchanged value is a no-op (no grants, no listener calls), so callers may re-sync per request.
173
+ */
171
174
  function setInteractiveReserve(on) {
175
+ if (!!on === reserveOn) return reserveOn;
172
176
  reserveOn = !!on;
173
177
  notify();
174
178
  return reserveOn;