claude-code-session-manager 0.142.0 → 0.144.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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Pure classifier: did the OS job sandbox itself refuse something the job
5
+ * tried? Such a failure is an environment limit, not a code defect — an
6
+ * auto-fix investigation runs in the same sandbox and hits the same wall
7
+ * (Self 1313 -> 1313-fix). Deliberately narrow: each pattern needs the
8
+ * sandbox-specific symptom AND its object on one line, so an ordinary EACCES
9
+ * in user code or the bare word "sandbox" never matches.
10
+ */
11
+
12
+ const PATTERNS = [
13
+ ['claude-dir-write', /^(?=[^\n]*(?:denied|EPERM|EACCES|read-only|not permitted|\bblocked\b|\bblocks\b))[^\n]*?(?:sandbox[^\n]{0,80}\.claude\/|\.claude\/[^\n]{0,80}sandbox)|(?:Operation not permitted|Permission denied|Errno 30|Read-only file system|read-only filesystem)[^\n]{0,160}\.claude\/|\.claude\/[^\n]{0,160}(?:Operation not permitted|Permission denied|Errno 30|Read-only file system|read-only filesystem)/im],
14
+ ['unix-socket', /(?:Operation not permitted)[^\n]{0,80}AF_UNIX|AF_UNIX[^\n]{0,80}Operation not permitted/i],
15
+ ['readonly-tmp', /(?:Errno 30|Read-only file system)[^\n]{0,80}\/tmp|\/tmp[^\n]{0,80}(?:Errno 30|Read-only file system)/i],
16
+ ];
17
+
18
+ const MAX_BLOCK_LINES = 60;
19
+ const TRACEBACK_START = /^Traceback \(most recent call last\):/;
20
+ const ERROR_LINE = /(?:Operation not permitted|Errno 30|Read-only file system)/i;
21
+
22
+ const ENVIRONMENT_LIMIT_MESSAGE =
23
+ 'environment limit (job sandbox), not a code bug — see PRD_AUTHORING.md#job-sandbox-limits';
24
+
25
+ /** @returns {null | { kind: 'claude-dir-write'|'unix-socket'|'readonly-tmp', evidence: string }} */
26
+ function detectSandboxEnvironmentLimit(text) {
27
+ if (typeof text !== 'string' || !text) return null;
28
+ for (const [kind, re] of PATTERNS) {
29
+ const m = re.exec(text);
30
+ if (m) return { kind, evidence: m[0].slice(0, 200) };
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /** Plain per-line detection (single-line matches only). */
36
+ function detectPerLine(text) {
37
+ if (typeof text !== 'string' || !text) return null;
38
+ for (const line of text.split(/\r?\n/)) {
39
+ const hit = detectSandboxEnvironmentLimit(line);
40
+ if (hit) return hit;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * Bash tool_result bodies only: per-line detection, then a traceback-block
47
+ * scan. Anchor on an error line, look back to the nearest
48
+ * "Traceback (most recent call last):" (at most MAX_BLOCK_LINES lines) and
49
+ * classify unix-socket if AF_UNIX is in that block, readonly-tmp if /tmp is.
50
+ * A block ends at its exception line (the first non-indented line after the
51
+ * header), so a later unrelated line never joins it; each new header opens a
52
+ * fresh block (chained tracebacks work). Linear: one pass tracking the block start.
53
+ */
54
+ function detectBashBody(text) {
55
+ if (typeof text !== 'string' || !text) return null;
56
+ const lines = text.split(/\r?\n/);
57
+ const direct = detectPerLine(text);
58
+ if (direct) return direct;
59
+ let start = -1;
60
+ for (let i = 0; i < lines.length; i++) {
61
+ if (TRACEBACK_START.test(lines[i])) { start = i; continue; }
62
+ if (start < 0 || lines[i].trim() === '' || /^\s/.test(lines[i])) continue;
63
+ // First non-indented line after the header is the exception line: the block ends here.
64
+ const blockStart = start;
65
+ start = -1;
66
+ if (!ERROR_LINE.test(lines[i]) || i - blockStart > MAX_BLOCK_LINES) continue;
67
+ const block = lines.slice(blockStart, i + 1).join('\n');
68
+ if (/Operation not permitted/i.test(lines[i]) && block.includes('AF_UNIX')) {
69
+ return { kind: 'unix-socket', evidence: lines[i].slice(0, 200) };
70
+ }
71
+ if (/Errno 30|Read-only file system/i.test(lines[i]) && block.includes('/tmp')) {
72
+ return { kind: 'readonly-tmp', evidence: lines[i].slice(0, 200) };
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * Detect a sandbox refusal in a stream-json log tail. Only text the sandbox
80
+ * itself produced is considered: decoded Bash tool_result content, and the
81
+ * executor's `SCHEDULER_VERDICT: FAIL <reason>` from the final result text.
82
+ * Text a job merely read (Read tool_result) or quoted (assistant text) is ignored.
83
+ * @param {string} text
84
+ * @returns {null | { kind: 'claude-dir-write'|'unix-socket'|'readonly-tmp', evidence: string }}
85
+ */
86
+ function sandboxLimitFromStreamJson(text) {
87
+ if (typeof text !== 'string' || !text) return null;
88
+ const bashIds = new Set();
89
+ let hit = null;
90
+ let resultText = null;
91
+ let structuredOutput;
92
+ for (const raw of text.split('\n')) {
93
+ const line = raw.trim();
94
+ if (!line || line[0] !== '{') continue;
95
+ let ev;
96
+ try { ev = JSON.parse(line); } catch { continue; }
97
+ if (!ev || typeof ev !== 'object') continue;
98
+ if (ev.type === 'result' && typeof ev.result === 'string') {
99
+ resultText = ev.result;
100
+ const so = ev.structured_output ?? ev.structuredOutput;
101
+ if (so && typeof so === 'object' && !Array.isArray(so)) structuredOutput = so;
102
+ continue;
103
+ }
104
+ const content = ev.message && Array.isArray(ev.message.content) ? ev.message.content : null;
105
+ if (!content) continue;
106
+ for (const item of content) {
107
+ if (!item || typeof item !== 'object') continue;
108
+ if (ev.type === 'assistant' && item.type === 'tool_use' && item.name === 'Bash' && item.id) {
109
+ bashIds.add(item.id);
110
+ } else if (ev.type === 'user' && item.type === 'tool_result' && bashIds.has(item.tool_use_id)) {
111
+ if (hit || item.is_error !== true) continue;
112
+ const body = typeof item.content === 'string'
113
+ ? item.content
114
+ : Array.isArray(item.content)
115
+ ? item.content.filter((b) => b && b.type === 'text').map((b) => b.text ?? '').join('')
116
+ : '';
117
+ hit = detectBashBody(body);
118
+ }
119
+ }
120
+ }
121
+ if (hit) return hit;
122
+ if (resultText || structuredOutput) {
123
+ // Lazy require: runVerify.cjs is large.
124
+ const { scanSentinelReason } = require('../../runVerify.cjs');
125
+ return detectPerLine(scanSentinelReason({ resultText, ...(structuredOutput ? { structuredOutput } : {}) }, []));
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /**
131
+ * Finalize stamp/clear decision for a job row.
132
+ * @returns {{ environmentLimit: object|null, error: string|null }}
133
+ */
134
+ function environmentLimitStamp(sandboxLimit, status) {
135
+ if (sandboxLimit && (status === 'failed' || status === 'needs_review')) {
136
+ return { environmentLimit: sandboxLimit, error: ENVIRONMENT_LIMIT_MESSAGE };
137
+ }
138
+ return { environmentLimit: null, error: null };
139
+ }
140
+
141
+ module.exports = { detectSandboxEnvironmentLimit, sandboxLimitFromStreamJson, environmentLimitStamp, ENVIRONMENT_LIMIT_MESSAGE };
@@ -115,8 +115,19 @@ const ScheduleJobSchema = z
115
115
  // quietMachineWaitMs without the machine going quiet — tells a reader the
116
116
  // job's measurements ran under contention, not on a quiet machine.
117
117
  quietLeaseDegraded: z.boolean().optional(),
118
+ // Set when the job sandbox itself refused the run (sandboxEnvironmentLimit.cjs); auto-fix skips such rows.
119
+ environmentLimit: z.object({ kind: z.string(), evidence: z.string() }).optional(),
118
120
  // Salvaged uncommitted diff patch path (PRD 1098).
119
121
  salvagePatch: z.string().nullable().optional(),
122
+ // Artifact evidence captured before the job worktree was removed, bound
123
+ // to the run that captured it (reverifyNeedsReview reuses it for that run only).
124
+ artifactEvidence: z.object({
125
+ runId: z.string(),
126
+ ok: z.boolean(),
127
+ verified: z.array(z.any()),
128
+ paths: z.array(z.string()),
129
+ capturedAt: z.string(),
130
+ }).passthrough().nullable().optional(),
120
131
  // Pin of a dead run's uncommitted checkout work (refs/sm-uncommitted/...), PRD 2892.
121
132
  uncommittedSnapshot: z.object({ sha: z.string(), ref: z.string() }).optional(),
122
133
  // Leftover-attribution fields: the newly-dirty paths a terminal run left
@@ -152,6 +163,10 @@ const ScheduleJobSchema = z
152
163
  // Content id of the AgentSnapshot (agentSnapshot.cjs) the job's first
153
164
  // dispatch pinned; every later dispatch (resume) re-runs that snapshot.
154
165
  agentSnapshotId: z.string().optional(),
166
+ // Validator only: the { ids, failedIds } per judged PRD built at dispatch
167
+ // from the check results the validator was shown; notifyOriginatingTab
168
+ // cross-checks the verdict against it instead of re-running the checks.
169
+ validatorCriteriaExpected: z.record(z.string(), z.object({ ids: z.array(z.string()), failedIds: z.array(z.string()) })).optional(),
155
170
  })
156
171
  .passthrough();
157
172
 
@@ -109,6 +109,12 @@ 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). */
@@ -205,6 +211,9 @@ module.exports = {
205
211
  heartbeatPath,
206
212
  sessionSlotsConfigPath,
207
213
  taskSwitchesPath,
214
+ heldSchedulerTurnsPath,
215
+ videoScriptSwitchesPath,
216
+ videoScriptRunsPath,
208
217
  externalRefIndexPath,
209
218
  needsYouPath,
210
219
  adminTokenPath,
@@ -18,12 +18,13 @@
18
18
  * taskSwitchRoute.cjs (humanPromptLedger.findHumanPromptContaining);
19
19
  * headless jobs and Tasks never record prompts there, so they fail here
20
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.
21
+ * 4. 403 quote_does_not_name_slots — no sentence of the quote is the
22
+ * one accepted form (see SLOT_COMMAND), or no whole sentence of the
23
+ * matched human prompt that contains the quote (or that the quote
24
+ * wholly covers) is that form — so "don't raise the limit to 14" or
25
+ * "raise the limit to 14?" never authorize via the quote
26
+ * 'raise the limit to 14'. The reason gives the form, e.g. say
27
+ * 'raise the limit to 14'.
27
28
  * Success: sessionSlots.setCap(cap) (persists + wakes waiters), one
28
29
  * slot_cap_changed audit event { from, to, epicId, quote, promptAt },
29
30
  * 200 { ok, from, to }.
@@ -45,99 +46,112 @@ const slotsBodySchema = z.object({
45
46
  callerJobSlug: z.string().max(256).optional(),
46
47
  }).strict();
47
48
 
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]}`];
49
+ // The one accepted sentence form, matched against a whole sentence after
50
+ // lowercasing and collapsing spaces:
51
+ // [please|ok|okay|so|now|then[,]] set|raise|increase|bump|lower|reduce|change
52
+ // [the|our] [session|slot|parallel] limit|cap|slots to <digits> [sessions|slots]
53
+ // Nothing else may be in that sentence. Anything else —
54
+ // questions, negations, percentages, number words, extra words — is refused.
55
+ const SLOT_COMMAND = new RegExp(
56
+ '^(?:(?:please|ok|okay|so|now|then),? )?'
57
+ + '(?:set|raise|increase|bump|lower|reduce|change) '
58
+ + '(?:(?:the|our) )?'
59
+ + '(?:(?:session|slot|parallel) )?'
60
+ + '(?:limit|cap|slots) to (\\d+)'
61
+ + '(?: (?:sessions|slots))?$',
62
+ );
63
+
64
+ /** The accepted form, as the refusal states it. @param {number} cap */
65
+ function acceptedFormHint(cap) {
66
+ return `say 'raise the limit to ${cap}' (one sentence: [please|ok|okay|so|now|then] `
67
+ + 'set|raise|increase|bump|lower|reduce|change [the|our] [session|slot|parallel] limit|cap|slots '
68
+ + 'to <number in digits> [sessions|slots], with nothing else in the sentence, a comma only right after '
69
+ + 'the lead-in word, and no question mark)';
84
70
  }
85
71
 
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();
72
+ /**
73
+ * Sentence spans of `text`: split on . ! ? ; and line breaks, the terminator
74
+ * kept with its sentence; a decimal ("14.5") is not split. Returns the
75
+ * lowercased, whitespace-collapsed body, its trimmed [start, end) in `text`,
76
+ * and the terminator ('' at the end of the text).
77
+ * @param {string} text
78
+ * @returns {Array<{ body: string, start: number, end: number, term: string }>}
79
+ */
80
+ function splitSentences(text) {
81
+ // Same-length mask keeps indices aligned with `text`.
82
+ const masked = text.toLowerCase().replace(/(\d)[.,](?=\d)/g, '$1#');
83
+ const out = [];
84
+ const sentence = /([^.!?;\r\n]*)([.!?;\r\n]|$)/g;
85
+ let m;
86
+ while ((m = sentence.exec(masked)) !== null) {
87
+ const raw = m[1];
88
+ const lead = raw.length - raw.replace(/^\s+/, '').length;
89
+ const trail = raw.length - raw.replace(/\s+$/, '').length;
90
+ const start = m.index + lead;
91
+ const end = m.index + raw.length - trail;
92
+ if (end > start) out.push({ body: raw.replace(/\s+/g, ' ').trim(), start, end, term: m[2] });
93
+ if (m[2] === '') break; // end of the text
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /** @param {string} body @param {string} term @param {number} cap */
99
+ function sentenceNamesCap(body, term, cap) {
100
+ if (term === '?' || !body) return false;
101
+ const hit = SLOT_COMMAND.exec(body);
102
+ return !!hit && hit[1] === String(cap);
99
103
  }
100
104
 
101
105
  /**
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
+ * True only when the human prompt `promptText` (the text the ledger matched)
107
+ * has a whole sentence in the strict SLOT_COMMAND form naming `cap` that
108
+ * either contains an occurrence of `quote` or lies wholly inside one. The
109
+ * quote is located the way humanPromptLedger matches it (lowercased,
110
+ * whitespace collapsed). A sentence the quote only partly overlaps never
111
+ * authorizes. Refuses on doubt.
112
+ * @param {unknown} promptText
113
+ * @param {unknown} quote
106
114
  * @param {number} cap
107
115
  */
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
- ];
116
+ function promptSentenceNamesSlots(promptText, quote, cap) {
117
+ if (typeof promptText !== 'string' || typeof quote !== 'string') return false;
118
+ if (!Number.isInteger(cap) || cap < 0) return false;
119
+ const q = quote.replace(/\s+/g, ' ').trim().toLowerCase();
120
+ if (!q) return false;
121
+ // Normalized prompt + map from each normalized char to its index in promptText.
122
+ const lower = promptText.toLowerCase();
123
+ let norm = '';
124
+ /** @type {number[]} */
125
+ const map = [];
126
+ for (let i = 0; i < lower.length; i++) {
127
+ if (/\s/.test(lower[i])) {
128
+ if (norm.length && norm[norm.length - 1] !== ' ') { norm += ' '; map.push(i); }
129
+ } else { norm += lower[i]; map.push(i); }
130
+ }
131
+ const sentences = splitSentences(promptText);
132
+ for (let at = norm.indexOf(q); at !== -1; at = norm.indexOf(q, at + 1)) {
133
+ const qs = map[at];
134
+ const qe = map[at + q.length - 1] + 1;
135
+ for (const s of sentences) {
136
+ const contains = s.start <= qs && qe <= s.end;
137
+ const covered = qs <= s.start && s.end <= qe;
138
+ if ((contains || covered) && sentenceNamesCap(s.body, s.term, cap)) return true;
139
+ }
140
+ }
141
+ return false;
118
142
  }
119
143
 
120
144
  /**
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.
145
+ * True only when one sentence of the quote is exactly the SLOT_COMMAND form
146
+ * naming `cap` in digits. Sentences split on . ! ? ; and line breaks; a
147
+ * sentence ended by '?' never authorizes; a decimal ("14.5") is not split, so
148
+ * it never reads as 14. Refuses on doubt.
131
149
  * @param {unknown} quote
132
150
  * @param {number} cap
133
151
  */
134
152
  function quoteNamesSlots(quote, cap) {
135
153
  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));
154
+ return splitSentences(quote).some((x) => sentenceNamesCap(x.body, x.term, cap));
141
155
  }
142
156
 
143
157
  /**
@@ -205,8 +219,8 @@ function registerSlotsRoute(adminHttp, deps = {}) {
205
219
  refuse(403, 'human_request_unverified', 'quote was not found in a prompt the human typed in this chat session');
206
220
  return;
207
221
  }
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}`);
222
+ if (!quoteNamesSlots(quote, cap) || !promptSentenceNamesSlots(found.text, quote, cap)) {
223
+ refuse(403, 'quote_does_not_name_slots', `the human's quote does not ask to change the session limit to ${cap} in the accepted form; ${acceptedFormHint(cap)}`);
210
224
  return;
211
225
  }
212
226
 
@@ -234,4 +248,4 @@ function registerSlotsRoute(adminHttp, deps = {}) {
234
248
  });
235
249
  }
236
250
 
237
- module.exports = { registerSlotsRoute, quoteNamesSlots, MAX_SLOTS_BODY_BYTES };
251
+ module.exports = { registerSlotsRoute, quoteNamesSlots, promptSentenceNamesSlots, MAX_SLOTS_BODY_BYTES };
@@ -74,6 +74,16 @@ function retireRestartRequest(file = schedulerPaths.restartRequestPath()) {
74
74
  try { fs.unlinkSync(file); } catch (e) { if (e?.code !== 'ENOENT') throw e; }
75
75
  }
76
76
 
77
+ /** Never throws: { ok: true } or { ok: false, error } (for the forced-reboot path). */
78
+ function retireRestartRequestBestEffort(file = schedulerPaths.restartRequestPath()) {
79
+ try {
80
+ retireRestartRequest(file);
81
+ return { ok: true };
82
+ } catch (e) {
83
+ return { ok: false, error: e?.code || e?.message || String(e) };
84
+ }
85
+ }
86
+
77
87
  // ---------- pure state machine ----------
78
88
 
79
89
  /**
@@ -88,20 +98,31 @@ function queueBusyCount(jobs, extraInFlight = 0) {
88
98
  return n + (Number.isFinite(extraInFlight) ? extraInFlight : 0);
89
99
  }
90
100
 
101
+ /** True when a request's requestedAt is earlier than bootedAt; unparsable/missing either → false. Pure. */
102
+ function requestPredatesBoot(request, bootedAt) {
103
+ const requestedMs = Date.parse(request?.requestedAt ?? '');
104
+ const bootedMs = typeof bootedAt === 'string' ? Date.parse(bootedAt) : NaN;
105
+ return Number.isFinite(requestedMs) && Number.isFinite(bootedMs) && requestedMs < bootedMs;
106
+ }
107
+
91
108
  /**
92
- * evaluateDrain({request, queueSnapshot, drainState, now, deadlineMs}) → {action, reason}
109
+ * evaluateDrain({request, queueSnapshot, drainState, now, deadlineMs, bootedAt}) → {action, reason}
93
110
  *
94
111
  * queueSnapshot: { running, investigating } counts (in-memory investigations
95
112
  * already folded in by the caller). drainState: the machine `drain` field
96
- * (null / {active}). Pure — no IO, no clock.
113
+ * (null / {active}). bootedAt: this process's boot time (ISO); a missing or
114
+ * unparsable value skips the predates-boot rule. Pure — no IO, no clock.
97
115
  *
98
116
  * no request, or request already completed → none (abort if a stale drain is still active)
117
+ * pending request written before bootedAt → abort (the restart it asked for already
118
+ * happened: force reboot, manual
119
+ * relaunch, or a crash before the stamp)
99
120
  * deadline passed → abort
100
121
  * request pending, drain not yet active → pause (engage drain)
101
122
  * drain active, anything running/investigating → wait
102
123
  * drain active, zero busy → restart
103
124
  */
104
- function evaluateDrain({ request, queueSnapshot, drainState, now, deadlineMs = DEFAULT_DRAIN_DEADLINE_MS } = {}) {
125
+ function evaluateDrain({ request, queueSnapshot, drainState, now, deadlineMs = DEFAULT_DRAIN_DEADLINE_MS, bootedAt } = {}) {
105
126
  const active = Boolean(drainState && drainState.active);
106
127
  if (!request || request.drainCompletedAt) {
107
128
  return active && !request
@@ -109,6 +130,9 @@ function evaluateDrain({ request, queueSnapshot, drainState, now, deadlineMs = D
109
130
  : { action: 'none', reason: request ? 'request-complete' : 'no-request' };
110
131
  }
111
132
  const requestedMs = Date.parse(request.requestedAt ?? '');
133
+ if (requestPredatesBoot(request, bootedAt)) {
134
+ return { action: 'abort', reason: 'request-predates-boot' };
135
+ }
112
136
  if (Number.isFinite(requestedMs) && now - requestedMs >= deadlineMs) {
113
137
  return { action: 'abort', reason: 'deadline' };
114
138
  }
@@ -118,12 +142,13 @@ function evaluateDrain({ request, queueSnapshot, drainState, now, deadlineMs = D
118
142
  }
119
143
 
120
144
  /**
121
- * bootDrainAction({drainState, request}) → 'clear' | 'keep' | 'none'.
145
+ * bootDrainAction({drainState, request, bootedAt}) → 'clear' | 'keep' | 'none'.
122
146
  * A drain whose request is complete (the restart happened) or gone is stale.
123
147
  */
124
- function bootDrainAction({ drainState, request } = {}) {
148
+ function bootDrainAction({ drainState, request, bootedAt } = {}) {
125
149
  if (!drainState || !drainState.active) return 'none';
126
150
  if (!request || request.drainCompletedAt) return 'clear';
151
+ if (requestPredatesBoot(request, bootedAt)) return 'clear';
127
152
  return 'keep';
128
153
  }
129
154
 
@@ -168,9 +193,11 @@ module.exports = {
168
193
  requestRestart,
169
194
  stampDrainCompleted,
170
195
  retireRestartRequest,
196
+ retireRestartRequestBestEffort,
171
197
  queueBusyCount,
172
198
  evaluateDrain,
173
199
  bootDrainAction,
200
+ requestPredatesBoot,
174
201
  effectivePaused,
175
202
  installedBuildDiffers,
176
203
  markRestarting,
@@ -0,0 +1,97 @@
1
+ // @ts-check
2
+ 'use strict';
3
+ // GET /admin/usage-hold — the usage hold Session Manager is applying to
4
+ // automatic claude -p runs right now ('pause above'), the same hold
5
+ // POST /admin/tasks refuses on. Answers
6
+ // 200 { ok: true, hold, threshold }
7
+ // where hold is null when nothing is held, else
8
+ // { reason, window, percent, threshold, resetsAt, detail } (+ baseThreshold
9
+ // when set) — publicHold below, the same shape every 429 usage_held answers,
10
+ // and threshold is the saved 'pause above' percent. A failed read answers
11
+ // 503 { ok: false, error: 'usage_hold_error', details }.
12
+ // Read by scripts that start claude -p directly (e.g. Self's Kiln daily job
13
+ // while its Task switch is off): they check `hold === null` before an
14
+ // automatic run. Read-only: ignores any query string, reads no body, writes nothing.
15
+
16
+ const { sendJson } = require('../feedback-remote/localAdminHttp.cjs');
17
+
18
+ /**
19
+ * @typedef {import('../../scheduler/utilizationHold.cjs').AutoDispatchHold} AutoDispatchHold
20
+ * @typedef {{
21
+ * reason: AutoDispatchHold['reason'] | null,
22
+ * window: string | null,
23
+ * percent: number | null,
24
+ * threshold: number | null,
25
+ * resetsAt: string | null,
26
+ * detail: string | null,
27
+ * baseThreshold?: number,
28
+ * }} PublicHold
29
+ */
30
+
31
+ /**
32
+ * Builds the hold's one outside shape from a real hold. baseThreshold (the
33
+ * saved 'pause above' before pro-rating) is forwarded only when it is a
34
+ * finite number.
35
+ * @param {AutoDispatchHold} hold
36
+ * @returns {PublicHold}
37
+ */
38
+ function toPublicHold(hold) {
39
+ /** @type {PublicHold} */
40
+ const out = {
41
+ reason: hold.reason ?? null,
42
+ window: hold.window ?? null,
43
+ percent: hold.percent ?? null,
44
+ threshold: hold.threshold ?? null,
45
+ resetsAt: hold.resetsAt ?? null,
46
+ detail: hold.detail ?? null,
47
+ };
48
+ if (typeof hold.baseThreshold === 'number' && Number.isFinite(hold.baseThreshold)) {
49
+ out.baseThreshold = hold.baseThreshold;
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * The hold's one outside shape, shared by GET /admin/usage-hold and every
56
+ * 429 usage_held answer; null when nothing is held.
57
+ * @param {AutoDispatchHold | null | undefined} hold
58
+ * @returns {PublicHold | null}
59
+ */
60
+ function publicHold(hold) {
61
+ return hold == null ? null : toPublicHold(hold);
62
+ }
63
+
64
+ /**
65
+ * The 429 usage_held body: the public hold minus detail, with detail and the
66
+ * caller's hint at the top level. A 429 usage_held always carries a real hold.
67
+ * @param {AutoDispatchHold} hold
68
+ * @param {string} hint
69
+ */
70
+ function usageHeldBody(hold, hint) {
71
+ const { detail, ...rest } = toPublicHold(hold);
72
+ return { ok: false, error: 'usage_held', hold: rest, detail, hint };
73
+ }
74
+
75
+ /**
76
+ * @param {{ registerRoute: Function }} adminHttp
77
+ * @param {{ usageHold?: () => AutoDispatchHold | null, threshold?: () => number }} [deps]
78
+ */
79
+ function registerUsageHoldRoute(adminHttp, deps = {}) {
80
+ const usageHold = deps.usageHold || (() => require('../../scheduler.cjs').currentUsageHold());
81
+ const threshold = deps.threshold || (() => require('../../scheduler.cjs').usageHoldThreshold());
82
+
83
+ adminHttp.registerRoute('GET', '/admin/usage-hold', (/** @type {unknown} */ _req, /** @type {import('node:http').ServerResponse} */ res) => {
84
+ let hold;
85
+ let t;
86
+ try {
87
+ hold = usageHold() ?? null;
88
+ t = threshold();
89
+ } catch (e) {
90
+ sendJson(res, 503, { ok: false, error: 'usage_hold_error', details: e instanceof Error ? e.message : String(e) });
91
+ return;
92
+ }
93
+ sendJson(res, 200, { ok: true, hold: publicHold(hold), threshold: t });
94
+ });
95
+ }
96
+
97
+ module.exports = { registerUsageHoldRoute, publicHold, usageHeldBody };