claude-code-session-manager 0.141.0 → 0.143.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -6,6 +6,11 @@
6
6
  * over needsYouStore.cjs:
7
7
  * needsYou:list (no payload) -> { ok: true, items } (open items only)
8
8
  * needsYou:answer { app, id, answer } -> { ok: true, item } | { ok: false, error }
9
+ * scheduler:confirm-tool { tool, argsDigest, approved }
10
+ * -> { ok: true, item } | { ok: false, error }
11
+ * answers the tool-risk confirmation item for (tool, argsDigest) with
12
+ * Approve / Deny; the scheduler's next tick applies it to the asking jobs
13
+ * via toolClearance.answerConfirmation (resume the same session, or park).
9
14
  *
10
15
  * A successful answer appends one `needs_you_answered` audit row (app, id,
11
16
  * answer, and the item's externalRef when it has one) so the outside app that
@@ -45,6 +50,18 @@ function registerNeedsYouIpc(deps = {}) {
45
50
  if (onChanged) onChanged();
46
51
  return { ok: true, item };
47
52
  }));
53
+
54
+ ipcMain.handle('scheduler:confirm-tool', v(s.schedulerConfirmTool, async ({ tool, argsDigest, approved }) => {
55
+ const id = needsYouStore.confirmationItemId(tool, argsDigest);
56
+ const answer = approved ? 'Approve' : 'Deny';
57
+ const item = await needsYouStore.answerNeedsYou({ app: needsYouStore.CONFIRM_APP, id, answer });
58
+ if (!item) {
59
+ return { ok: false, error: `There is no open confirmation for ${tool} with that argument digest. It may already be answered.` };
60
+ }
61
+ appendAuditEvent('needs_you_answered', { app: item.app, id: item.id, answer: item.answer, tool, argsDigest });
62
+ if (onChanged) onChanged();
63
+ return { ok: true, item };
64
+ }));
48
65
  }
49
66
 
50
67
  module.exports = { registerNeedsYouIpc };
@@ -10,9 +10,14 @@
10
10
  * A missing or corrupt file reads as empty; a corrupt file is set aside as
11
11
  * `needs-you.json.corrupt-<ms>` at the next write. Answered or withdrawn items
12
12
  * older than 14 days are dropped at the next write.
13
+ *
14
+ * Also posts tool-risk 'confirm' requests (app 'tool-risk'): the guard hook
15
+ * appends them to a JSONL and drainConfirmationRequests turns each into one
16
+ * item + one job.confirmation_requested Epic event, deduped by tool + digest.
13
17
  */
14
18
 
15
19
  const fsp = require('node:fs/promises');
20
+ const path = require('node:path');
16
21
  const { z } = require('zod');
17
22
  const { writeJsonAtomic } = require('../util/atomicFs.cjs');
18
23
  const { needsYouPath } = require('../scheduler/schedulerPaths.cjs');
@@ -49,6 +54,11 @@ function refSchema(label, required) {
49
54
  const TitleSchema = z.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), 'title must be one line');
50
55
  const WhySchema = z.string().max(1000);
51
56
  const LinkSchema = z.string().max(2000).regex(/^https?:\/\//, 'link must start with http:// or https://');
57
+ // Optional Epic link: an item posted with both epicId and cwd (the Epic's
58
+ // project root) also lands on that Epic's event log (job.needs_input on create,
59
+ // human.answer on answer). Stored only when given, so unlinked items keep their shape.
60
+ const EpicIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/, 'epicId must be a safe Epic id');
61
+ const CwdSchema = z.string().min(1).max(4096).refine((s) => path.isAbsolute(s), 'cwd must be an absolute path');
52
62
  const OptionsSchema = z.array(z.string().min(1).max(80)).min(2).max(5)
53
63
  .refine((opts) => new Set(opts).size === opts.length, 'options must be distinct');
54
64
 
@@ -60,6 +70,8 @@ const NeedsYouPostSchema = z.object({
60
70
  link: LinkSchema.optional(),
61
71
  options: OptionsSchema.optional(),
62
72
  externalRef: refSchema('externalRef', false),
73
+ epicId: EpicIdSchema.optional(),
74
+ cwd: CwdSchema.optional(),
63
75
  });
64
76
 
