claude-code-session-manager 0.141.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -2,6 +2,7 @@
2
2
  * projectHomeAdminRoutes.cjs — admin routes behind Project Home's library:
3
3
  * POST /admin/project-home/pages/write -> project-pages/knowledge/<pageId>/{index.html,meta.json}
4
4
  * POST /admin/project-home/videos/write -> project-pages/videos/<videoId>/{index.html,meta.json}
5
+ * (+ video.mp4 and poster.png, required for kind 'tiktok' / 'marketing')
5
6
  * POST /admin/project-home/write alias: {cwd, html} -> knowledge/overview/
6
7
  * POST /admin/project-home/demo-video/write alias: {cwd, html} -> a new videos/vid-<id>/ project-demo entry
7
8
  * POST /admin/project-home/matrix/read {cwd} -> project-pages/matrix/matrix.json (+ its JSON Schema)
@@ -9,6 +10,8 @@
9
10
  * POST /admin/project-home/videos/review/write {cwd, videoId, text, images:[{base64}]} -> videoReview.writeMaterial
10
11
  * (review material only; there is deliberately no route that decides, approves or retries —
11
12
  * only the human buttons in the app record a decision)
13
+ * POST /admin/project-home/videos/outcome/write {cwd, videoId, outcome, text} -> videos/<videoId>/outcome.json
14
+ * (a run that ends without a video by design, e.g. a finished TikTok series: outcome 'season-complete')
12
15
  * all owned by writer 'project-home' (see opsOwnership.cjs). Registered
13
16
  * against the same injected localAdminHttp.cjs transport as
14
17
  * prdAdminRoutes.cjs.
@@ -34,8 +37,9 @@ const { resolveProjectContext } = require('../projectRootResolve.cjs');
34
37
  const { opsPath, OPS_ROOT_DIR } = require('../opsOwnership.cjs');
35
38
  const config = require('../../config.cjs');
36
39
  const { schemas, ENTRY_ID_RE } = require('../../ipcSchemas.cjs');
37
- const { validateCharacterJson, validateCharacterJs, readCharacter, characterDir, MAX_JS_BYTES: MAX_CHARACTER_JS_BYTES } = require('../demo-video-kit/character.cjs');
38
- const { checkHtmlLimits } = require('../demo-video-kit/checks.cjs');
40
+ const { validateCharacterJson, validateCharacterJs, voiceIdRefsOf, inspectCharacter, characterDir, MAX_JSON_BYTES: MAX_CHARACTER_JSON_BYTES, MAX_JS_BYTES: MAX_CHARACTER_JS_BYTES } = require('../demo-video-kit/character.cjs');
41
+ const voiceLibrary = require('../demo-video-kit/voiceLibrary.cjs');
42
+ const { checkHtmlLimits, checkPostCaption, TIKTOK_CHECK_IDS } = require('../demo-video-kit/checks.cjs');
39
43
  const { injectPlayerBridge } = require('../project-pages/playerBridge.cjs');
40
44
  const { readMatrix, matrixJsonSchema, MAX_MATRIX_BYTES } = require('../project-pages/competitiveMatrix.cjs');
41
45
  const { writeMatrix } = require('../project-pages/matrixStore.cjs');
@@ -43,10 +47,22 @@ const videoReview = require('../project-pages/videoReview.cjs');
43
47
 
44
48
  const MAX_HTML_BYTES = 1024 * 1024;
45
49
  const MAX_DEMO_VIDEO_BYTES = 2 * 1024 * 1024;
50
+ /** Exported MP4 cap: 24 MiB per started 30 s of lengthS. */
51
+ const MAX_EXPORT_MP4_BYTES_PER_30S = 24 * 1024 * 1024;
52
+ const MAX_EXPORT_POSTER_BYTES = 4 * 1024 * 1024;
53
+ /** Kinds whose save must carry an MP4 + poster export, and the aspect each requires. */
54
+ const EXPORT_KIND_ASPECT = Object.freeze({ tiktok: '9:16', marketing: '16:9' });
55
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
56
+ const BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
46
57
  /** Review write body cap: 6 base64 images of 2 MiB (16 MiB) + a 32000-char text and JSON overhead. */
47
58
  const REVIEW_WRITE_BODY_MAX = 18 * 1024 * 1024;
48
59
  const REVIEW_DECISION_KEYS = Object.freeze(['decision', 'status', 'approved', 'approvedAt']);
