claude-code-session-manager 0.141.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 (200) 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-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.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/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -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;
@@ -0,0 +1,237 @@
1
+ /**
2
+ * slotsRoute.cjs — the agent path for the machine-wide session slot cap.
3
+ *
4
+ * GET /admin/scheduler/slots
5
+ * → 200 { ok, cap, min, max, inUse, available } from sessionSlots.cjs.
6
+ *
7
+ * POST /admin/scheduler/slots (body ≤ 64 KiB)
8
+ * { cap, quote, originClaudeSessionId, originProjectRoot?, callerJobSlug? }
9
+ * Changes the cap only on a verbatim quote of what the human typed in the
10
+ * calling chat session. Checks, in order, each refusal writing and auditing
11
+ * nothing:
12
+ * 1. 400 invalid_request — bad body, or cap not an integer in
13
+ * [MIN_SLOTS, MAX_SLOTS];
14
+ * 2. 403 called_from_headless_job — callerJobSlug is set (the MCP tool
15
+ * forwards SM_SCHEDULER_JOB_SLUG): a scheduled job never moves the cap;
16
+ * 3. 403 human_request_unverified — the quote is not in a prompt the
17
+ * human typed in originClaudeSessionId. Same verifier as
18
+ * taskSwitchRoute.cjs (humanPromptLedger.findHumanPromptContaining);
19
+ * headless jobs and Tasks never record prompts there, so they fail here
20
+ * too;
21
+ * 4. 403 quote_does_not_name_slots — the quote is not a change request:
22
+ * a change verb (set / raise / bump / lower / make …), a limit word
23
+ * (limit / cap / slots / sessions / parallel / concurrent) AND the new
24
+ * number given as the target ("to 14", "= 14", "at 14", "14 parallel
25
+ * sessions"). Naming a limit and a number in passing is not enough;
26
+ * a question or a percentage target is refused too.
27
+ * Success: sessionSlots.setCap(cap) (persists + wakes waiters), one
28
+ * slot_cap_changed audit event { from, to, epicId, quote, promptAt },
29
+ * 200 { ok, from, to }.
30
+ *
31
+ * Registered from index.cjs next to the other /admin/scheduler/ routes.
32
+ */
33
+ 'use strict';
34
+
35
+ const { z } = require('zod');
36
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
37
+
38
+ const MAX_SLOTS_BODY_BYTES = 64 * 1024;
39
+
40
+ const slotsBodySchema = z.object({
41
+ cap: z.unknown(),
42
+ quote: z.string().min(1).max(2000),
43
+ originClaudeSessionId: z.string().min(1).max(128),
44
+ originProjectRoot: z.string().min(1).optional(),
45
+ callerJobSlug: z.string().max(256).optional(),
46
+ }).strict();
47
+
48
+ const LIMIT_WORDS = '(?:limit|limits|cap|caps|slot|slots|session|sessions|parallel|parallelism|concurrent|concurrency)';
49
+ const CHANGE_VERBS = '(?:set|raise|increase|bump|lift|lower|reduce|drop|change|move|make)';
50
+ const NEGATION = '(?:not|never|no|dont|don t|won t|wont|can t|cant|shouldn t|shouldnt)';
51
+ const TARGET = '(?:to|=|at)';
52
+ const QUESTION_WORDS = '(?:will|would|do|does|did|may|might|are|is|can|could|should|shall|whether|want to)';
53
+ // A question word (or a '?') before the change verb, in the same clause, makes
54
+ // the quote a question ("will you raise the limit to 14"), never a request.
55
+ // A clause ends at , ; . ! or a line break (all normalized to ' . ').
56
+ const QUESTION_BEFORE_VERB = new RegExp(`(?:^| )(?:${QUESTION_WORDS}|\\?)(?: [^.]*)? ${CHANGE_VERBS}(?= |$)`);
57
+ // Any '?' after a change verb, anywhere later in the quote, makes it a question.
58
+ const QUESTION_AFTER_VERB = new RegExp(`(?:^| )${CHANGE_VERBS} (?:.* )?\\?`);
59
+ const PERCENT_WORDS = '(?:percent|per cent|pct|percentage)';
60
+ // Closing quotes and brackets a human (or a copy-paste) leaves after a '?'.
61
+ const TRAILING_CLOSERS = /[\s"'`\u201d\u2019\u00bb)\]}>]+$/;
62
+
63
+ const NUMBER_WORDS = [
64
+ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
65
+ 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen',
66
+ 'nineteen', 'twenty',
67
+ ];
68
+ const TENS = { 20: 'twenty', 30: 'thirty' };
69
+ const ANY_NUMBER = `(?:\\d+|${[...NUMBER_WORDS, 'thirty', 'forty', 'fifty'].join('|')})`;
70
+ // One filler word: letters only, never a number word, so a gap can never
71
+ // swallow half of "thirty two" or step over a different number.
72
+ const WORD = `(?!${ANY_NUMBER}(?: |$))[a-z]+`;
73
+ const gap = (/** @type {number} */ n) => `(?: ${WORD}){0,${n}}`;
74
+
75
+ /** @param {number} n */
76
+ function wordsFor(n) {
77
+ if (n < 0) return [];
78
+ if (n <= 20) return [NUMBER_WORDS[n]];
79
+ const tens = Math.floor(n / 10) * 10;
80
+ const unit = n % 10;
81
+ const t = TENS[/** @type {20|30} */ (tens)];
82
+ if (!t) return [];
83
+ return unit === 0 ? [t] : [`${t} ${NUMBER_WORDS[unit]}`];
84
+ }
85
+
86
+ /** @param {unknown} quote */
87
+ function normalizeQuote(quote) {
88
+ return String(quote)
89
+ .toLowerCase()
90
+ .replace(/\d+[.,]\d+/g, ' # ') // a decimal is never a cap; never let "14.5" read as 14
91
+ .replace(/%/g, ' percent ') // "14%" reads as "14 percent": a percentage, never a cap
92
+ .replace(/=/g, ' = ')
93
+ .replace(/[.!;,\r\n]/g, ' . ') // a clause boundary: no gap word or question scan crosses it
94
+ .replace(/\?/g, ' ? ') // a question mark: no gap word crosses it
95
+ .replace(/[:()[\]{}]/g, ' | ') // a phrase break: no gap word crosses it, the question scan does
96
+ .replace(/[^a-z0-9=.#?| ]/g, ' ')
97
+ .replace(/\s+/g, ' ')
98
+ .trim();
99
+ }
100
+
101
+ /**
102
+ * The anchored change-request patterns for `cap`:
103
+ * A. verb … limit word … to|=|at <cap> ("raise the limit to 14")
104
+ * B. verb … [to|=|at] <cap> … limit word ("make it 16 parallel sessions")
105
+ * The verb must be the base form and not negated; the number must stand alone.
106
+ * @param {number} cap
107
+ */
108
+ function changeRequestPatterns(cap) {
109
+ const num = `(?:${[String(cap), ...wordsFor(cap)].join('|')})`;
110
+ // The number must stand alone and not be a percentage ("14 percent", "14%").
111
+ const numEnd = `(?= |$)(?! ${ANY_NUMBER}(?: |$))(?! ${PERCENT_WORDS}(?: |$))`;
112
+ const verb = `(?<!${NEGATION}${gap(2)} )(?<=^| )${CHANGE_VERBS}`;
113
+ const verbAtStart = `(?:^| )${verb}`;
114
+ return [
115
+ new RegExp(`${verbAtStart}${gap(4)} ${LIMIT_WORDS}${gap(3)} ${TARGET} ${num}${numEnd}`),
116
+ new RegExp(`${verbAtStart}${gap(4)}(?: ${TARGET})? ${num}${numEnd}${gap(2)} ${LIMIT_WORDS}(?= |$)`),
117
+ ];
118
+ }
119
+
120
+ /**
121
+ * True only when the quote is a request to CHANGE the session limit to `cap`:
122
+ * a change verb, a limit word, and `cap` (digits, or English words up to
123
+ * thirty-nine) given as the new target. Mentioning a limit and a number is not
124
+ * enough — "lets see first 10 sessions chugging and then we will move the
125
+ * limit via the mcp" authorizes nothing. A question (ends with '?', or a
126
+ * '?' anywhere after the change verb, or a question word — will, would, do,
127
+ * does, did, may, might, are, is, can, could, should, shall, whether, want to —
128
+ * before the verb in its clause) and a percentage target ("14%", "14 percent",
129
+ * "14 per cent", "14 pct", "14 percentage") authorize nothing either.
130
+ * Refuses on doubt.
131
+ * @param {unknown} quote
132
+ * @param {number} cap
133
+ */
134
+ function quoteNamesSlots(quote, cap) {
135
+ if (typeof quote !== 'string' || !Number.isInteger(cap) || cap < 0) return false;
136
+ if (/\?$/.test(quote.replace(TRAILING_CLOSERS, ''))) return false; // a question is not a request
137
+ const q = normalizeQuote(quote);
138
+ if (QUESTION_AFTER_VERB.test(q)) return false;
139
+ if (QUESTION_BEFORE_VERB.test(q)) return false;
140
+ return changeRequestPatterns(cap).some((re) => re.test(q));
141
+ }
142
+
143
+ /**
144
+ * @param {{ registerRoute: Function }} adminHttp
145
+ * @param {{ findHumanPromptContaining?: Function, resolveProjectContext?: Function,
146
+ * sessionSlots?: any, appendAuditEvent?: Function, now?: () => number }} [deps]
147
+ */
148
+ function registerSlotsRoute(adminHttp, deps = {}) {
149
+ const findPrompt = deps.findHumanPromptContaining
150
+ || ((/** @type {string} */ s, /** @type {string} */ q, /** @type {number} */ n) => require('../feedback-remote/humanPromptLedger.cjs').findHumanPromptContaining(s, q, n));
151
+ const resolveContext = deps.resolveProjectContext
152
+ || ((/** @type {any} */ o) => require('../projectRootResolve.cjs').resolveProjectContext(o));
153
+ const slots = () => deps.sessionSlots || require('./sessionSlots.cjs');
154
+ const audit = deps.appendAuditEvent
155
+ || ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
156
+ const now = deps.now || Date.now;
157
+
158
+ adminHttp.registerRoute('GET', '/admin/scheduler/slots', (/** @type {any} */ _req, /** @type {any} */ res) => {
159
+ const s = slots();
160
+ sendJson(res, 200, {
161
+ ok: true,
162
+ cap: s.totalSlots(),
163
+ min: s.MIN_SLOTS,
164
+ max: s.MAX_SLOTS,
165
+ inUse: s.inUse(),
166
+ available: s.available(),
167
+ });
168
+ });
169
+
170
+ adminHttp.registerRoute('POST', '/admin/scheduler/slots', async (/** @type {any} */ req, /** @type {any} */ res) => {
171
+ const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
172
+ const refuse = (/** @type {number} */ status, /** @type {string} */ error, /** @type {string} */ reason) =>
173
+ sendJson(res, status, { ok: false, error, reason });
174
+
175
+ let raw;
176
+ try {
177
+ raw = await readBody(req, MAX_SLOTS_BODY_BYTES);
178
+ } catch (e) {
179
+ bad(e instanceof Error ? e.message : String(e));
180
+ return;
181
+ }
182
+ let json;
183
+ try { json = JSON.parse(raw || '{}'); } catch {
184
+ bad('body is not valid JSON');
185
+ return;
186
+ }
187
+ const parsed = slotsBodySchema.safeParse(json);
188
+ if (!parsed.success) {
189
+ bad(parsed.error.issues);
190
+ return;
191
+ }
192
+ const { cap, quote, originClaudeSessionId, originProjectRoot, callerJobSlug } = parsed.data;
193
+ const s = slots();
194
+ if (typeof cap !== 'number' || !Number.isInteger(cap) || cap < s.MIN_SLOTS || cap > s.MAX_SLOTS) {
195
+ bad(`cap must be an integer in [${s.MIN_SLOTS}, ${s.MAX_SLOTS}]`);
196
+ return;
197
+ }
198
+ if (callerJobSlug) {
199
+ refuse(403, 'called_from_headless_job', `a headless scheduled job ('${callerJobSlug}') never changes the slot limit; say in your final result what the human should set`);
200
+ return;
201
+ }
202
+
203
+ const found = findPrompt(originClaudeSessionId, quote, now());
204
+ if (!found) {
205
+ refuse(403, 'human_request_unverified', 'quote was not found in a prompt the human typed in this chat session');
206
+ return;
207
+ }
208
+ if (!quoteNamesSlots(quote, cap)) {
209
+ refuse(403, 'quote_does_not_name_slots', `the human's quote does not ask to change the session limit to ${cap}`);
210
+ return;
211
+ }
212
+
213
+ let epicId = null;
214
+ try {
215
+ const ctx = resolveContext({ originClaudeSessionId, originProjectRoot });
216
+ if (ctx && typeof ctx.epicId === 'string' && ctx.epicId) epicId = ctx.epicId;
217
+ } catch { epicId = null; }
218
+
219
+ const from = s.totalSlots();
220
+ let to;
221
+ try {
222
+ to = s.setCap(cap);
223
+ } catch (e) {
224
+ sendJson(res, 500, { ok: false, error: 'cap_write_failed', details: e instanceof Error ? e.message : String(e) });
225
+ return;
226
+ }
227
+ const promptMs = Number(found.at);
228
+ const promptAt = Number.isFinite(promptMs) ? new Date(promptMs).toISOString() : null;
229
+ try {
230
+ audit('slot_cap_changed', { from, to, epicId, quote, promptAt });
231
+ } catch { /* audit is best-effort, like taskSwitchRoute */ }
232
+
233
+ sendJson(res, 200, { ok: true, from, to });
234
+ });
235
+ }
236
+
237
+ module.exports = { registerSlotsRoute, quoteNamesSlots, MAX_SLOTS_BODY_BYTES };