65
77
  const KeySchema = z.object({ app: AppSchema, id: refSchema('id', true) });
@@ -77,6 +89,8 @@ const StoredItemSchema = z.object({
77
89
  createdAt: z.string(),
78
90
  updatedAt: z.string(),
79
91
  answeredAt: z.string().nullable(),
92
+ epicId: EpicIdSchema.optional(),
93
+ cwd: CwdSchema.optional(),
80
94
  });
81
95
 
82
96
  /** @typedef {z.infer<typeof StoredItemSchema>} NeedsYouItem */
@@ -152,6 +166,22 @@ async function writeStore(filePath, items) {
152
166
  await writeJsonAtomic(filePath, { version: STORE_VERSION, items: prune(items, Date.now()) });
153
167
  }
154
168
 
169
+ /**
170
+ * Append one event for an item linked to an Epic (epicId + cwd). Never throws:
171
+ * an append failure is logged so the store write it follows still succeeds.
172
+ * @param {NeedsYouItem} item
173
+ * @param {Record<string, unknown>} event
174
+ */
175
+ async function emitItemEvent(item, event) {
176
+ if (!item || !item.epicId || !item.cwd) return;
177
+ try {
178
+ const { appendEpicEvent } = require('../epic/epicEventLog.cjs');
179
+ await appendEpicEvent(item.cwd, item.epicId, event);
180
+ } catch (err) {
181
+ console.error('[needsYouStore] event append failed', item.epicId, event.kind, err && err.message ? err.message : err);
182
+ }
183
+ }
184
+
155
185
  function limitError(message) {
156
186
  const err = /** @type {Error & { code: string }} */ (new Error(message));
157
187
  err.code = 'NEEDS_YOU_LIMIT';
@@ -185,9 +215,20 @@ function callerKey(item) {
185
215
  * @returns {Promise<{ item: NeedsYouItem, created: boolean, changed: boolean }>}
186
216
  */
187
217
  async function postNeedsYou(input) {
218
+ return postItem(input, (item) => ({
219
+ kind: 'job.needs_input',
220
+ app: item.app,
221
+ id: item.id,
222
+ title: item.title,
223
+ ...(item.options ? { options: item.options } : {}),
224
+ }));
225
+ }
226
+
227
+ /** postNeedsYou with the Epic event a NEW item appends built by `createdEvent`. */
228
+ async function postItem(input, createdEvent) {
188
229
  const data = NeedsYouPostSchema.parse(input);
189
230
  const filePath = needsYouPath();
190
- return serialize(async () => {
231
+ const result = await serialize(async () => {
191
232
  const items = await loadForWrite(filePath);
192
233
  const now = new Date().toISOString();
193
234
  const existing = items.find((it) => it.app === data.app && it.id === data.id);
@@ -225,11 +266,133 @@ async function postNeedsYou(input) {
225
266
  createdAt: now,
226
267
  updatedAt: now,
227
268
  answeredAt: null,
269
+ ...(data.epicId && data.cwd ? { epicId: data.epicId, cwd: data.cwd } : {}),
228
270
  };
229
271
  items.push(item);
230
272
  await writeStore(filePath, items);
231
273
  return { item, created: true, changed: true };
232
274
  });
275
+ if (result.created) await emitItemEvent(result.item, createdEvent(result.item));
276
+ return result;
277
+ }
278
+
279
+ // --- tool-risk confirmation requests -------------------------------------------
280
+
281
+ const CONFIRM_APP = 'tool-risk';
282
+ const DIGEST_RE = /^[0-9a-f]{64}$/;
283
+ const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
284
+
285
+ /**
286
+ * One request line written by scripts/hooks/lib/guard-tool-risk-policy.cjs.
287
+ * epicId / cwd are optional: without both, the item is posted unlinked.
288
+ */
289
+ const ConfirmationRequestSchema = z.object({
290
+ tool: z.string().min(1).max(300),
291
+ argsDigest: z.string().regex(DIGEST_RE, 'argsDigest must be a sha256 hex digest'),
292
+ jobSlug: z.string().min(1).max(300).nullable().optional(),
293
+ epicId: z.string().nullable().optional(),
294
+ cwd: z.string().nullable().optional(),
295
+ rule: z.string().max(500).optional(),
296
+ summary: z.string().max(500).optional(),
297
+ });
298
+
299
+ /**
300
+ * Needs-you id of a request: one item per (tool, argsDigest). The digest alone
301
+ * is not enough — every argument-less MCP call shares the digest of `{}`.
302
+ */
303
+ function confirmationItemId(tool, digest) {
304
+ const key = require('node:crypto').createHash('sha256').update(`${tool}\u0000${digest}`).digest('hex');
305
+ return `confirm-${key.slice(0, 40)}`;
306
+ }
307
+
308
+ function oneLine(s, max) {
309
+ const t = String(s).replace(/\s+/g, ' ').trim();
310
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
311
+ }
312
+
313
+ /**
314
+ * Post one confirmation request: one Needs-you item, and — only when the item
315
+ * is new — one job.confirmation_requested event on the Epic's log. A repeat
316
+ * request for the same tool + args digest (from any job) changes nothing.
317
+ * @param {unknown} input
318
+ * @returns {Promise<{ item: NeedsYouItem, created: boolean, changed: boolean }>}
319
+ */
320
+ async function postConfirmationRequest(input) {
321
+ const req = ConfirmationRequestSchema.parse(input);
322
+ const id = confirmationItemId(req.tool, req.argsDigest);
323
+ const linked = typeof req.epicId === 'string' && SAFE_ID_RE.test(req.epicId)
324
+ && typeof req.cwd === 'string' && path.isAbsolute(req.cwd);
325
+ const what = req.summary && req.summary !== req.tool ? `${req.tool}: ${req.summary}` : req.tool;
326
+ const why = [
327
+ `A headless job${req.jobSlug ? ` (${req.jobSlug})` : ''} tried \`${oneLine(what, 400)}\`, which is marked 'confirm'${req.rule ? ` by rule \`${req.rule}\`` : ''}, and was refused.`,
328
+ `Args digest: ${req.argsDigest}.`,
329
+ 'Approve resumes that same job session and lets this exact call (same arguments) run once; Deny keeps the job parked (confirmation_denied).',
330
+ ].join(' ');
331
+ const existing = (await listNeedsYou({ app: CONFIRM_APP })).find((it) => it.id === id);
332
+ if (existing) return { item: existing, created: false, changed: false };
333
+ return postItem({
334
+ app: CONFIRM_APP,
335
+ id,
336
+ title: oneLine(`Confirm ${what}`, 200),
337
+ why: why.slice(0, 1000),
338
+ options: ['Approve', 'Deny'],
339
+ ...(linked ? { epicId: req.epicId, cwd: req.cwd } : {}),
340
+ }, (item) => ({
341
+ kind: 'job.confirmation_requested',
342
+ app: item.app,
343
+ id: item.id,
344
+ tool: req.tool,
345
+ argsDigest: req.argsDigest,
346
+ ...(req.jobSlug ? { jobSlug: req.jobSlug } : {}),
347
+ ...(req.rule ? { rule: req.rule } : {}),
348
+ }));
349
+ }
350
+
351
+ /**
352
+ * Drain the guard's confirmation-requests JSONL: the file is renamed aside
353
+ * first (so a guard appending meanwhile starts a fresh file), every valid line
354
+ * is posted via postConfirmationRequest, and the drained copy is removed.
355
+ * A missing file is a no-op. Never throws; a bad line or a failed post is logged.
356
+ * @param {{ file?: string }} [opts] default: schedulerHome()/tool-confirmation-requests.jsonl
357
+ * @returns {Promise<{ read: number, posted: number, created: number }>}
358
+ */
359
+ async function drainConfirmationRequests(opts = {}) {
360
+ const out = { read: 0, posted: 0, created: 0 };
361
+ let file;
362
+ try {
363
+ const { confirmationRequestsPath } = require('../claude/toolRiskMarks.cjs');
364
+ file = opts.file || confirmationRequestsPath(require('../scheduler/schedulerPaths.cjs').schedulerHome());
365
+ } catch (err) {
366
+ console.error('[needsYouStore] confirmation requests path unavailable', err && err.message);
367
+ return out;
368
+ }
369
+ const draining = `${file}.draining-${process.pid}-${Date.now()}`;
370
+ try {
371
+ await fsp.rename(file, draining);
372
+ } catch (err) {
373
+ if (!err || err.code !== 'ENOENT') console.error('[needsYouStore] cannot drain', file, err && err.message);
374
+ return out;
375
+ }
376
+ let text = '';
377
+ try {
378
+ text = await fsp.readFile(draining, 'utf8');
379
+ } catch (err) {
380
+ console.error('[needsYouStore] cannot read', draining, err && err.message);
381
+ return out;
382
+ }
383
+ for (const line of text.split('\n')) {
384
+ if (!line.trim()) continue;
385
+ out.read++;
386
+ try {
387
+ const r = await postConfirmationRequest(JSON.parse(line));
388
+ out.posted++;
389
+ if (r.created) out.created++;
390
+ } catch (err) {
391
+ console.error('[needsYouStore] confirmation request dropped:', err && err.message ? err.message : err);
392
+ }
393
+ }
394
+ await fsp.rm(draining, { force: true }).catch(() => {});
395
+ return out;
233
396
  }
234
397
 
235
398
  /** Apply `mutate` to the open item app+id; returns it, or null when none / mutate refuses. */
@@ -264,13 +427,17 @@ async function withdrawNeedsYou({ app, id }) {
264
427
  * @returns {Promise<NeedsYouItem | null>}
265
428
  */
266
429
  async function answerNeedsYou({ app, id, answer }) {
267
- return updateOpen(app, id, (item, now) => {
268
- if (!item.options || typeof answer !== 'string' || !item.options.includes(answer)) return false;
269
- item.status = 'answered';
270
- item.answer = answer;
271
- item.answeredAt = now;
430
+ const item = await updateOpen(app, id, (it, now) => {
431
+ if (!it.options || typeof answer !== 'string' || !it.options.includes(answer)) return false;
432
+ it.status = 'answered';
433
+ it.answer = answer;
434
+ it.answeredAt = now;
272
435
  return true;
273
436
  });
437
+ if (item) {
438
+ await emitItemEvent(item, { kind: 'human.answer', app: item.app, id: item.id, answer: item.answer });
439
+ }
440
+ return item;
274
441
  }
275
442
 
276
443
  module.exports = {
@@ -279,6 +446,10 @@ module.exports = {
279
446
  postNeedsYou,
280
447
  withdrawNeedsYou,
281
448
  answerNeedsYou,
449
+ postConfirmationRequest,
450
+ drainConfirmationRequests,
451
+ confirmationItemId,
452
+ CONFIRM_APP,
282
453
  MAX_OPEN_PER_APP,
283
454
  MAX_OPEN_TOTAL,
284
455
  RETENTION_MS,
@@ -0,0 +1,207 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * pendingReplies.cjs — machine-wide ledger of cross-project replies that are
5
+ * OWED but not yet sendable: an "it's live" reply must wait until Session
6
+ * Manager runs a version above the one the fix landed after, and the Epic
7
+ * that owes it is often closed by then, so without a ledger the reply is
8
+ * never sent (six were lost on 11-22/23).
9
+ *
10
+ * File: schedulerHome()/pending-replies.json (the folder that holds
11
+ * admin-api.json; honors SM_SCHEDULER_HOME) = { version: 1, entries }.
12
+ * An entry is due once appVersionAbove < running appVersion (strictly, via
13
+ * seedDevPlugin.cjs compareSemver — an equal version is not due).
14
+ * An entry with `commits` (release.commits) is further gated by the
15
+ * deliverer on tag v<running version> containing every commit.
16
+ * A missing or unreadable file reads as empty. Writes go through
17
+ * util/atomicFs.cjs.
18
+ *
19
+ * Single writer: crossProjectReply.cjs is the ONLY caller of addPendingReply
20
+ * and markReplyDelivered; everything else reads.
21
+ */
22
+
23
+ const crypto = require('node:crypto');
24
+ const path = require('node:path');
25
+ const { writeJsonAtomicSync, readJsonOrSync } = require('../util/atomicFs.cjs');
26
+ const { schedulerHome } = require('../scheduler/schedulerPaths.cjs');
27
+
28
+ const STORE_VERSION = 1;
29
+ const FILE_NAME = 'pending-replies.json';
30
+ const SEMVER_RE = /^\d+\.\d+\.\d+$/;
31
+ const COMMIT_RE = /^[0-9a-f]{7,40}$/;
32
+ /** Failed delivery attempts (one per hourly pass) before an entry gives up for good. */
33
+ const MAX_DELIVERY_ATTEMPTS = 24;
34
+
35
+ /** seedDevPlugin.cjs pulls electron-side modules; load its comparator only when needed. */
36
+ function compareSemver(a, b) {
37
+ return require('../../seedDevPlugin.cjs').compareSemver(a, b);
38
+ }
39
+
40
+ function ledgerPath() {
41
+ return path.join(schedulerHome(), FILE_NAME);
42
+ }
43
+
44
+ /** @returns {any[]} entries; [] for a missing/corrupt/ill-shaped file. */
45
+ function readEntries() {
46
+ const doc = readJsonOrSync(ledgerPath(), null);
47
+ if (!doc || typeof doc !== 'object' || !Array.isArray(doc.entries)) return [];
48
+ return doc.entries.filter((e) => e && typeof e === 'object' && typeof e.id === 'string');
49
+ }
50
+
51
+ function writeEntries(entries) {
52
+ writeJsonAtomicSync(ledgerPath(), { version: STORE_VERSION, entries });
53
+ }
54
+
55
+ function isSemver(v) {
56
+ return typeof v === 'string' && SEMVER_RE.test(v);
57
+ }
58
+
59
+ function str(v) {
60
+ return typeof v === 'string' ? v : null;
61
+ }
62
+
63
+ function normalizeThread(t) {
64
+ const o = t && typeof t === 'object' ? t : {};
65
+ return {
66
+ cwd: str(o.cwd),
67
+ epicId: str(o.epicId),
68
+ claudeSessionId: str(o.claudeSessionId),
69
+ legacy: o.legacy === true,
70
+ mode: str(o.mode),
71
+ };
72
+ }
73
+
74
+ function isPlainObject(v) {
75
+ return !!v && typeof v === 'object' && !Array.isArray(v)
76
+ && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
77
+ }
78
+
79
+ /** A JSON-safe copy of the scheduling Epic's source (externalRef, proposal, replyTo, ...); null if not a plain object. */
80
+ function normalizeYSource(v) {
81
+ if (!isPlainObject(v)) return null;
82
+ try { return JSON.parse(JSON.stringify(v)); } catch { return null; }
83
+ }
84
+
85
+ /** Lowercased, de-duplicated commit hashes (7-40 hex); [] when none are valid. */
86
+ function normalizeCommits(v) {
87
+ if (!Array.isArray(v)) return [];
88
+ const out = [];
89
+ for (const c of v) {
90
+ if (typeof c !== 'string') continue;
91
+ const lc = c.toLowerCase();
92
+ if (COMMIT_RE.test(lc) && !out.includes(lc)) out.push(lc);
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /** Pure: build a full ledger entry from caller input. Throws on a bad appVersionAbove. */
98
+ function buildEntry(input, now = new Date()) {
99
+ const e = input && typeof input === 'object' ? input : {};
100
+ if (!isSemver(e.appVersionAbove)) {
101
+ throw new Error(`pendingReplies: appVersionAbove must be x.y.z, got ${JSON.stringify(e.appVersionAbove)}`);
102
+ }
103
+ // release.commits the reply claims: delivery waits until tag v<running> holds every one.
104
+ const commits = normalizeCommits(e.commits);
105
+ return {
106
+ id: crypto.randomUUID(),
107
+ createdAt: now.toISOString(),
108
+ replierCwd: str(e.replierCwd),
109
+ yId: str(e.yId),
110
+ goalText: str(e.goalText),
111
+ thread: normalizeThread(e.thread),
112
+ targetCwd: str(e.targetCwd),
113
+ outcome: str(e.outcome),
114
+ message: str(e.message),
115
+ referencePaths: Array.isArray(e.referencePaths) ? e.referencePaths.filter((p) => typeof p === 'string') : [],
116
+ appVersionAbove: e.appVersionAbove,
117
+ ...(commits.length ? { commits } : {}),
118
+ // What delivery needs once the scheduling Epic has closed: its source
119
+ // (externalRef / proposal / replyTo) and the cap count this reply took.
120
+ ySource: normalizeYSource(e.ySource),
121
+ sentAtScheduling: Number.isInteger(e.sentAtScheduling) && e.sentAtScheduling > 0 ? e.sentAtScheduling : null,
122
+ // replyHash(outcome, message) — an identical scheduled retry matches it.
123
+ hash: str(e.hash),
124
+ attempts: 0,
125
+ gaveUpAt: null,
126
+ deliveredAt: null,
127
+ deliveredVersion: null,
128
+ lastError: null,
129
+ };
130
+ }
131
+
132
+ /** Pure: undelivered, not-given-up entries whose appVersionAbove is strictly below appVersion. */
133
+ function selectDue(entries, appVersion) {
134
+ if (!isSemver(String(appVersion ?? '').split('-')[0])) return [];
135
+ return entries.filter((e) => !e.deliveredAt && !e.gaveUpAt && isSemver(e.appVersionAbove)
136
+ && compareSemver(e.appVersionAbove, appVersion) < 0);
137
+ }
138
+
139
+ function addPendingReply(entry) {
140
+ const built = buildEntry(entry);
141
+ const entries = readEntries();
142
+ entries.push(built);
143
+ writeEntries(entries);
144
+ return built;
145
+ }
146
+
147
+ function listDueReplies(appVersion) {
148
+ return selectDue(readEntries(), appVersion);
149
+ }
150
+
151
+ /** Pure: true for an undelivered, not-given-up entry of the thread (replierCwd + yId). */
152
+ function isPendingForThread(e, replierCwd, yId) {
153
+ return !e.deliveredAt && !e.gaveUpAt && e.replierCwd === replierCwd && e.yId === yId;
154
+ }
155
+
156
+ /** How many of the thread's reply slots are held — a given-up entry frees its slot. */
157
+ function countPendingForThread(replierCwd, yId) {
158
+ return listPendingForThread(replierCwd, yId).length;
159
+ }
160
+
161
+ /** Undelivered, not-given-up entries one thread (replierCwd + yId) still holds. */
162
+ function listPendingForThread(replierCwd, yId) {
163
+ return readEntries().filter((e) => isPendingForThread(e, replierCwd, yId));
164
+ }
165
+
166
+ /**
167
+ * Record a delivery attempt. result.ok !== false = delivered (deliveredAt +
168
+ * deliveredVersion stamped, lastError cleared); otherwise lastError is set and
169
+ * attempts is incremented; the MAX_DELIVERY_ATTEMPTS-th failure stamps
170
+ * gaveUpAt and the entry is never due again. Returns the updated entry, or null for an unknown id.
171
+ */
172
+ function failedAttempt(prev, lastError) {
173
+ const attempts = (Number.isInteger(prev.attempts) && prev.attempts > 0 ? prev.attempts : 0) + 1;
174
+ return {
175
+ ...prev,
176
+ attempts,
177
+ lastError,
178
+ gaveUpAt: attempts >= MAX_DELIVERY_ATTEMPTS ? new Date().toISOString() : (prev.gaveUpAt || null),
179
+ };
180
+ }
181
+
182
+ function markReplyDelivered(id, { version, result } = {}) {
183
+ const entries = readEntries();
184
+ const idx = entries.findIndex((e) => e.id === id);
185
+ if (idx < 0) return null;
186
+ const ok = !(result && typeof result === 'object' && result.ok === false);
187
+ const prev = entries[idx];
188
+ const next = ok
189
+ ? { ...prev, deliveredAt: new Date().toISOString(), deliveredVersion: str(version), lastError: null }
190
+ : failedAttempt(prev, str(result.error) || str(result.reason) || 'delivery failed');
191
+ entries[idx] = next;
192
+ writeEntries(entries);
193
+ return next;
194
+ }
195
+
196
+ module.exports = {
197
+ addPendingReply,
198
+ listDueReplies,
199
+ countPendingForThread,
200
+ listPendingForThread,
201
+ markReplyDelivered,
202
+ MAX_DELIVERY_ATTEMPTS,
203
+ ledgerPath,
204
+ buildEntry,
205
+ selectDue,
206
+ STORE_VERSION,
207
+ };