claude-code-session-manager 0.140.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,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 };
@@ -0,0 +1,258 @@
1
+ /**
2
+ * toolClearance.cjs — single-use clearances for tool-risk 'confirm' calls.
3
+ *
4
+ * Flow (see session-manager-operations/architecture/tool-risk.md):
5
+ * 1. The guard (scripts/hooks/lib/guard-tool-risk-policy.cjs) denies a
6
+ * confirm-marked call in a job and records a PENDING confirmation here
7
+ * (one record per tool + args digest, listing every job that asked).
8
+ * 2. The owner answers the Needs-you item. The scheduler takes the pending
9
+ * record and calls answerConfirmation: it emits human.tool_confirmation,
10
+ * and on approve grants one clearance bound to (job, tool, args digest,
11
+ * project) and resumes the SAME Claude session; on deny it parks the job
12
+ * with reason confirmation_denied.
13
+ * 3. In the resumed run the guard calls consumeClearance for the exact call.
14
+ * A matching live clearance lets exactly ONE call through: consumption is
15
+ * an atomic rename, so a second use (or a racing hook) finds nothing. A
16
+ * call with different args has a different digest, so it never matches.
17
+ *
18
+ * State lives machine-level under schedulerHome() (not the operations root):
19
+ * tool-clearances/<key>.json live grants
20
+ * tool-confirmations-pending/<key>.json pending confirmation records
21
+ * Plain Node (no Electron) so the guard hook can require it.
22
+ */
23
+ 'use strict';
24
+
25
+ const crypto = require('node:crypto');
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const { writeJsonAtomicSync } = require('../util/atomicFs.cjs');
29
+
30
+ const CLEARANCES_DIR = 'tool-clearances';
31
+ const PENDING_DIR = 'tool-confirmations-pending';
32
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
33
+ const MAX_TTL_MS = 7 * DEFAULT_TTL_MS;
34
+ const DIGEST_RE = /^[0-9a-f]{64}$/;
35
+ const MAX_REQUESTS_PER_RECORD = 50;
36
+ const DENIED_REASON = 'confirmation_denied';
37
+ const NO_SESSION_REASON = 'confirmation_no_session';
38
+ const EVENT_KIND = 'human.tool_confirmation';
39
+
40
+ function home() {
41
+ return require('./schedulerPaths.cjs').schedulerHome();
42
+ }
43
+
44
+ function clearancesDir(dir) { return dir || path.join(home(), CLEARANCES_DIR); }
45
+ function pendingDir(dir) { return dir || path.join(home(), PENDING_DIR); }
46
+
47
+ function sha(parts) {
48
+ return crypto.createHash('sha256').update(parts.join('\u0000')).digest('hex');
49
+ }
50
+
51
+ /** File key of a clearance: one per (job, tool, args digest). */
52
+ function clearanceKey(jobSlug, tool, argsDigest) {
53
+ return sha(['clearance', jobSlug, tool, argsDigest]).slice(0, 48);
54
+ }
55
+
56
+ /** File key of a pending confirmation: one per (tool, args digest), like its Needs-you item. */
57
+ function confirmationKey(tool, argsDigest) {
58
+ return sha(['confirm', tool, argsDigest]).slice(0, 48);
59
+ }
60
+
61
+ function requireString(name, v) {
62
+ if (typeof v !== 'string' || !v) throw new Error(`toolClearance: ${name} must be a non-empty string`);
63
+ }
64
+
65
+ function requireDigest(v) {
66
+ if (typeof v !== 'string' || !DIGEST_RE.test(v)) throw new Error('toolClearance: argsDigest must be a sha256 hex digest');
67
+ }
68
+
69
+ function readJson(file) {
70
+ try {
71
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Grant one single-use clearance. A new grant for the same key replaces the old one.
79
+ * @param {{ cwd?: string|null, jobSlug: string, tool: string, argsDigest: string, ttlMs?: number, now?: number, dir?: string }} args
80
+ * @returns {{ key: string, file: string, grantedAt: number, expiresAt: number }}
81
+ */
82
+ function grantClearance({ cwd = null, jobSlug, tool, argsDigest, ttlMs = DEFAULT_TTL_MS, now = Date.now(), dir } = /** @type {any} */ ({})) {
83
+ requireString('jobSlug', jobSlug);
84
+ requireString('tool', tool);
85
+ requireDigest(argsDigest);
86
+ const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? Math.min(ttlMs, MAX_TTL_MS) : DEFAULT_TTL_MS;
87
+ const key = clearanceKey(jobSlug, tool, argsDigest);
88
+ const file = path.join(clearancesDir(dir), `${key}.json`);
89
+ const record = { key, cwd: typeof cwd === 'string' && cwd ? cwd : null, jobSlug, tool, argsDigest, grantedAt: now, expiresAt: now + ttl };
90
+ fs.mkdirSync(path.dirname(file), { recursive: true });
91
+ writeJsonAtomicSync(file, record);
92
+ return { key, file, grantedAt: record.grantedAt, expiresAt: record.expiresAt };
93
+ }
94
+
95
+ /**
96
+ * Consume the clearance for this exact call, at most once. Atomic: the grant
97
+ * is renamed aside before it is read, so only one caller can ever win it.
98
+ * A claimed grant is always deleted — expired or mismatched ones included.
99
+ * @param {{ cwd?: string|null, jobSlug: string, tool: string, argsDigest: string, now?: number, dir?: string }} args
100
+ * @returns {{ ok: true, clearance: object } | { ok: false, reason: 'none'|'expired'|'mismatch' }}
101
+ */
102
+ function consumeClearance({ cwd = null, jobSlug, tool, argsDigest, now = Date.now(), dir } = /** @type {any} */ ({})) {
103
+ if (typeof jobSlug !== 'string' || !jobSlug || typeof tool !== 'string' || !tool
104
+ || typeof argsDigest !== 'string' || !DIGEST_RE.test(argsDigest)) {
105
+ return { ok: false, reason: 'none' };
106
+ }
107
+ const file = path.join(clearancesDir(dir), `${clearanceKey(jobSlug, tool, argsDigest)}.json`);
108
+ const claimed = `${file}.consumed-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
109
+ try {
110
+ fs.renameSync(file, claimed);
111
+ } catch {
112
+ return { ok: false, reason: 'none' };
113
+ }
114
+ const record = readJson(claimed);
115
+ try { fs.rmSync(claimed, { force: true }); } catch { /* best effort */ }
116
+ if (!record || record.jobSlug !== jobSlug || record.tool !== tool || record.argsDigest !== argsDigest) {
117
+ return { ok: false, reason: 'mismatch' };
118
+ }
119
+ if (!(typeof record.expiresAt === 'number' && record.expiresAt > now)) return { ok: false, reason: 'expired' };
120
+ if (record.cwd && cwd && path.resolve(record.cwd) !== path.resolve(cwd)) return { ok: false, reason: 'mismatch' };
121
+ return { ok: true, clearance: record };
122
+ }
123
+
124
+ /**
125
+ * Delete every expired (or unreadable) grant. Never throws.
126
+ * @param {{ now?: number, dir?: string }} [opts]
127
+ * @returns {number} grants removed
128
+ */
129
+ function pruneExpired({ now = Date.now(), dir } = {}) {
130
+ let removed = 0;
131
+ let names = [];
132
+ try { names = fs.readdirSync(clearancesDir(dir)); } catch { return 0; }
133
+ for (const name of names) {
134
+ if (!name.endsWith('.json')) continue;
135
+ const file = path.join(clearancesDir(dir), name);
136
+ const rec = readJson(file);
137
+ if (rec && typeof rec.expiresAt === 'number' && rec.expiresAt > now) continue;
138
+ try { fs.rmSync(file, { force: true }); removed++; } catch { /* next */ }
139
+ }
140
+ return removed;
141
+ }
142
+
143
+ // ── pending confirmations ───────────────────────────────────────────────────
144
+
145
+ /**
146
+ * Record (or extend) the pending confirmation for one guard refusal. One
147
+ * record per (tool, digest); each job asks at most once in it. Never throws.
148
+ * @param {{ tool: string, argsDigest: string, jobSlug: string, sessionId?: string|null, epicId?: string|null, cwd?: string|null, rule?: string, summary?: string }} req
149
+ * @param {{ dir?: string, now?: number }} [opts]
150
+ * @returns {boolean}
151
+ */
152
+ function recordPendingConfirmation(req, { dir, now = Date.now() } = {}) {
153
+ try {
154
+ requireString('tool', req.tool);
155
+ requireDigest(req.argsDigest);
156
+ requireString('jobSlug', req.jobSlug);
157
+ const key = confirmationKey(req.tool, req.argsDigest);
158
+ const file = path.join(pendingDir(dir), `${key}.json`);
159
+ const existing = readJson(file);
160
+ const requests = existing && Array.isArray(existing.requests) ? existing.requests : [];
161
+ if (requests.some((r) => r && r.jobSlug === req.jobSlug)) return true;
162
+ if (requests.length >= MAX_REQUESTS_PER_RECORD) return false;
163
+ requests.push({
164
+ tool: req.tool,
165
+ argsDigest: req.argsDigest,
166
+ jobSlug: req.jobSlug,
167
+ sessionId: typeof req.sessionId === 'string' && req.sessionId ? req.sessionId : null,
168
+ epicId: typeof req.epicId === 'string' && req.epicId ? req.epicId : null,
169
+ cwd: typeof req.cwd === 'string' && req.cwd ? req.cwd : null,
170
+ ...(typeof req.rule === 'string' ? { rule: req.rule } : {}),
171
+ ...(typeof req.summary === 'string' ? { summary: req.summary } : {}),
172
+ requestedAt: now,
173
+ });
174
+ fs.mkdirSync(path.dirname(file), { recursive: true });
175
+ writeJsonAtomicSync(file, { key, tool: req.tool, argsDigest: req.argsDigest, requests });
176
+ return true;
177
+ } catch (e) {
178
+ console.error(`[toolClearance] pending confirmation not recorded: ${e && e.message}`);
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /** @returns {{ key: string, tool: string, argsDigest: string, requests: object[] }[]} */
184
+ function listPendingConfirmations({ dir } = {}) {
185
+ let names = [];
186
+ try { names = fs.readdirSync(pendingDir(dir)); } catch { return []; }
187
+ const out = [];
188
+ for (const name of names.sort()) {
189
+ if (!name.endsWith('.json')) continue;
190
+ const rec = readJson(path.join(pendingDir(dir), name));
191
+ if (rec && typeof rec.key === 'string' && Array.isArray(rec.requests)) out.push(rec);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /** Atomically take (remove and return) one pending record, or null when it is gone. */
197
+ function takePendingConfirmation(key, { dir } = {}) {
198
+ if (typeof key !== 'string' || !/^[0-9a-f]{1,64}$/.test(key)) return null;
199
+ const file = path.join(pendingDir(dir), `${key}.json`);
200
+ const claimed = `${file}.taken-${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
201
+ try { fs.renameSync(file, claimed); } catch { return null; }
202
+ const rec = readJson(claimed);
203
+ try { fs.rmSync(claimed, { force: true }); } catch { /* best effort */ }
204
+ return rec && Array.isArray(rec.requests) ? rec : null;
205
+ }
206
+
207
+ // ── answering ───────────────────────────────────────────────────────────────
208
+
209
+ /**
210
+ * Apply the owner's answer to one job's confirmation request.
211
+ * approve → emit human.tool_confirmation { approved: true }, grant the
212
+ * clearance, resume({ jobSlug, sessionId, request }) — same session.
213
+ * deny → emit human.tool_confirmation { approved: false },
214
+ * park({ jobSlug, reason: 'confirmation_denied', request }).
215
+ * An approval with no session id to resume parks with 'confirmation_no_session'.
216
+ * @param {{ request: any, approved: boolean, ttlMs?: number, now?: number, dir?: string }} answer
217
+ * @param {{ emit: (e: object) => void, resume: (r: object) => void, park: (p: object) => void }} deps
218
+ * @returns {{ action: 'resume'|'park', clearance?: object }}
219
+ */
220
+ function answerConfirmation({ request, approved, ttlMs, now = Date.now(), dir }, deps) {
221
+ requireString('jobSlug', request && request.jobSlug);
222
+ const event = {
223
+ kind: EVENT_KIND,
224
+ approved: approved === true,
225
+ tool: request.tool,
226
+ argsDigest: request.argsDigest,
227
+ jobSlug: request.jobSlug,
228
+ ...(request.rule ? { rule: request.rule } : {}),
229
+ };
230
+ try { deps.emit(event); } catch (e) { console.error(`[toolClearance] event emit failed: ${e && e.message}`); }
231
+ if (approved === true && request.sessionId) {
232
+ const clearance = grantClearance({
233
+ cwd: request.cwd, jobSlug: request.jobSlug, tool: request.tool, argsDigest: request.argsDigest, ttlMs, now, dir,
234
+ });
235
+ deps.resume({ jobSlug: request.jobSlug, sessionId: request.sessionId, request });
236
+ return { action: 'resume', clearance };
237
+ }
238
+ deps.park({ jobSlug: request.jobSlug, reason: approved === true ? NO_SESSION_REASON : DENIED_REASON, request });
239
+ return { action: 'park' };
240
+ }
241
+
242
+ module.exports = {
243
+ CLEARANCES_DIR,
244
+ PENDING_DIR,
245
+ DEFAULT_TTL_MS,
246
+ DENIED_REASON,
247
+ NO_SESSION_REASON,
248
+ EVENT_KIND,
249
+ clearanceKey,
250
+ confirmationKey,
251
+ grantClearance,
252
+ consumeClearance,
253
+ pruneExpired,
254
+ recordPendingConfirmation,
255
+ listPendingConfirmations,
256
+ takePendingConfirmation,
257
+ answerConfirmation,
258
+ };