49
60
  const REVIEW_DECISION_REFUSAL = 'review decisions are made only by a human in the app';
61
+ /** Outcomes a run may record instead of a video, the outcome text cap, and the only body keys accepted. */
62
+ const VIDEO_OUTCOMES = ['season-complete'];
63
+ const OUTCOME_TEXT_MAX = 300;
64
+ const OUTCOME_BODY_KEYS = ['cwd', 'videoId', 'outcome', 'text'];
65
+ const OUTCOME_WRITE_BODY_MAX = 64 * 1024;
50
66
 
51
67
  // Each detector is a linear regex scan; the input is capped first.
52
68
  const REMOTE_REFERENCE_CHECKS = [
@@ -201,13 +217,14 @@ function resolveCwd(rawCwd) {
201
217
  * meta}. The entry folder gets index.html then meta.json, both atomically as
202
218
  * writer 'project-home'. Responds {ok, path (index.html), bytes}.
203
219
  */
204
- function makeWriteHandler({ schema, bodyLimit, build }) {
220
+ function makeWriteHandler({ schema, bodyLimit, extraBodyBytes = 0, build }) {
205
221
  return async (req, res) => {
206
222
  // Headroom over the html limit for JSON escaping; the html byte limit
207
- // itself is enforced by `build`.
223
+ // itself is enforced by `build`. `extraBodyBytes` makes room for base64
224
+ // binary exports, whose decoded caps `build` enforces too.
208
225
  let raw;
209
226
  try {
210
- raw = await readBody(req, bodyLimit * 2 + 4096);
227
+ raw = await readBody(req, bodyLimit * 2 + extraBodyBytes + 4096);
211
228
  } catch (e) {
212
229
  sendJson(res, 400, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'} (html limit is ${bodyLimit} bytes)` });
213
230
  return;
@@ -242,6 +259,10 @@ function makeWriteHandler({ schema, bodyLimit, build }) {
242
259
  try {
243
260
  const dir = opsPath(resolved.cwd, 'project-pages', ...built.dirParts);
244
261
  await fs.promises.mkdir(dir, { recursive: true });
262
+ // Binary exports first, then index.html, then meta.json last: meta.json marks a complete entry.
263
+ for (const file of built.files ?? []) {
264
+ await config.writeBinaryAtomic(path.join(dir, file.name), file.buffer, { writer: 'project-home' });
265
+ }
245
266
  const abs = path.join(dir, 'index.html');
246
267
  await config.writeTextAtomic(abs, built.html, { writer: 'project-home' });
247
268
  await config.writeTextAtomic(path.join(dir, 'meta.json'), JSON.stringify(built.meta, null, 2) + '\n', { writer: 'project-home' });
@@ -257,6 +278,63 @@ function maxVideoBytes(lengthS) {
257
278
  return Math.ceil(lengthS / 30) * MAX_DEMO_VIDEO_BYTES;
258
279
  }
259
280
 
281
+ /** Exported MP4 cap for a video of `lengthS` seconds: 24 MiB per started 30 s. */
282
+ function maxExportMp4Bytes(lengthS) {
283
+ return Math.ceil(lengthS / 30) * MAX_EXPORT_MP4_BYTES_PER_30S;
284
+ }
285
+
286
+ /** Base64 length that decodes to at most `bytes` bytes. */
287
+ function base64LengthFor(bytes) {
288
+ return Math.ceil(bytes / 3) * 4;
289
+ }
290
+
291
+ /** Decodes one base64 export under `maxBytes`; -> {buffer} | {error}. Errors never echo the payload. */
292
+ function decodeExport(b64, label, maxBytes) {
293
+ if (b64.length > base64LengthFor(maxBytes)) return { error: `exports.${label} exceeds the ${maxBytes}-byte limit` };
294
+ if (b64.length % 4 !== 0 || !BASE64_RE.test(b64)) return { error: `exports.${label} is not valid base64` };
295
+ const buffer = Buffer.from(b64, 'base64');
296
+ if (buffer.length > maxBytes) return { error: `exports.${label} exceeds the ${maxBytes}-byte limit` };
297
+ return { buffer };
298
+ }
299
+
300
+ /**
301
+ * Rules for kinds that must ship an MP4 + poster ('tiktok', 'marketing'):
302
+ * both exports present, magic bytes, size caps, the kind's aspect, and for
303
+ * 'tiktok' the post caption and every TikTok check passing.
304
+ * -> {files: [{name, buffer}]} | {error}.
305
+ */
306
+ function validateExportKind(input, aspect) {
307
+ const { kind, lengthS } = input;
308
+ const exp = input.exports;
309
+ if (!exp || !exp.mp4Base64 || !exp.posterBase64) {
310
+ return { error: `kind '${kind}' requires exports.mp4Base64 and exports.posterBase64 (the MP4 and poster)` };
311
+ }
312
+ const mp4 = decodeExport(exp.mp4Base64, 'mp4Base64', maxExportMp4Bytes(lengthS));
313
+ if (mp4.error) return { error: `${mp4.error} (24 MiB per started 30 s of lengthS ${lengthS})` };
314
+ if (mp4.buffer.length < 8 || mp4.buffer.toString('latin1', 4, 8) !== 'ftyp') {
315
+ return { error: "exports.mp4Base64 is not an MP4 (no 'ftyp' at bytes 4-7)" };
316
+ }
317
+ const poster = decodeExport(exp.posterBase64, 'posterBase64', MAX_EXPORT_POSTER_BYTES);
318
+ if (poster.error) return { error: poster.error };
319
+ if (poster.buffer.length < PNG_SIGNATURE.length || !poster.buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
320
+ return { error: 'exports.posterBase64 is not a PNG (missing the PNG signature)' };
321
+ }
322
+ const wantAspect = EXPORT_KIND_ASPECT[kind];
323
+ if (aspect !== wantAspect) {
324
+ return { error: `kind '${kind}' requires aspect '${wantAspect}' (the document declares '${aspect}' via sm-demo-aspect)` };
325
+ }
326
+ if (kind === 'tiktok') {
327
+ const post = input.meta?.post;
328
+ if (!post) return { error: "kind 'tiktok' requires meta.post {caption, audience}" };
329
+ const caption = checkPostCaption(post.caption);
330
+ if (!caption.ok) return { error: `kind 'tiktok' post caption check failed: ${caption.detail}` };
331
+ const checks = input.meta?.report?.checks ?? [];
332
+ const missing = TIKTOK_CHECK_IDS.filter((id) => !checks.some((c) => c.id === id && c.ok === true));
333
+ if (missing.length) return { error: `kind 'tiktok' requires every TikTok check in meta.report.checks with ok true; missing or failed: ${missing.join(', ')}` };
334
+ }
335
+ return { files: [{ name: 'video.mp4', buffer: mp4.buffer }, { name: 'poster.png', buffer: poster.buffer }] };
336
+ }
337
+
260
338
  // Owned by the Competitor matrix store (project-pages/matrixStore.cjs writes
261
339
  // knowledge/<id>/ directly). Kept local on purpose; macroJobDispatch.cjs holds
262
340
  // the same constant so the builder never derives this id.
@@ -323,13 +401,19 @@ function registerAdminRoute(adminHttp) {
323
401
  adminHttp.registerRoute('POST', '/admin/project-home/videos/write', makeWriteHandler({
324
402
  schema: schemas.projectVideoAdminWriteBody,
325
403
  bodyLimit: maxVideoBytes(MAX_DEMO_DURATION_S),
404
+ extraBodyBytes: base64LengthFor(maxExportMp4Bytes(MAX_DEMO_DURATION_S)) + base64LengthFor(MAX_EXPORT_POSTER_BYTES),
326
405
  build: (i) => {
327
406
  // Cheap kit checks re-run server-side; the alias route is exempt (Burrow sends no report).
328
407
  const failed = (i.meta?.report?.checks ?? []).find((c) => c.ok === false);
329
408
  if (failed) return { error: `report.checks failed: ${failed.id}${failed.detail ? ` (${failed.detail})` : ''}` };
330
409
  const limits = checkHtmlLimits({ html: i.html, lengthS: i.lengthS });
331
410
  if (!limits.ok) return { error: `${limits.id} check failed: ${limits.detail}` };
332
- return buildVideo(i, i);
411
+ const built = buildVideo(i, i);
412
+ // Other kinds ignore any exports, exactly as before.
413
+ if (built.error || !Object.hasOwn(EXPORT_KIND_ASPECT, i.kind)) return built;
414
+ const exported = validateExportKind(i, built.meta.aspect ?? '16:9');
415
+ if (exported.error) return { error: exported.error };
416
+ return { ...built, files: exported.files };
333
417
  },
334
418
  }));
335
419
 
@@ -370,6 +454,9 @@ function registerAdminRoute(adminHttp) {
370
454
  // POST /admin/project-home/videos/review/write {cwd, videoId, text, images:[{base64}]} -> review/material.json
371
455
  adminHttp.registerRoute('POST', '/admin/project-home/videos/review/write', reviewWriteHandler);
372
456
 
457
+ // POST /admin/project-home/videos/outcome/write {cwd, videoId, outcome, text} -> videos/<videoId>/outcome.json
458
+ adminHttp.registerRoute('POST', '/admin/project-home/videos/outcome/write', outcomeWriteHandler);
459
+
373
460
  // POST /admin/project-home/character/write {cwd, json, js, replace?} -> videos/_character/
374
461
  adminHttp.registerRoute('POST', '/admin/project-home/character/write', characterWriteHandler);
375
462
 
@@ -489,6 +576,71 @@ async function reviewWriteHandler(req, res) {
489
576
  }
490
577
  }
491
578
 
579
+ /** Returns a refusal reason for an outcome body, or null when it is valid. */
580
+ function validateOutcomeBody(body) {
581
+ const unknown = Object.keys(body).filter((k) => !OUTCOME_BODY_KEYS.includes(k));
582
+ if (unknown.length) return `unknown body keys: ${unknown.join(', ')} (allowed: ${OUTCOME_BODY_KEYS.join(', ')})`;
583
+ if (typeof body.videoId !== 'string' || !ENTRY_ID_RE.test(body.videoId)) return 'invalid videoId';
584
+ if (!VIDEO_OUTCOMES.includes(body.outcome)) return `outcome must be one of: ${VIDEO_OUTCOMES.join(', ')}`;
585
+ const { text } = body;
586
+ if (typeof text !== 'string' || !text.trim()) return 'text must be a non-empty string';
587
+ if (/[\r\n]/.test(text)) return 'text must be one line';
588
+ if (text.length > OUTCOME_TEXT_MAX) return `text must be at most ${OUTCOME_TEXT_MAX} characters`;
589
+ return null;
590
+ }
591
+
592
+ /**
593
+ * Records that a video entry ended without a video by design (a finished
594
+ * TikTok series): writes videos/<videoId>/outcome.json = {id, outcome, text, at}.
595
+ * Refused when the entry already has its video (index.html).
596
+ */
597
+ async function outcomeWriteHandler(req, res) {
598
+ let raw;
599
+ try {
600
+ raw = await readBody(req, OUTCOME_WRITE_BODY_MAX);
601
+ } catch (e) {
602
+ sendJson(res, 413, { ok: false, error: `request body rejected: ${e?.message ?? 'unreadable'} (limit is ${OUTCOME_WRITE_BODY_MAX} bytes)` });
603
+ return;
604
+ }
605
+ let body;
606
+ try {
607
+ body = raw ? JSON.parse(raw) : {};
608
+ } catch {
609
+ sendJson(res, 400, { ok: false, error: 'invalid JSON body' });
610
+ return;
611
+ }
612
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
613
+ sendJson(res, 400, { ok: false, error: 'invalid payload' });
614
+ return;
615
+ }
616
+ const invalid = validateOutcomeBody(body);
617
+ if (invalid) {
618
+ sendJson(res, 400, { ok: false, error: invalid });
619
+ return;
620
+ }
621
+ const resolved = resolveCwd(body.cwd);
622
+ if (!resolved.ok) {
623
+ sendJson(res, resolved.status, { ok: false, error: resolved.error });
624
+ return;
625
+ }
626
+ const { videoId, outcome, text } = body;
627
+ const dir = opsPath(resolved.cwd, 'project-pages', 'videos', videoId);
628
+ if (fs.existsSync(path.join(dir, 'index.html'))) {
629
+ sendJson(res, 400, { ok: false, error: `entry ${videoId} already has a video (index.html) — an outcome is only for a run that ends without one` });
630
+ return;
631
+ }
632
+ config.addAllowedRoot(resolved.cwd);
633
+ try {
634
+ await fs.promises.mkdir(dir, { recursive: true });
635
+ const abs = opsPath(resolved.cwd, 'project-pages', 'videos', videoId, 'outcome.json');
636
+ const record = { id: videoId, outcome, text, at: new Date().toISOString() };
637
+ await config.writeTextAtomic(abs, JSON.stringify(record, null, 2) + '\n', { writer: 'project-home' });
638
+ sendJson(res, 200, { ok: true, entryId: videoId, path: abs });
639
+ } catch (e) {
640
+ sendJson(res, 500, { ok: false, error: e?.message ?? 'outcome write failed' });
641
+ }
642
+ }
643
+
492
644
  async function characterWriteHandler(req, res) {
493
645
  let raw;
494
646
  try {
@@ -520,14 +672,36 @@ async function characterWriteHandler(req, res) {
520
672
  sendJson(res, 400, { ok: false, error: `character.json invalid: ${jsonErr}` });
521
673
  return;
522
674
  }
675
+ // A {voiceId} voice must name a library voice this project can use (unknown or
676
+ // tampered-approved ids are refused by voiceLibrary's own reason) before anything is written.
677
+ for (const ref of voiceIdRefsOf(jsonObj)) {
678
+ const r = voiceLibrary.resolveVoiceId(resolved.cwd, ref.voiceId);
679
+ if (!r.ok) {
680
+ sendJson(res, 400, { ok: false, error: r.error });
681
+ return;
682
+ }
683
+ }
684
+ const jsonText = JSON.stringify(jsonObj, null, 2) + '\n';
685
+ const jsonBytes = Buffer.byteLength(jsonText, 'utf8');
686
+ if (jsonBytes > MAX_CHARACTER_JSON_BYTES) {
687
+ sendJson(res, 400, { ok: false, error: `character.json exceeds the ${MAX_CHARACTER_JSON_BYTES}-byte limit (${jsonBytes} bytes as saved)` });
688
+ return;
689
+ }
523
690
  const jsErr = validateCharacterJs(body.js, [...REMOTE_REFERENCE_CHECKS, ...NETWORK_CHECKS]);
524
691
  if (jsErr) {
525
692
  sendJson(res, 400, { ok: false, error: jsErr });
526
693
  return;
527
694
  }
528
- if (!body.replace && readCharacter(resolved.cwd)) {
529
- sendJson(res, 409, { ok: false, error: 'a character already exists — pass replace: true to overwrite it' });
530
- return;
695
+ if (!body.replace) {
696
+ const existing = inspectCharacter(resolved.cwd);
697
+ if (existing.ok) {
698
+ sendJson(res, 409, { ok: false, error: 'a character already exists — pass replace: true to overwrite it' });
699
+ return;
700
+ }
701
+ if (existing.exists) {
702
+ sendJson(res, 409, { ok: false, error: `a character already exists but cannot be used (${existing.error}) — fix it, or pass replace: true to overwrite it` });
703
+ return;
704
+ }
531
705
  }
532
706
  config.addAllowedRoot(resolved.cwd);
533
707
  try {
@@ -535,7 +709,7 @@ async function characterWriteHandler(req, res) {
535
709
  await fs.promises.mkdir(dir, { recursive: true });
536
710
  const jsPath = path.join(dir, 'character.js');
537
711
  await config.writeTextAtomic(jsPath, body.js, { writer: 'project-home' });
538
- await config.writeTextAtomic(path.join(dir, 'character.json'), JSON.stringify(jsonObj, null, 2) + '\n', { writer: 'project-home' });
712
+ await config.writeTextAtomic(path.join(dir, 'character.json'), jsonText, { writer: 'project-home' });
539
713
  sendJson(res, 200, { ok: true, path: dir, bytes: Buffer.byteLength(body.js, 'utf8') });
540
714
  } catch (e) {
541
715
  sendJson(res, 500, { ok: false, error: e?.message ?? 'write failed' });
@@ -548,9 +722,13 @@ module.exports = {
548
722
  validateDemoVideoHtml,
549
723
  injectCsp,
550
724
  maxVideoBytes,
725
+ maxExportMp4Bytes,
726
+ MAX_EXPORT_POSTER_BYTES,
551
727
  DEMO_VIDEO_CSP,
552
728
  MAX_HTML_BYTES,
553
729
  MAX_DEMO_VIDEO_BYTES,
554
730
  REVIEW_WRITE_BODY_MAX,
731
+ VIDEO_OUTCOMES,
732
+ OUTCOME_TEXT_MAX,
555
733
  resolveCwd,
556
734
  };