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,175 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * voiceAdminRoutes.cjs — the voice library's READ routes for agents (MCP
5
+ * voice_list / voice_preview). Neither route can change a voice: approving,
6
+ * unapproving and deleting stay renderer-IPC only (voicesIpc.cjs).
7
+ *
8
+ * GET /admin/voices?cwd=<abs> -> {ok, voices, errors} (voiceLibrary.listVoices)
9
+ * POST /admin/voices/preview {cwd, voiceId, text}
10
+ * -> {ok:true, status:'ready', cached, wavPath, wallMs, audioSeconds}
11
+ * when previewVoice finishes within WAIT_MS (60 s), else
12
+ * -> {ok:true, status:'queued', lane, position}
13
+ * while the run keeps going in-process. A repeat call with the same
14
+ * (project, voiceId, text) joins that run, or — once it finished —
15
+ * previewVoice answers from its clip cache.
16
+ *
17
+ * cwd goes through projectHomeAdminRoutes.resolveCwd (the shared project-root
18
+ * resolver + allowed-roots check); voiceId must match VOICE_ID_RE and text be
19
+ * 1-TEXT_MAX chars after trimming; bad input answers 400.
20
+ *
21
+ * deps (tests): { resolveCwd, voiceLibrary, voiceLane, previewVoice, waitMs, now }.
22
+ */
23
+
24
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
25
+ const { wavSeconds } = require('../demo-video-kit/character.cjs');
26
+
27
+ const { VOICE_ID_RE } = require('../demo-video-kit/voiceLibrary.cjs');
28
+ const TEXT_MAX = 300;
29
+ const WAIT_MS = 60 * 1000;
30
+ const BODY_MAX = 64 * 1024;
31
+
32
+ /** key -> {promise, startedAt} for previews still running in-process. */
33
+ const pending = new Map();
34
+
35
+ function depsOf(deps) {
36
+ return {
37
+ resolveCwd: deps.resolveCwd || require('../feedback-remote/projectHomeAdminRoutes.cjs').resolveCwd,
38
+ voiceLibrary: deps.voiceLibrary || require('../demo-video-kit/voiceLibrary.cjs'),
39
+ voiceLane: deps.voiceLane || require('../demo-video-kit/voiceLane.cjs'),
40
+ previewVoice: deps.previewVoice || require('./voicePreview.cjs').previewVoice,
41
+ waitMs: Number.isFinite(deps.waitMs) && deps.waitMs >= 0 ? deps.waitMs : WAIT_MS,
42
+ now: deps.now || Date.now,
43
+ };
44
+ }
45
+
46
+ /** Seconds of audio in the clip at wavPath (character.cjs wavSeconds, 3 dp), else null. */
47
+ function clipSeconds(wavPath) {
48
+ if (!wavPath) return null;
49
+ const s = wavSeconds(wavPath);
50
+ return s > 0 ? Math.round(s * 1000) / 1000 : null;
51
+ }
52
+
53
+ /** -> null when the preview body is acceptable, else the 400 reason. */
54
+ function validatePreviewBody(body) {
55
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return 'invalid payload';
56
+ if (typeof body.voiceId !== 'string' || !VOICE_ID_RE.test(body.voiceId)) {
57
+ return `voiceId must match /${VOICE_ID_RE.source}/`;
58
+ }
59
+ const t = typeof body.text === 'string' ? body.text.trim() : '';
60
+ if (t.length < 1 || t.length > TEXT_MAX) return `text must be 1-${TEXT_MAX} chars`;
61
+ return null;
62
+ }
63
+
64
+ /** This preview's place in the voice lane: {lane, position} or {lane:null, position:null}. */
65
+ function lanePositionOf(d, root, voiceId) {
66
+ let snapshot = {};
67
+ try { snapshot = d.voiceLane.laneSnapshot() || {}; } catch { snapshot = {}; }
68
+ for (const [lane, tickets] of Object.entries(snapshot)) {
69
+ for (const t of Array.isArray(tickets) ? tickets : []) {
70
+ if (!t || t.voiceId !== voiceId) continue;
71
+ if (t.projectRoot && t.projectRoot !== root) continue;
72
+ return { lane, position: Number.isFinite(t.position) ? t.position : null };
73
+ }
74
+ }
75
+ return { lane: null, position: null };
76
+ }
77
+
78
+ function listHandler(deps) {
79
+ return async (_req, res, query) => {
80
+ const d = depsOf(deps);
81
+ const resolved = d.resolveCwd(query?.get('cwd') ?? '');
82
+ if (!resolved.ok) {
83
+ sendJson(res, resolved.status || 400, { ok: false, error: resolved.error });
84
+ return;
85
+ }
86
+ const { voices, errors } = d.voiceLibrary.listVoices(resolved.cwd);
87
+ sendJson(res, 200, { ok: true, voices, errors });
88
+ };
89
+ }
90
+
91
+ function previewHandler(deps) {
92
+ return async (req, res) => {
93
+ const d = depsOf(deps);
94
+ let raw;
95
+ try {
96
+ raw = await readBody(req, BODY_MAX);
97
+ } catch (e) {
98
+ sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'}` });
99
+ return;
100
+ }
101
+ let body;
102
+ try {
103
+ body = raw ? JSON.parse(raw) : {};
104
+ } catch {
105
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
106
+ return;
107
+ }
108
+ const invalid = validatePreviewBody(body);
109
+ if (invalid) {
110
+ sendJson(res, 400, { ok: false, error: invalid });
111
+ return;
112
+ }
113
+ const resolved = d.resolveCwd(body.cwd);
114
+ if (!resolved.ok) {
115
+ sendJson(res, resolved.status || 400, { ok: false, error: resolved.error });
116
+ return;
117
+ }
118
+ const root = resolved.cwd;
119
+ const voiceId = body.voiceId;
120
+ const text = body.text.trim();
121
+ const rv = d.voiceLibrary.resolveVoiceId(root, voiceId);
122
+ if (!rv || !rv.ok) {
123
+ sendJson(res, 400, { ok: false, error: (rv && rv.error) || `unknown voice '${voiceId}'` });
124
+ return;
125
+ }
126
+
127
+ const key = JSON.stringify([root, voiceId, text]);
128
+ let run = pending.get(key);
129
+ if (!run) {
130
+ const startedAt = d.now();
131
+ const promise = Promise.resolve()
132
+ .then(() => d.previewVoice({ projectRoot: root, voiceId, text }))
133
+ .catch((e) => ({ ok: false, error: `voice preview failed: ${e?.message ?? String(e)}` }))
134
+ .then((r) => ({ r, endedAt: d.now() }))
135
+ .finally(() => { if (pending.get(key) === run) pending.delete(key); });
136
+ run = { promise, startedAt };
137
+ pending.set(key, run);
138
+ }
139
+
140
+ let timer = null;
141
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), d.waitMs); });
142
+ const outcome = await Promise.race([run.promise, timeout]);
143
+ clearTimeout(timer);
144
+
145
+ if (!outcome) {
146
+ sendJson(res, 200, { ok: true, status: 'queued', ...lanePositionOf(d, root, voiceId) });
147
+ return;
148
+ }
149
+ const { r, endedAt } = outcome;
150
+ if (!r || r.ok !== true) {
151
+ sendJson(res, 500, { ok: false, error: (r && r.error) || 'voice preview failed' });
152
+ return;
153
+ }
154
+ sendJson(res, 200, {
155
+ ok: true,
156
+ status: 'ready',
157
+ cached: !!r.cached,
158
+ wavPath: r.wavPath,
159
+ wallMs: Math.max(0, endedAt - run.startedAt),
160
+ audioSeconds: clipSeconds(r.wavPath),
161
+ });
162
+ };
163
+ }
164
+
165
+ function registerAdminRoute(adminHttp, deps = {}) {
166
+ adminHttp.registerRoute('GET', '/admin/voices', listHandler(deps));
167
+ adminHttp.registerRoute('POST', '/admin/voices/preview', previewHandler(deps));
168
+ }
169
+
170
+ /** Tests only: forget previews still tracked in-process. */
171
+ function _resetPending() {
172
+ pending.clear();
173
+ }
174
+
175
+ module.exports = { registerAdminRoute, validatePreviewBody, VOICE_ID_RE, TEXT_MAX, WAIT_MS, _resetPending };
@@ -0,0 +1,196 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * voicePreview.cjs — the one preview path for a library voice (the Voices
5
+ * screen and the MCP preview tool both call previewVoice).
6
+ *
7
+ * A clip is cached at <voicesHome>/cache/<previewKey>.wav, where previewKey is
8
+ * the sha256 of voice id + trimmed text + canonical resolved voice JSON + the
9
+ * approval pin (voiceLibrary.pinOf) — editing a voice's params or pin files
10
+ * changes the key, so a stale clip is never served. A hit answers without
11
+ * spawning anything.
12
+ *
13
+ * A miss runs the kit speak CLI (demo-video-kit/character.cjs speak <spec>)
14
+ * as an ASYNC child (process.execPath + ELECTRON_RUN_AS_NODE=1, no shell), so
15
+ * the main process never blocks and the preview waits in the same voice lane
16
+ * as video runs. Exit 75 = still speaking: the same command is re-run until it
17
+ * finishes or timeoutMs passes. Concurrent calls for one key share one run.
18
+ * The cache keeps at most CACHE_MAX clips (oldest mtime removed).
19
+ * Plain Node: no Electron import.
20
+ */
21
+
22
+ const fs = require('node:fs');
23
+ const os = require('node:os');
24
+ const path = require('node:path');
25
+ const crypto = require('node:crypto');
26
+ const childProcess = require('node:child_process');
27
+ const voiceLibrary = require('../demo-video-kit/voiceLibrary.cjs');
28
+ const { cleanChildEnv } = require('../process/cleanEnv.cjs');
29
+
30
+ const CHARACTER_CJS = path.join(__dirname, '..', 'demo-video-kit', 'character.cjs');
31
+ const TEXT_MAX = 300;
32
+ const CACHE_MAX = 200;
33
+ const DEFAULT_TIMEOUT_MS = 20 * 60 * 1000;
34
+ const EXIT_PENDING = 75;
35
+ const RETRY_DELAY_MS = 200;
36
+ const OUTPUT_TAIL = 4000;
37
+
38
+ /** @type {Map<string, Promise<any>>} key -> in-flight preview */
39
+ const inFlight = new Map();
40
+
41
+ /**
42
+ * sha256 hex of voiceId, text, canonical resolved voice JSON, the approval pin
43
+ * and — for a project-scope voice only — the resolved projectRoot: two projects
44
+ * may define the same project voice id + JSON over different scripts, so their
45
+ * clips must not share a key; machine and built-in voices stay shared.
46
+ */
47
+ function previewKey({ voiceId, text, voice, pin, scope, projectRoot }) {
48
+ const root = scope === 'project' && projectRoot ? path.resolve(String(projectRoot)) : undefined;
49
+ return crypto.createHash('sha256')
50
+ .update(voiceLibrary.canonical({ voiceId: String(voiceId), text: String(text), voice: voice ?? null, pin: String(pin ?? ''), projectRoot: root }))
51
+ .digest('hex');
52
+ }
53
+
54
+ const cacheDir = () => path.join(voiceLibrary.voicesHome(), 'cache');
55
+
56
+ /** Remove the oldest-mtime clips until at most CACHE_MAX remain; never throws. */
57
+ function pruneCache(dir, keep) {
58
+ let files;
59
+ try {
60
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.wav') && !f.endsWith('.tmp.wav')).map((f) => {
61
+ const p = path.join(dir, f);
62
+ try { return { p, f, m: fs.statSync(p).mtimeMs }; } catch { return null; }
63
+ }).filter(Boolean);
64
+ } catch {
65
+ return;
66
+ }
67
+ if (files.length <= CACHE_MAX) return;
68
+ files.sort((a, b) => a.m - b.m);
69
+ let excess = files.length - CACHE_MAX;
70
+ for (const x of files) {
71
+ if (excess <= 0) break;
72
+ if (x.p === keep) continue;
73
+ try { fs.rmSync(x.p, { force: true }); } catch { /* best effort */ }
74
+ excess -= 1;
75
+ }
76
+ }
77
+
78
+ /** One async run of the speak CLI -> {code, signal, stdout, stderr, error?}. */
79
+ function runOnce(specPath, cwd, killAfterMs) {
80
+ return new Promise((resolve) => {
81
+ let stdout = '';
82
+ let stderr = '';
83
+ let settled = false;
84
+ let timer = null;
85
+ const done = (r) => {
86
+ if (settled) return;
87
+ settled = true;
88
+ if (timer) clearTimeout(timer);
89
+ resolve({ stdout, stderr, ...r });
90
+ };
91
+ let child;
92
+ try {
93
+ child = childProcess.spawn(process.execPath, [CHARACTER_CJS, 'speak', specPath], {
94
+ cwd,
95
+ env: cleanChildEnv({ ELECTRON_RUN_AS_NODE: '1' }),
96
+ stdio: ['ignore', 'pipe', 'pipe'],
97
+ shell: false,
98
+ windowsHide: true,
99
+ });
100
+ } catch (e) {
101
+ done({ code: null, signal: null, error: e.message });
102
+ return;
103
+ }
104
+ child.stdout?.on('data', (d) => { stdout = (stdout + d).slice(-OUTPUT_TAIL); });
105
+ child.stderr?.on('data', (d) => { stderr = (stderr + d).slice(-OUTPUT_TAIL); });
106
+ child.on('error', (e) => done({ code: null, signal: null, error: e.message }));
107
+ child.on('close', (code, signal) => done({ code, signal }));
108
+ timer = setTimeout(() => {
109
+ try { child.kill('SIGTERM'); } catch { /* gone */ }
110
+ done({ code: null, signal: 'SIGTERM', timedOut: true });
111
+ }, Math.max(1, killAfterMs));
112
+ });
113
+ }
114
+
115
+ /** The CLI's own error: its JSON result line's error, else stderr, else the exit. */
116
+ function cliError(r) {
117
+ const last = String(r.stdout || '').trim().split('\n').pop() || '';
118
+ try {
119
+ const j = JSON.parse(last);
120
+ if (j && typeof j.error === 'string' && j.error) return j.error;
121
+ } catch { /* not JSON */ }
122
+ const err = String(r.stderr || '').trim();
123
+ if (err) return err;
124
+ if (r.error) return r.error;
125
+ return `speak CLI failed (${r.signal ? `killed by ${r.signal}` : `exit ${r.code}`})`;
126
+ }
127
+
128
+ async function synthesize({ root, voiceId, text, key, timeoutMs }) {
129
+ const dir = cacheDir();
130
+ const wavPath = path.join(dir, `${key}.wav`);
131
+ const tmpOut = path.join(dir, `${key}.tmp.wav`);
132
+ let specDir = null;
133
+ try {
134
+ fs.mkdirSync(dir, { recursive: true });
135
+ fs.rmSync(tmpOut, { force: true });
136
+ specDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-voice-preview-'));
137
+ const specPath = path.join(specDir, 'spec.json');
138
+ const spec = { projectRoot: root, voice: voiceId, kind: 'preview', label: `preview ${voiceId}`, lines: [{ text, out: tmpOut }] };
139
+ fs.writeFileSync(specPath, JSON.stringify(spec));
140
+ const deadline = Date.now() + timeoutMs;
141
+ for (;;) {
142
+ const left = deadline - Date.now();
143
+ if (left <= 0) return { ok: false, error: `voice preview for '${voiceId}' timed out after ${Math.round(timeoutMs / 1000)}s` };
144
+ const r = await runOnce(specPath, root, left);
145
+ if (r.timedOut) return { ok: false, error: `voice preview for '${voiceId}' timed out after ${Math.round(timeoutMs / 1000)}s` };
146
+ if (r.code === EXIT_PENDING) {
147
+ await new Promise((res) => setTimeout(res, Math.min(RETRY_DELAY_MS, Math.max(0, deadline - Date.now()))));
148
+ continue;
149
+ }
150
+ if (r.code !== 0) return { ok: false, error: cliError(r) };
151
+ if (!fs.existsSync(tmpOut)) return { ok: false, error: `speak CLI exited 0 but wrote no clip to ${tmpOut}` };
152
+ fs.renameSync(tmpOut, wavPath);
153
+ pruneCache(dir, wavPath);
154
+ return { ok: true, cached: false, wavPath, bytes: fs.readFileSync(wavPath) };
155
+ }
156
+ } catch (e) {
157
+ return { ok: false, error: `voice preview failed: ${e && e.message ? e.message : String(e)}` };
158
+ } finally {
159
+ try { fs.rmSync(tmpOut, { force: true }); } catch { /* best effort */ }
160
+ if (specDir) {
161
+ try { require('../demo-video-kit/resumableRun.cjs').stopRun(path.join(specDir, 'spec.json.run')); } catch { /* none */ }
162
+ try { fs.rmSync(specDir, { recursive: true, force: true }); } catch { /* best effort */ }
163
+ }
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Preview one library voice speaking `text`.
169
+ * -> {ok:true, cached, wavPath, bytes: Buffer} | {ok:false, error}
170
+ * @param {{ projectRoot?: string, voiceId: string, text: string, timeoutMs?: number }} args
171
+ */
172
+ async function previewVoice({ projectRoot, voiceId, text, timeoutMs } = /** @type {any} */ ({})) {
173
+ if (!projectRoot || typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
174
+ return { ok: false, error: 'projectRoot must be an absolute path' };
175
+ }
176
+ const root = path.resolve(projectRoot);
177
+ const t = typeof text === 'string' ? text.trim() : '';
178
+ if (t.length < 1 || t.length > TEXT_MAX) return { ok: false, error: `text must be 1-${TEXT_MAX} chars after trimming` };
179
+ const rv = voiceLibrary.resolveVoiceId(root, voiceId);
180
+ if (!rv.ok) return { ok: false, error: rv.error };
181
+ const key = previewKey({ voiceId, text: t, voice: rv.voice, pin: voiceLibrary.pinOf(rv.entry, root), scope: rv.scope, projectRoot: root });
182
+ const wavPath = path.join(cacheDir(), `${key}.wav`);
183
+ try {
184
+ const bytes = fs.readFileSync(wavPath);
185
+ try { const now = new Date(); fs.utimesSync(wavPath, now, now); } catch { /* best effort */ }
186
+ return { ok: true, cached: true, wavPath, bytes };
187
+ } catch { /* miss */ }
188
+ const running = inFlight.get(key);
189
+ if (running) return running;
190
+ const ms = Number.isFinite(timeoutMs) && /** @type {number} */ (timeoutMs) > 0 ? /** @type {number} */ (timeoutMs) : DEFAULT_TIMEOUT_MS;
191
+ const p = synthesize({ root, voiceId, text: t, key, timeoutMs: ms }).finally(() => inFlight.delete(key));
192
+ inFlight.set(key, p);
193
+ return p;
194
+ }
195
+
196
+ module.exports = { previewVoice, previewKey, CACHE_MAX, TEXT_MAX, DEFAULT_TIMEOUT_MS };
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * voicesIpc.cjs — the Voices screen's IPC (Project Home ▸ Video ▸ Voices).
5
+ * Renderer IPC only: no admin HTTP route or MCP tool reaches the writers here,
6
+ * so changing an approved voice always takes a human click in the app.
7
+ *
8
+ * voices:list {cwd} -> { voices, errors, lane }
9
+ * each voice = voiceLibrary.listVoices entry + lastPreview
10
+ * {at, wallMs, audioSeconds} | null (newest 'preview' usage
11
+ * line for this project, voiceLane.readUsage) + inLane
12
+ * {lane, position} | null (voiceLane.laneSnapshot).
13
+ * voices:preview {cwd, voiceId, text} -> previewVoice result, bytes as a Uint8Array.
14
+ * voices:approve {cwd, voiceId} -> writes <voicesHome>/approvals.json
15
+ * each approval as {pin, approvedAt (ISO)}, pin = voiceLibrary.pinOf;
16
+ * project/machine voices only.
17
+ * voices:unapprove {cwd, voiceId} -> removes that approval.
18
+ * voices:delete {cwd, voiceId} -> deletes the effective project or
19
+ * machine voice file; refuses an approved voice and a built-in.
20
+ *
21
+ * This module is the ONLY writer of approvals.json and of voice deletions
22
+ * (voiceLibrary.cjs only reads approvals). Approval keys come from
23
+ * voiceLibrary.approvalKey — the reader's own function, never a copy.
24
+ *
25
+ * deps: { schemas, validatePath } plus optional test overrides
26
+ * { resolveProjectRoot, voiceLibrary, voiceLane, previewVoice, now }.
27
+ */
28
+
29
+ const fs = require('node:fs');
30
+ const path = require('node:path');
31
+ const { writeJsonAtomicSync } = require('../util/atomicFs.cjs');
32
+
33
+ const BUILTIN_ERROR = 'built-in voices cannot be approved, unapproved or deleted';
34
+ const APPROVED_DELETE_ERROR = 'this voice is approved — unapprove it first';
35
+
36
+ function libOf(deps) {
37
+ return deps.voiceLibrary || require('../demo-video-kit/voiceLibrary.cjs');
38
+ }
39
+ function laneOf(deps) {
40
+ return deps.voiceLane || require('../demo-video-kit/voiceLane.cjs');
41
+ }
42
+
43
+ /** cwd -> validated, resolved project root. Throws on an invalid cwd. */
44
+ function projectRootOf(deps, cwd) {
45
+ const real = deps.validatePath(cwd);
46
+ const resolve = deps.resolveProjectRoot || require('../opsOwnership.cjs').resolveProjectRoot;
47
+ return path.resolve(resolve(real));
48
+ }
49
+
50
+ // The one approval-key format, shared with the reader so the two can never drift.
51
+ const { approvalKey } = require('../demo-video-kit/voiceLibrary.cjs');
52
+
53
+ function approvalsPath(lib) {
54
+ return path.join(lib.voicesHome(), 'approvals.json');
55
+ }
56
+
57
+ /** The effective (highest-scope) library entry for id, or null. */
58
+ function effectiveEntry(lib, root, voiceId) {
59
+ const { voices } = lib.listVoices(root);
60
+ return voices.find((v) => v.id === voiceId) || null;
61
+ }
62
+
63
+ function writeApprovals(lib, approvals) {
64
+ writeJsonAtomicSync(approvalsPath(lib), { version: 1, approvals });
65
+ }
66
+
67
+ function listWithStats(deps, root) {
68
+ const lib = libOf(deps);
69
+ const lane = laneOf(deps);
70
+ const { voices, errors } = lib.listVoices(root);
71
+ let usage = [];
72
+ try { usage = lane.readUsage({ projectRoot: root, limit: Infinity }) || []; } catch { usage = []; }
73
+ /** @type {Map<string, any>} */
74
+ const last = new Map();
75
+ for (const row of usage) {
76
+ if (!row || row.kind !== 'preview' || typeof row.voiceId !== 'string' || last.has(row.voiceId)) continue;
77
+ last.set(row.voiceId, {
78
+ at: typeof row.at === 'string' ? row.at : null,
79
+ wallMs: Number.isFinite(row.wallMs) ? row.wallMs : null,
80
+ audioSeconds: Number.isFinite(row.audioSeconds) ? row.audioSeconds : null,
81
+ });
82
+ }
83
+ let snapshot = {};
84
+ try { snapshot = lane.laneSnapshot() || {}; } catch { snapshot = {}; }
85
+ /** @type {Map<string, {lane: string, position: number}>} */
86
+ const inLane = new Map();
87
+ for (const [name, tickets] of Object.entries(snapshot)) {
88
+ for (const t of Array.isArray(tickets) ? tickets : []) {
89
+ if (!t || typeof t.voiceId !== 'string' || inLane.has(t.voiceId)) continue;
90
+ if (t.projectRoot && t.projectRoot !== root) continue;
91
+ inLane.set(t.voiceId, { lane: name, position: t.position });
92
+ }
93
+ }
94
+ return {
95
+ voices: voices.map((v) => ({ ...v, lastPreview: last.get(v.id) || null, inLane: inLane.get(v.id) || null })),
96
+ errors,
97
+ lane: snapshot,
98
+ };
99
+ }
100
+
101
+ async function preview(deps, root, voiceId, text) {
102
+ const run = deps.previewVoice || require('./voicePreview.cjs').previewVoice;
103
+ const r = await run({ projectRoot: root, voiceId, text });
104
+ if (!r || r.ok !== true) return { ok: false, error: (r && r.error) || 'voice preview failed' };
105
+ return { ok: true, cached: !!r.cached, wavPath: r.wavPath, bytes: new Uint8Array(r.bytes) };
106
+ }
107
+
108
+ function approve(deps, root, voiceId) {
109
+ const lib = libOf(deps);
110
+ const entry = effectiveEntry(lib, root, voiceId);
111
+ if (!entry) return { ok: false, error: `unknown voice '${voiceId}'` };
112
+ if (entry.scope === 'builtin') return { ok: false, error: BUILTIN_ERROR };
113
+ if (entry.scope !== 'project' && entry.scope !== 'machine') return { ok: false, error: `voice '${voiceId}' has no approvable scope` };
114
+ const { approvals } = lib.readApprovals();
115
+ const key = approvalKey(entry.scope, root, voiceId);
116
+ const pin = lib.pinOf(entry, root);
117
+ const approvedAt = (deps.now ? deps.now() : new Date()).toISOString();
118
+ writeApprovals(lib, { ...approvals, [key]: { pin, approvedAt } });
119
+ return { ok: true, voiceId, scope: entry.scope, pin, approvedAt };
120
+ }
121
+
122
+ function unapprove(deps, root, voiceId) {
123
+ const lib = libOf(deps);
124
+ const entry = effectiveEntry(lib, root, voiceId);
125
+ if (entry && entry.scope === 'builtin') return { ok: false, error: BUILTIN_ERROR };
126
+ const { approvals } = lib.readApprovals();
127
+ // The effective entry's key; with no file left (removed outside the app), any
128
+ // project/machine approval of this id so the human can clear the refusal.
129
+ const keys = entry
130
+ ? [approvalKey(entry.scope, root, voiceId)]
131
+ : [approvalKey('project', root, voiceId), approvalKey('machine', root, voiceId)];
132
+ const present = keys.filter((k) => Object.prototype.hasOwnProperty.call(approvals, k));
133
+ if (!present.length) return { ok: false, error: `voice '${voiceId}' is not approved` };
134
+ const next = { ...approvals };
135
+ for (const k of present) delete next[k];
136
+ writeApprovals(lib, next);
137
+ return { ok: true, voiceId };
138
+ }
139
+
140
+ function deleteVoice(deps, root, voiceId) {
141
+ const lib = libOf(deps);
142
+ const entry = effectiveEntry(lib, root, voiceId);
143
+ if (!entry) return { ok: false, error: `unknown voice '${voiceId}'` };
144
+ if (entry.scope === 'builtin') return { ok: false, error: BUILTIN_ERROR };
145
+ const { approvals } = lib.readApprovals();
146
+ if (Object.prototype.hasOwnProperty.call(approvals, approvalKey(entry.scope, root, voiceId))) {
147
+ return { ok: false, error: APPROVED_DELETE_ERROR };
148
+ }
149
+ if (typeof entry.file !== 'string' || !entry.file) return { ok: false, error: `voice '${voiceId}' has no file` };
150
+ try {
151
+ fs.unlinkSync(entry.file);
152
+ } catch (e) {
153
+ return { ok: false, error: `could not delete voice '${voiceId}': ${e && e.message ? e.message : String(e)}` };
154
+ }
155
+ return { ok: true, voiceId, scope: entry.scope, file: entry.file };
156
+ }
157
+
158
+ function registerVoicesIpc(ipcMain, deps = {}) {
159
+ ipcMain.handle('voices:list', async (_event, raw) => {
160
+ const p = deps.schemas.voicesList.parse(raw);
161
+ return listWithStats(deps, projectRootOf(deps, p.cwd));
162
+ });
163
+ ipcMain.handle('voices:preview', async (_event, raw) => {
164
+ const p = deps.schemas.voicesPreview.parse(raw);
165
+ return preview(deps, projectRootOf(deps, p.cwd), p.voiceId, p.text);
166
+ });
167
+ ipcMain.handle('voices:approve', async (_event, raw) => {
168
+ const p = deps.schemas.voicesApprove.parse(raw);
169
+ return approve(deps, projectRootOf(deps, p.cwd), p.voiceId);
170
+ });
171
+ ipcMain.handle('voices:unapprove', async (_event, raw) => {
172
+ const p = deps.schemas.voicesUnapprove.parse(raw);
173
+ return unapprove(deps, projectRootOf(deps, p.cwd), p.voiceId);
174
+ });
175
+ ipcMain.handle('voices:delete', async (_event, raw) => {
176
+ const p = deps.schemas.voicesDelete.parse(raw);
177
+ return deleteVoice(deps, projectRootOf(deps, p.cwd), p.voiceId);
178
+ });
179
+ }
180
+
181
+ module.exports = {
182
+ registerVoicesIpc,
183
+ BUILTIN_ERROR,
184
+ APPROVED_DELETE_ERROR,
185
+ CHANNELS: Object.freeze(['voices:list', 'voices:preview', 'voices:approve', 'voices:unapprove', 'voices:delete']),
186
+ };
@@ -115,6 +115,12 @@ const PromptSessionSchema = z.object({
115
115
  // Unknown ids are kept (bounded strings, never an enum) so dropInvalidSessions (ipcSchemas.cjs)
116
116
  // never drops a row for a pack id a newer build ships and this one does not know.
117
117
  packs: z.array(z.string().min(1).max(64)).max(16).optional(),
118
+ // Content id (sha256 hex) of the AgentSnapshot (claude/agentSnapshot.cjs) frozen at mint:
119
+ // every chat turn builds its persona body + model from it, so a later persona edit reaches
120
+ // only new Epics. Absent on Epics minted before pinning (they keep the live persona read)
121
+ // and on non-Claude / agentType-less Epics. A bounded string, not a hex regex, so
122
+ // dropInvalidSessions (ipcSchemas.cjs) never drops a whole row over it.
123
+ agentSnapshotId: z.string().min(1).max(128).optional(),
118
124
  // true = this Epic adopted an existing CLI session as its claudeSessionId
119
125
  // (ensureEpic's restoreSessionId) instead of a fresh one; absent otherwise.
120
126
  // Only true is ever written: a false would fail here, and dropInvalidSessions
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+ // @ts-check
3
+
4
+ /**
5
+ * cancelledRow — the ONE definition of "did a human cancel this queue row?"
6
+ * Pure, requires nothing, so every layer (scheduler, queueOps, lib/epic,
7
+ * lib/prd) can import it without dragging in scheduler deps.
8
+ *
9
+ * The rule: a row is cancelled when its status is a cancel status AND at
10
+ * least one cancel marker holds.
11
+ *
12
+ * Why two statuses: remote.cancelJob (scheduler.cjs) parks a cancelled row as
13
+ * 'failed', except when the killed run's landedCommit resolves — then it parks
14
+ * 'needs_review' so the landed work is verified before anyone trusts it. Both
15
+ * are a human cancel. Any other status (pending, running, completed, …) is
16
+ * never cancelled, even if it still carries a stale marker.
17
+ *
18
+ * Why three markers (any one is enough):
19
+ * 1. `cancelledAt` (non-empty string) — stamped by remote.cancelJob (and its
20
+ * dependents cascade) since 2026-10-19; the primary marker.
21
+ * 2. The newest statusHistory entry whose `to` equals the row's current
22
+ * status has source 'remote:cancelJob' — covers rows cancelled before
23
+ * `cancelledAt` existed. Only the newest matching entry counts, so a row
24
+ * cancelled, reset, then failed for real reads as a real failure.
25
+ * 3. `error` starts with 'cancelled via admin API' — the oldest rows, which
26
+ * carry neither of the above.
27
+ *
28
+ * A revived row never reads as cancelled: resetJobFields deletes `cancelledAt`
29
+ * and overwrites `error`, and the reset moves status off failed/needs_review.
30
+ */
31
+
32
+ /** Statuses remote.cancelJob writes for a cancelled row. */
33
+ const CANCEL_STATUSES = new Set(['failed', 'needs_review']);
34
+ /** statusHistory source remote.cancelJob stamps. */
35
+ const CANCEL_SOURCE = 'remote:cancelJob';
36
+ /** Prefix of every error string remote.cancelJob writes. */
37
+ const CANCEL_ERROR_PREFIX = 'cancelled via admin API';
38
+
39
+ /**
40
+ * @param {unknown} row a queue row (ScheduleJob-shaped) or anything else
41
+ * @returns {boolean} true only for a human-cancelled row
42
+ */
43
+ function isCancelledRow(row) {
44
+ if (!row || typeof row !== 'object') return false;
45
+ const r = /** @type {Record<string, any>} */ (row);
46
+ if (!CANCEL_STATUSES.has(r.status)) return false;
47
+ if (typeof r.cancelledAt === 'string' && r.cancelledAt.length > 0) return true;
48
+ if (typeof r.error === 'string' && r.error.startsWith(CANCEL_ERROR_PREFIX)) return true;
49
+ const hist = Array.isArray(r.statusHistory) ? r.statusHistory : [];
50
+ for (let i = hist.length - 1; i >= 0; i--) {
51
+ const h = hist[i];
52
+ if (h && h.to === r.status) return h.source === CANCEL_SOURCE;
53
+ }
54
+ return false;
55
+ }
56
+
57
+ module.exports = { isCancelledRow, CANCEL_STATUSES, CANCEL_SOURCE, CANCEL_ERROR_PREFIX };