claude-code-session-manager 0.141.0 → 0.143.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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,191 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * prdOutcomeRecord.cjs — one structured outcome record per finished PRD run
5
+ * (Managed Agents' "outcome", kept local).
6
+ *
7
+ * Layout: session-manager-operations/scheduler/epics/<epicId>/outcomes/<slug>.json
8
+ * { schemaVersion, slug, epicId, recordedAt, verdict, commits, files, gates, checks, ...extra }
9
+ * Written atomically (util/atomicFs) as the 'scheduler' namespace owner; the
10
+ * latest terminal run of a slug overwrites the previous record. After the
11
+ * write, one `outcome.recorded` { slug, verdict } event is appended to the
12
+ * Epic's event log (lib/epic/epicEventLog.cjs). An event-append failure is
13
+ * logged, never thrown — the record on disk is the source of truth.
14
+ *
15
+ * `verdict` is the job's terminal status (completed / failed / needs_review);
16
+ * the verifier's own verdict string travels inside `gates`.
17
+ */
18
+
19
+ const path = require('node:path');
20
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
21
+ const { writeJsonAtomic, writeTextAtomic, readJsonOr } = require('../util/atomicFs.cjs');
22
+
23
+ const WRITER = 'scheduler';
24
+ const SCHEMA_VERSION = 1;
25
+ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
26
+ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;
27
+ const MAX_FILES = 500;
28
+ const MAX_COMMITS = 100;
29
+
30
+ function assertIds(epicId, slug) {
31
+ if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) throw new Error(`prdOutcomeRecord: invalid epicId "${epicId}"`);
32
+ if (typeof slug !== 'string' || !SLUG_RE.test(slug) || slug.includes('..')) throw new Error(`prdOutcomeRecord: invalid slug "${slug}"`);
33
+ }
34
+
35
+ /** Absolute path of a slug's outcome record. Throws on an unsafe epicId/slug. */
36
+ function outcomeRecordPath(cwd, epicId, slug) {
37
+ assertIds(epicId, slug);
38
+ return opsPath(cwd, 'scheduler', 'epics', epicId, 'outcomes', `${slug}.json`);
39
+ }
40
+
41
+ function strList(v, cap) {
42
+ return (Array.isArray(v) ? v : []).filter((x) => typeof x === 'string' && x).slice(0, cap);
43
+ }
44
+ function objList(v) {
45
+ return (Array.isArray(v) ? v : []).filter((x) => x && typeof x === 'object');
46
+ }
47
+
48
+ /**
49
+ * writeOutcomeRecord({ cwd, epicId, slug, commits, files, gates, checks, verdict, extra?, write?, appendEvent? })
50
+ * → Promise<string> (the written path). Rejects on a bad id or write failure.
51
+ */
52
+ async function writeOutcomeRecord({
53
+ cwd, epicId, slug, commits, files, gates, checks, verdict, extra = null,
54
+ write = writeJsonAtomic, appendEvent = null,
55
+ } = {}) {
56
+ const file = outcomeRecordPath(cwd, epicId, slug);
57
+ assertOpsWrite(file, WRITER);
58
+ const record = {
59
+ ...(extra && typeof extra === 'object' ? extra : {}),
60
+ schemaVersion: SCHEMA_VERSION,
61
+ slug,
62
+ epicId,
63
+ recordedAt: new Date().toISOString(),
64
+ verdict: verdict == null ? null : String(verdict),
65
+ commits: strList(commits, MAX_COMMITS),
66
+ files: strList(files, MAX_FILES),
67
+ gates: objList(gates),
68
+ checks: objList(checks),
69
+ };
70
+ await write(file, record);
71
+ try {
72
+ const append = appendEvent || require('../epic/epicEventLog.cjs').appendEpicEvent;
73
+ await append(cwd, epicId, { kind: 'outcome.recorded', slug, verdict: record.verdict });
74
+ } catch (e) {
75
+ console.error('[prdOutcomeRecord] outcome.recorded event append failed', epicId, slug, e && e.message ? e.message : e);
76
+ }
77
+ return file;
78
+ }
79
+
80
+ /**
81
+ * mergeOutcomeChecks({ cwd, epicId, slug, checks, write? }) → Promise<boolean>
82
+ * (true when a record was rewritten). Replaces the existing record's `checks`
83
+ * entries by id with the fresh ones (each stamped ranAt + stage
84
+ * 'validator-dispatch' unless already stamped), keeps every other entry, and
85
+ * writes atomically as 'scheduler'. No record on disk → no write. Never throws.
86
+ */
87
+ async function mergeOutcomeChecks({ cwd, epicId, slug, checks, write = writeJsonAtomic } = {}) {
88
+ try {
89
+ const file = outcomeRecordPath(cwd, epicId, slug);
90
+ const record = await readJsonOr(file, null);
91
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return false;
92
+ const ranAt = new Date().toISOString();
93
+ const fresh = objList(checks)
94
+ .filter((c) => typeof c.id === 'string' && c.id)
95
+ .map((c) => ({ ...c, ranAt: c.ranAt || ranAt, stage: c.stage || 'validator-dispatch' }));
96
+ const freshById = new Map(fresh.map((c) => [c.id, c]));
97
+ const merged = [];
98
+ const seen = new Set();
99
+ for (const c of objList(record.checks)) {
100
+ if (typeof c.id === 'string' && freshById.has(c.id)) {
101
+ if (!seen.has(c.id)) { merged.push(freshById.get(c.id)); seen.add(c.id); }
102
+ } else merged.push(c);
103
+ }
104
+ for (const c of fresh) if (!seen.has(c.id)) { merged.push(c); seen.add(c.id); }
105
+ assertOpsWrite(file, WRITER);
106
+ await write(file, { ...record, checks: merged });
107
+ return true;
108
+ } catch (e) {
109
+ console.error('[prdOutcomeRecord] mergeOutcomeChecks failed', epicId, slug, e && e.message ? e.message : e);
110
+ return false;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * writeCheckBody({ cwd, epicId, slug, id, body, write? }) → Promise<string|null>.
116
+ * Writes one http check's response body to
117
+ * scheduler/epics/<epicId>/outcomes/<slug>.bodies/<id>.txt (atomic, writer
118
+ * 'scheduler'; overwritten per id, so each check keeps one copy). Returns the
119
+ * absolute path, or null on a bad id / write failure. Never throws. The
120
+ * directory lives under the Epic's scheduler folder, so epicPurge removes it
121
+ * with the outcome records.
122
+ */
123
+ async function writeCheckBody({ cwd, epicId, slug, id, body, write = writeTextAtomic } = {}) {
124
+ try {
125
+ assertIds(epicId, slug);
126
+ if (typeof id !== 'string' || !SLUG_RE.test(id) || id.includes('..')) throw new Error(`invalid check id "${id}"`);
127
+ if (typeof body !== 'string') throw new Error('body must be a string');
128
+ const file = opsPath(cwd, 'scheduler', 'epics', epicId, 'outcomes', `${slug}.bodies`, `${id}.txt`);
129
+ assertOpsWrite(file, WRITER);
130
+ await write(file, body);
131
+ return file;
132
+ } catch (e) {
133
+ console.error('[prdOutcomeRecord] writeCheckBody failed', epicId, slug, id, e && e.message ? e.message : e);
134
+ return null;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Pure: derive { verdict, commits, files, gates, checks } from a finalized
140
+ * job row plus the run's verifyResult. `gates` holds the verifier verdict
141
+ * (always) and the row's gate re-run (gateShadow) when one is recorded;
142
+ * `checks` holds the structured-criteria results when present.
143
+ */
144
+ function buildOutcomeFromJob({ job, verifyResult = null, commits = [], files = [] }) {
145
+ const j = job || {};
146
+ /** @type {Array<Record<string, unknown>>} */
147
+ const gates = [{
148
+ source: 'verifier',
149
+ verdict: (verifyResult && verifyResult.verdict) || j.verifierVerdict || (j.exitCode === 0 ? 'clean' : null),
150
+ reason: (verifyResult && verifyResult.reason) || j.error || null,
151
+ exitCode: j.exitCode ?? null,
152
+ terminalReason: j.terminalReason ?? null,
153
+ }];
154
+ const shadow = j.gateShadow && typeof j.gateShadow === 'object' ? j.gateShadow : null;
155
+ if (shadow) {
156
+ gates.push({
157
+ source: `gate:${shadow.source ?? 'prd'}`,
158
+ status: shadow.status ?? null,
159
+ head: shadow.head ?? null,
160
+ ranAt: shadow.ranAt ?? null,
161
+ results: Array.isArray(shadow.results) ? shadow.results : [],
162
+ });
163
+ }
164
+ let checks = [];
165
+ if (shadow && Array.isArray(shadow.criteriaChecks)) checks = shadow.criteriaChecks;
166
+ else if (j.criteriaChecks && Array.isArray(j.criteriaChecks.results)) checks = j.criteriaChecks.results;
167
+ return { verdict: j.status ?? null, commits, files, gates, checks };
168
+ }
169
+
170
+ /**
171
+ * Files touched by `shas` in `cwd` (union, sorted). Never throws — a git
172
+ * error yields whatever was collected so far.
173
+ */
174
+ async function listCommitFiles(cwd, shas) {
175
+ const { execGit } = require('../git/gitExec.cjs');
176
+ const out = new Set();
177
+ for (const sha of strList(shas, MAX_COMMITS)) {
178
+ try {
179
+ const text = await execGit(cwd, ['show', '--name-only', '--format=', '--no-renames', sha], { timeout: 10_000 });
180
+ for (const line of String(text).split('\n')) {
181
+ const p = line.trim();
182
+ if (p) out.add(p.split(path.sep).join('/'));
183
+ }
184
+ } catch { /* unknown sha / non-git cwd */ }
185
+ }
186
+ return [...out].sort().slice(0, MAX_FILES);
187
+ }
188
+
189
+ module.exports = {
190
+ writeOutcomeRecord, mergeOutcomeChecks, writeCheckBody, outcomeRecordPath, buildOutcomeFromJob, listCommitFiles, SCHEMA_VERSION,
191
+ };
@@ -403,6 +403,21 @@ function loadMachineStateSync() {
403
403
  }
404
404
  }
405
405
 
406
+ /**
407
+ * The machine-runtime state file's `config` (firePolicy, utilizationThreshold,
408
+ * …) or {} when the file is missing, unreadable or carries none. Reads only the
409
+ * small machine file — never a project queue shard — and never throws.
410
+ */
411
+ function readMachineConfigSync() {
412
+ try {
413
+ const m = loadMachineStateSync();
414
+ const c = m && m.shaped && m.shaped.config;
415
+ return c && typeof c === 'object' ? c : {};
416
+ } catch {
417
+ return {};
418
+ }
419
+ }
420
+
406
421
  async function loadMachineState() {
407
422
  let raw;
408
423
  try {
@@ -604,6 +619,7 @@ module.exports = {
604
619
  writeJsonAtomic,
605
620
  writeJsonAtomicSync,
606
621
  findLongestValidJsonPrefix,
622
+ readMachineConfigSync,
607
623
  };
608
624
 
609
625
  // Lazy path getters (SM_SCHEDULER_HOME resolved at read, never at require).
@@ -34,7 +34,13 @@ const fs = require('node:fs');
34
34
  const path = require('node:path');
35
35
  const { splitFrontmatter } = require('../prd/prdFrontmatter.cjs');
36
36
  const { readTail } = require('../util/fileTail.cjs');
37
- const { resolvePrdWriteDir } = require('../prd/prdLocations.cjs');
37
+ const {
38
+ resolvePrdWriteDir,
39
+ resolveEpicPrdWriteDir,
40
+ listEpicPrdDirs,
41
+ listArchivedPrdDirs,
42
+ isSafeEpicId,
43
+ } = require('../prd/prdLocations.cjs');
38
44
  const atomicFs = require('../util/atomicFs.cjs');
39
45
 
40
46
  // ─── VERDICT_LABELS — deliberate duplicate ──────────────────────────────────
@@ -74,6 +80,7 @@ const FAILURE_CLASSES = {
74
80
  TRANSCRIPT_ERRORS: 'transcript-errors',
75
81
  ABANDONED_BACKGROUND_TASK: 'abandoned-background-task',
76
82
  BLOCKED_BY_FOREIGN_WIP: 'blocked-by-foreign-wip',
83
+ EXECUTOR_FAIL: 'executor-fail',
77
84
  UNKNOWN: 'unknown',
78
85
  };
79
86
 
@@ -105,6 +112,7 @@ const RECOVERY_ACTIONS = {
105
112
  // guidance into that cold-read investigation.
106
113
  [FAILURE_CLASSES.ABANDONED_BACKGROUND_TASK]: 'investigate',
107
114
  [FAILURE_CLASSES.BLOCKED_BY_FOREIGN_WIP]: 'archive',
115
+ [FAILURE_CLASSES.EXECUTOR_FAIL]: 'investigate',
108
116
  [FAILURE_CLASSES.UNKNOWN]: 'investigate',
109
117
  };
110
118
 
@@ -132,6 +140,8 @@ const PREVENTION_HINTS = {
132
140
  'A headless run cannot receive a background-task completion notification — never let a long Bash command auto-background past its foreground timeout and then wait for it. Run long commands with an explicit bound (`timeout <N> <cmd>`) so they finish in the foreground, or poll their output file directly instead of waiting on Monitor/notification.',
133
141
  [FAILURE_CLASSES.BLOCKED_BY_FOREIGN_WIP]:
134
142
  'This job correctly reported `SCHEDULER_VERDICT: BLOCKED_BY_FOREIGN_WIP` against a sibling job\'s in-flight, uncommitted files three times in a row — auto-requeue is exhausted (reconcile() only clears this once the blocked paths go clean). This is not a defect in this PRD\'s own work: check on the sibling job/human that owns the still-dirty path(s) named on the job row, and either wait for them to commit or manually reset this job to `pending` once the tree is clear. Do not author a fix-plan PRD against it.',
143
+ [FAILURE_CLASSES.EXECUTOR_FAIL]:
144
+ "The executor ended `SCHEDULER_VERDICT: FAIL` and stated why — read its reason under 'What happened'. That stated reason, not a log-tail pattern, is what to fix. If the blocker is a step only a person can do (an account, dashboard or signing action), it belongs behind a preflight hold, not in the job body (PRD_AUTHORING.md §6).",
135
145
  [FAILURE_CLASSES.UNKNOWN]:
136
146
  'Re-run the acceptance criteria gate locally against the failure log to pin down the specific break before re-queuing.',
137
147
  };
@@ -162,7 +172,13 @@ const SELF_QUEUE_SKILL_RE = /Launching skill: session-manager-dev:(develop|proce
162
172
  // rule now requires a stream-json tool_use `"name":"ScheduleWakeup"` field, and
163
173
  // classifyFailure strips init events before any rule runs.
164
174
  const SELF_QUEUE_WAKEUP_RE = /"name"\s*:\s*"ScheduleWakeup"/;
165
- const STUCK_LOOP_RE = /\b(until\s|while\s+true|sleep\s)/i;
175
+ // Stuck-loop rule: matched only against real Bash tool_use commands (see
176
+ // bashCommandsIn), never prose. Incident: starry-night-2
177
+ // 856-ios-testflight-public-link (run 2026-11-24T17-02-30-189Z) — the old
178
+ // word rule matched 'until ' in skill-catalog text in the log tail; 49 of 114
179
+ // reports since 2026-11-17 were prose false positives.
180
+ const UNBOUNDED_LOOP_RE = /\b(?:while\s+(?:true\b|:)|until\s)[\s\S]*?(?:;|\n)\s*do\b/;
181
+ const TIMEOUT_BOUND_RE = /\btimeout\s+(?:-\S+\s+)*\d/;
166
182
  const AC_CHECKBOX_RE = /^\s*[-*]\s*\[[xX]\]/;
167
183
  const SENTINEL_PASS_RE = /SCHEDULER_VERDICT:\s*PASS/;
168
184
  const STUCK_LOOP_WINDOW = 40; // "final lines" per AC
@@ -188,6 +204,31 @@ function structuredPassLine(line) {
188
204
  }
189
205
  }
190
206
 
207
+ /**
208
+ * Shell commands from stream-json Bash tool_use events in `lines`. Plain-text
209
+ * lines, assistant text blocks, tool_result content and system events yield
210
+ * nothing; malformed JSON lines are skipped. Pure; O(n) in characters.
211
+ */
212
+ function bashCommandsIn(lines) {
213
+ const out = [];
214
+ for (const line of lines || []) {
215
+ if (typeof line !== 'string' || !line.includes('"tool_use"') || !line.includes('"Bash"')) continue;
216
+ let obj;
217
+ try {
218
+ obj = JSON.parse(line.trim());
219
+ } catch {
220
+ continue;
221
+ }
222
+ if (!obj || obj.type !== 'assistant' || !Array.isArray(obj.message?.content)) continue;
223
+ for (const c of obj.message.content) {
224
+ if (c && c.type === 'tool_use' && c.name === 'Bash' && typeof c.input?.command === 'string') {
225
+ out.push(c.input.command);
226
+ }
227
+ }
228
+ }
229
+ return out;
230
+ }
231
+
191
232
  /**
192
233
  * Drop every stream-json harness init event (`"type":"system"` +
193
234
  * `"subtype":"init"`) from a log tail. That line names every available tool
@@ -239,22 +280,27 @@ function classifyFailure({ verdict, logTail: rawLogTail }) {
239
280
  // Checked before SELF_QUEUE/STUCK_LOOP: the verifier already did the real
240
281
  // detection work (scanning for the harness's own auto-background marker
241
282
  // text) to produce this verdict — trust it rather than re-deriving from the
242
- // log tail, which can otherwise false-match SELF_QUEUE_WAKEUP_RE/STUCK_LOOP_RE
243
- // on words like "sleep"/"background" that appear in the harness's own
244
- // auto-background tool_result.
283
+ // log tail, which can otherwise false-match SELF_QUEUE_WAKEUP_RE on words
284
+ // like "background" that appear in the harness's own auto-background
285
+ // tool_result.
245
286
  if (verdict === 'abandoned_background_task') {
246
287
  return FAILURE_CLASSES.ABANDONED_BACKGROUND_TASK;
247
288
  }
248
289
 
249
290
  // Checked before STUCK_LOOP: a backgrounded command + ScheduleWakeup
250
291
  // (variant b) can land words like "sleep"/"poll" in the tail via the PRD's
251
- // own AC text, which would otherwise false-match STUCK_LOOP_RE (see PRD 771).
292
+ // own AC text; self-queue is the truer class for that run (see PRD 771).
252
293
  if (SELF_QUEUE_SKILL_RE.test(logTail || '') || SELF_QUEUE_WAKEUP_RE.test(logTail || '')) {
253
294
  return FAILURE_CLASSES.SELF_QUEUE;
254
295
  }
255
296
 
297
+ // Checked before STUCK_LOOP: the executor ended SCHEDULER_VERDICT: FAIL and
298
+ // stated its own reason — trust that over any log-tail pattern.
299
+ if (verdict === 'sentinel_fail') return FAILURE_CLASSES.EXECUTOR_FAIL;
300
+
301
+ // Only a real, unbounded Bash loop command counts — never prose.
256
302
  const tailWindow = lines.slice(-STUCK_LOOP_WINDOW);
257
- if (tailWindow.some((l) => STUCK_LOOP_RE.test(l))) {
303
+ if (bashCommandsIn(tailWindow).some((cmd) => UNBOUNDED_LOOP_RE.test(cmd) && !TIMEOUT_BOUND_RE.test(cmd))) {
258
304
  return FAILURE_CLASSES.STUCK_LOOP;
259
305
  }
260
306
 
@@ -317,14 +363,31 @@ function readRunMeta(runDir, slug) {
317
363
  }
318
364
  }
319
365
 
320
- function readPrdBody(cwd, slug) {
321
- if (!cwd) return '';
322
- try {
323
- const raw = fs.readFileSync(path.join(resolvePrdWriteDir(cwd), `${slug}.md`), 'utf8');
324
- return splitFrontmatter(raw).body;
325
- } catch {
326
- return '';
366
+ /**
367
+ * Read the parked job's PRD body (frontmatter stripped). Looks where PRDs
368
+ * really live, in order: the job's own Epic prds/, every Epic prds/ of the
369
+ * project, every prds-archived/ twin, then the retired flat dir. Scoped to
370
+ * job.cwd only — never a machine-wide scan. Returns '' when not found; never
371
+ * throws.
372
+ */
373
+ function readPrdBody(job) {
374
+ const cwd = job?.cwd;
375
+ const slug = job?.slug;
376
+ if (!cwd || typeof cwd !== 'string' || !slug) return '';
377
+ const candidates = [];
378
+ const add = (dir) => { if (dir && !candidates.includes(dir)) candidates.push(dir); };
379
+ if (isSafeEpicId(job.epicId)) {
380
+ try { add(resolveEpicPrdWriteDir(cwd, job.epicId)); } catch { /* skip */ }
381
+ }
382
+ try { for (const d of listEpicPrdDirs(cwd)) add(d); } catch { /* skip */ }
383
+ try { for (const d of listArchivedPrdDirs(cwd)) add(d); } catch { /* skip */ }
384
+ try { add(resolvePrdWriteDir(cwd)); } catch { /* skip */ }
385
+ for (const dir of candidates) {
386
+ let raw;
387
+ try { raw = fs.readFileSync(path.join(dir, `${slug}.md`), 'utf8'); } catch { continue; }
388
+ try { return splitFrontmatter(raw).body; } catch { return ''; }
327
389
  }
390
+ return '';
328
391
  }
329
392
 
330
393
  /**
@@ -412,7 +475,7 @@ async function writeRcaReport({ job, runDir, verdict, annotations, investigation
412
475
  const meta = readRunMeta(runDir, job.slug);
413
476
  const logPath = runDir ? path.join(runDir, `${job.slug}.log`) : null;
414
477
  const logTail = logPath ? readTail(logPath, 64 * 1024) : '';
415
- const acText = extractAcceptanceCriteria(readPrdBody(job.cwd, job.slug));
478
+ const acText = extractAcceptanceCriteria(readPrdBody(job));
416
479
  const failureClass = classifyFailure({ verdict, logTail });
417
480
 
418
481
  const markdown = buildRcaMarkdown({
@@ -442,6 +505,7 @@ module.exports = {
442
505
  // Pure helpers, exported for unit tests.
443
506
  humanVerdict,
444
507
  classifyFailure,
508
+ bashCommandsIn,
445
509
  stripHarnessInitEvents,
446
510
  extractAcceptanceCriteria,
447
511
  extractRcaBlock,
@@ -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).
@@ -115,6 +117,15 @@ const ScheduleJobSchema = z
115
117
  quietLeaseDegraded: z.boolean().optional(),
116
118
  // Salvaged uncommitted diff patch path (PRD 1098).
117
119
  salvagePatch: z.string().nullable().optional(),
120
+ // Artifact evidence captured before the job worktree was removed, bound
121
+ // to the run that captured it (reverifyNeedsReview reuses it for that run only).
122
+ artifactEvidence: z.object({
123
+ runId: z.string(),
124
+ ok: z.boolean(),
125
+ verified: z.array(z.any()),
126
+ paths: z.array(z.string()),
127
+ capturedAt: z.string(),
128
+ }).passthrough().nullable().optional(),
118
129
  // Pin of a dead run's uncommitted checkout work (refs/sm-uncommitted/...), PRD 2892.
119
130
  uncommittedSnapshot: z.object({ sha: z.string(), ref: z.string() }).optional(),
120
131
  // Leftover-attribution fields: the newly-dirty paths a terminal run left
@@ -147,6 +158,13 @@ const ScheduleJobSchema = z
147
158
  // at entry, deleted at resolution).
148
159
  needsReviewEntryRunId: z.string().nullable().optional(),
149
160
  needsReviewEnteredAt: z.string().nullable().optional(),
161
+ // Content id of the AgentSnapshot (agentSnapshot.cjs) the job's first
162
+ // dispatch pinned; every later dispatch (resume) re-runs that snapshot.
163
+ agentSnapshotId: z.string().optional(),
164
+ // Validator only: the { ids, failedIds } per judged PRD built at dispatch
165
+ // from the check results the validator was shown; notifyOriginatingTab
166
+ // cross-checks the verdict against it instead of re-running the checks.
167
+ validatorCriteriaExpected: z.record(z.string(), z.object({ ids: z.array(z.string()), failedIds: z.array(z.string()) })).optional(),
150
168
  })
151
169
  .passthrough();
152
170
 
@@ -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;
@@ -109,12 +109,16 @@ function heartbeatPath() { return assertNotLiveRoot(path.join(schedulerHome(), '
109
109
  function sessionSlotsConfigPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'session-slots-config.json'), 'sessionSlotsConfigPath'); }
110
110
  /** Machine-level per-project 'Scripts may run Tasks' switches, keyed by abs cwd (tasks/taskSwitch.cjs). */
111
111
  function taskSwitchesPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'task-switches.json'), 'taskSwitchesPath'); }
112
+ /** Machine-level scheduler chat turns the usage hold kept, delivered later per tab (heldSchedulerTurns.cjs). */
113
+ function heldSchedulerTurnsPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'held-scheduler-turns.json'), 'heldSchedulerTurnsPath'); }
114
+ /** Machine-level per-project 'Scripts may run Demo Video' switches, keyed by abs cwd (project-pages/videoScriptPress.cjs). */
115
+ function videoScriptSwitchesPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'video-script-switches.json'), 'videoScriptSwitchesPath'); }
116
+ /** Machine-level ledger of scripted Demo Video presses (entryId -> epicId, slug, externalRef) (project-pages/videoScriptPress.cjs). */
117
+ function videoScriptRunsPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'video-script-runs.json'), 'videoScriptRunsPath'); }
112
118
  /** Machine-level (project cwd, externalRef) -> Epic id index (epic/externalRefIndex.cjs). */
113
119
  function externalRefIndexPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'external-refs.json'), 'externalRefIndexPath'); }
114
120
  /** Machine-level "Needs you" items posted by outside apps (feedback-remote/needsYouStore.cjs). */
115
121
  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
122
  function watchdogLogsDir() { return assertNotLiveRoot(path.join(schedulerHome(), 'logs'), 'watchdogLogsDir'); }
119
123
  function restartRequestPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restart-request.json'), 'restartRequestPath'); }
120
124
  function restartingMarkerPath() { return assertNotLiveRoot(path.join(schedulerHome(), 'restarting.json'), 'restartingMarkerPath'); }
@@ -207,9 +211,11 @@ module.exports = {
207
211
  heartbeatPath,
208
212
  sessionSlotsConfigPath,
209
213
  taskSwitchesPath,
214
+ heldSchedulerTurnsPath,
215
+ videoScriptSwitchesPath,
216
+ videoScriptRunsPath,
210
217
  externalRefIndexPath,
211
218
  needsYouPath,
212
- epicStateSnapshotPath,
213
219
  adminTokenPath,
214
220
  machineStateLogCwd,
215
221
  worktreeBase,