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
@@ -19,6 +19,7 @@ const { PRD_EFFORT_LEVELS } = require('./lib/prd/prdFrontmatter.cjs');
19
19
  const { MISS_KINDS } = require('./lib/scheduler/validatorVerdictSchema.cjs');
20
20
  // Aliased: this file already has a looser, exchanges-only SESSION_ID_RE (Exchanges section).
21
21
  const { SESSION_ID_RE: RESTORABLE_SESSION_ID_RE } = require('./lib/epic/restorableSessions.cjs');
22
+ const { VOICE_ID_RE } = require('./lib/demo-video-kit/voiceLibrary.cjs');
22
23
 
23
24
  // ──────────────────────────────────────────── PTY
24
25
  const ptySpawn = z.object({
@@ -284,6 +285,12 @@ const promptSessionsCwd = z.object({ cwd: z.string().min(1).max(4096) }).strict(
284
285
  const promptSessionsReadArchived = z.object({ cwd: z.string().min(1).max(4096), epicId: z.string().regex(PROMPT_SESSION_ID_RE) }).strict();
285
286
  const promptSessionsReadSessionTranscript = z.object({ cwd: z.string().min(1).max(4096), sessionId: z.string().min(1).max(128) }).strict();
286
287
  const promptSessionsReopen = z.object({ cwd: z.string().min(1).max(4096), epicId: z.string().regex(PROMPT_SESSION_ID_RE) }).strict();
288
+ // epic:refresh-agent-snapshot (lib/epic/epicAgentRefresh.cjs) — re-pin an Epic's persona snapshot.
289
+ const epicRefreshAgentSnapshot = z.object({ cwd: z.string().min(1).max(4096), epicId: z.string().regex(PROMPT_SESSION_ID_RE) }).strict();
290
+ // epic:purge (lib/epic/epicPurge.cjs) — the human-only purge of a completed Epic's data.
291
+ // Its ONLY caller is the Purge button (typed-id confirm); never exposed to scripts, MCP or admin routes.
292
+ // `dryRun: true` = read-only listing of what a purge would remove (the confirm shows its count).
293
+ const epicPurge = z.object({ cwd: z.string().min(1).max(4096), epicId: z.string().regex(PROMPT_SESSION_ID_RE), dryRun: z.boolean().optional() }).strict();
287
294
 
288
295
  // Renderer entry point for folding an Epic's isolated git worktree branch
289
296
  // back into its owning project's main tree (lib/epic/epicWorktreeMerge.cjs) — PRD
@@ -449,6 +456,19 @@ const PreflightSchema = z.string().max(500);
449
456
  // after-the-fact change path) so both can never disagree on what a valid
450
457
  // disposition value is.
451
458
  const PrdDispositionSchema = z.enum(['append', 'new-head']);
459
+ // String, or a structured criterion { id?, statement, check?: { kind, spec } }.
460
+ // Per-kind shape rules live in prd/prdCriteria.cjs (createPrd / prdBodyPatch run them).
461
+ const AcceptanceCriteriaSchema = z.array(z.union([
462
+ z.string().min(1).max(2000),
463
+ z.object({
464
+ id: z.string().min(1).max(60).optional(),
465
+ statement: z.string().min(1).max(2000),
466
+ check: z.object({
467
+ kind: z.enum(['command', 'file', 'http', 'manual']),
468
+ spec: z.unknown().optional(),
469
+ }).strict().optional(),
470
+ }).strict(),
471
+ ])).min(1).max(100);
452
472
  const schedulerCreatePrd = z.object({
453
473
  title: z.string().min(1).max(200).regex(NO_NEWLINE_RE, 'must not contain newlines'),
454
474
  // Optional (PRD: worktree-cwd Epic-lookup hazard) — when omitted, prdCreate.cjs's
@@ -459,7 +479,7 @@ const schedulerCreatePrd = z.object({
459
479
  cwd: z.string().min(1).max(4096).regex(NO_NEWLINE_RE, 'must not contain newlines').optional(),
460
480
  estimateMinutes: z.number().int().min(1).max(100000).optional(),
461
481
  goal: z.string().min(1).max(20000),
462
- acceptanceCriteria: z.array(z.string().min(1).max(2000)).min(1).max(100),
482
+ acceptanceCriteria: AcceptanceCriteriaSchema,
463
483
  implementationNotes: z.string().min(1).max(20000),
464
484
  outOfScope: z.array(z.string().min(1).max(2000)).max(100).optional(),
465
485
  slug: z.string().min(1).max(60).regex(PRD_CREATE_SLUG_RE).optional(),
@@ -741,7 +761,7 @@ const adminUpdatePrd = z.object({
741
761
  // re-rendered). Mutually exclusive with `body` (enforced in updatePrd too).
742
762
  gate: z.array(z.string().min(1).max(2000)).min(1).max(50).optional(),
743
763
  files: z.array(z.string().min(1).max(1000)).min(1).max(200).optional(),
744
- acceptanceCriteria: z.array(z.string().min(1).max(2000)).min(1).max(100).optional(),
764
+ acceptanceCriteria: AcceptanceCriteriaSchema.optional(),
745
765
  }).strict().refine(
746
766
  (it) => (it.frontmatter && Object.keys(it.frontmatter).length > 0) || it.body !== undefined
747
767
  || it.gate !== undefined || it.files !== undefined || it.acceptanceCriteria !== undefined,
@@ -869,6 +889,8 @@ const macrosSave = MacroSaveSchema;
869
889
  const macrosDelete = MacroDeleteSchema;
870
890
  const macrosSetProject = MacroSetProjectSchema;
871
891
  const macrosRemoveFromProject = MacroRemoveFromProjectSchema;
892
+ // A voice library id: the one shared pattern, voiceLibrary.VOICE_ID_RE.
893
+ const voiceLibraryId = z.string().regex(VOICE_ID_RE);
872
894
  // Background macro job (macroJobIpc.cjs): press a built-in macro or project Video tool as a scheduler PRD inside an existing Epic.
873
895
  const macrosDispatchJob = z.object({
874
896
  cwd: z.string().min(1).max(4096),
@@ -881,6 +903,11 @@ const macrosDispatchJob = z.object({
881
903
  .refine((o) => Object.keys(o).length <= 20, 'at most 20 input values')
882
904
  .optional(),
883
905
  effort: z.enum(/** @type {[string, ...string[]]} */ ([...PRD_EFFORT_LEVELS])).optional(),
906
+ // A Demo Video press asking for the review stage before the final save.
907
+ reviewStage: z.boolean().optional(),
908
+ // A project Video tool press's picked library voice; beats the tool's default voiceId.
909
+ // Omitted = the tool default, else the persona voice, else the kit default.
910
+ voiceId: voiceLibraryId.optional(),
884
911
  });
885
912
  const macrosJobStatus = z.object({ cwd: z.string().min(1).max(4096) });
886
913
  // Dashboard "Needs you" (lib/feedback-remote/needsYouIpc.cjs): list takes no payload; answer
@@ -891,6 +918,13 @@ const needsYouAnswer = z.object({
891
918
  id: z.string().min(1).max(200),
892
919
  answer: z.string().min(1).max(80),
893
920
  }).strict();
921
+ // Tool-risk 'confirm' answer (needsYouIpc.cjs 'scheduler:confirm-tool'): the tool + sha256 args
922
+ // digest name the Needs-you item; approved picks Approve / Deny (toolClearance.answerConfirmation).
923
+ const schedulerConfirmTool = z.object({
924
+ tool: z.string().min(1).max(300),
925
+ argsDigest: z.string().regex(/^[0-9a-f]{64}$/, 'argsDigest must be a sha256 hex digest'),
926
+ approved: z.boolean(),
927
+ }).strict();
894
928
 
895
929
  // ──────────────────────────────────────────── Memory tool (Bundle C, cycle 3)
896
930
  // Workspace-scoped markdown store at ~/.claude/projects/<ws>/memory/.
@@ -1118,6 +1152,18 @@ const projectVideosReviewDecide = z.object({
1118
1152
  note: z.string().max(2000).optional(),
1119
1153
  }).strict();
1120
1154
  const projectVideosReviewRetry = z.object({ cwd: z.string().min(1).max(4096), entryId }).strict();
1155
+ // Voices screen (project-pages/voicesIpc.cjs): renderer IPC only — the sole writer of
1156
+ // voice approvals and deletions. voiceId follows voiceLibrary.VOICE_ID_RE (voiceLibraryId, declared
1157
+ // above macrosDispatchJob); text is TEXT_MAX (300).
1158
+ const voicesList = z.object({ cwd: z.string().min(1).max(4096) }).strict();
1159
+ const voicesPreview = z.object({
1160
+ cwd: z.string().min(1).max(4096),
1161
+ voiceId: voiceLibraryId,
1162
+ text: z.string().min(1).max(300),
1163
+ }).strict();
1164
+ const voicesApprove = z.object({ cwd: z.string().min(1).max(4096), voiceId: voiceLibraryId }).strict();
1165
+ const voicesUnapprove = z.object({ cwd: z.string().min(1).max(4096), voiceId: voiceLibraryId }).strict();
1166
+ const voicesDelete = z.object({ cwd: z.string().min(1).max(4096), voiceId: voiceLibraryId }).strict();
1121
1167
  const projectVideoReportFields = {
1122
1168
  lufs: z.number().nullable(),
1123
1169
  truePeakDb: z.number().nullable(),
@@ -1129,13 +1175,21 @@ const projectVideoReportFields = {
1129
1175
  detail: z.string().max(300),
1130
1176
  }).strict()).max(60),
1131
1177
  };
1178
+ // One list for every saved-video kind, so the meta and the admin write body cannot drift.
1179
+ const PROJECT_VIDEO_KINDS = /** @type {const} */ (['project-demo', 'blog-post', 'feature', 'episode', 'tiktok', 'marketing']);
1180
+ const projectVideoKind = z.enum(PROJECT_VIDEO_KINDS);
1132
1181
  const projectVideoMeta = z.object({
1133
1182
  id: entryId,
1134
1183
  title: z.string().min(1).max(120),
1135
- kind: z.enum(['project-demo', 'blog-post', 'feature', 'episode']),
1184
+ kind: projectVideoKind,
1136
1185
  target: z.string().max(300).optional(),
1137
1186
  // From the document's sm-demo-aspect tag; absent on older entries (treat as '16:9').
1138
1187
  aspect: z.enum(['16:9', '9:16']).optional(),
1188
+ // TikTok post copy; absent on every other kind and on older entries.
1189
+ post: z.object({
1190
+ caption: z.string().min(1).max(150),
1191
+ audience: z.string().min(1).max(200),
1192
+ }).strict().optional(),
1139
1193
  style: z.string().max(40),
1140
1194
  lengthS: z.number().int().min(5).max(60),
1141
1195
  createdAt: z.string().datetime(),
@@ -1182,12 +1236,17 @@ const projectVideoAdminWriteBody = z.object({
1182
1236
  cwd: z.string().min(1).max(4096).optional(),
1183
1237
  videoId: entryId,
1184
1238
  title: z.string().min(1).max(120),
1185
- kind: z.enum(['project-demo', 'blog-post', 'feature', 'episode']),
1239
+ kind: projectVideoKind,
1186
1240
  lengthS: z.number().int().min(5).max(60),
1187
1241
  html: z.string(),
1188
1242
  meta: projectVideoMeta.omit({ id: true, createdAt: true }).extend({
1189
1243
  report: z.object(projectVideoReportFields).strict(),
1190
1244
  }),
1245
+ // Optional MP4 + poster export, base64-encoded; top level, never inside meta.
1246
+ exports: z.object({
1247
+ mp4Base64: z.string().min(1),
1248
+ posterBase64: z.string().min(1),
1249
+ }).strict().optional(),
1191
1250
  }).strict();
1192
1251
 
1193
1252
  const projectBriefSetPin = z.object({
@@ -1253,15 +1312,12 @@ const AUDIT_LOG_KIND = z.enum([
1253
1312
  'epic_resume',
1254
1313
  'epic_duplicate',
1255
1314
  'epic_draft_update',
1256
- 'epic_continue',
1257
1315
  ]);
1258
1316
  const auditLogAppend = z.object({
1259
1317
  kind: AUDIT_LOG_KIND,
1260
1318
  cwd: z.string().min(1).max(4096),
1261
1319
  epicId: z.string().min(1).max(256),
1262
1320
  source: z.string().min(1).max(256),
1263
- /** epic_continue only: the Epic the new session continues from. */
1264
- fromEpicId: z.string().min(1).max(256).optional(),
1265
1321
  }).strict();
1266
1322
 
1267
1323
  // ──────────────────────────────────────────── Exchanges (PRD 324 read path)
@@ -1446,6 +1502,28 @@ const webRemoteConfirmSas = z.object({
1446
1502
  clientKey: z.string().max(64).optional(),
1447
1503
  }).strict().optional();
1448
1504
 
1505
+ // Paired services (servicePairings.cjs). scope names the service MCP tools the
1506
+ // store validates against its own SERVICE_TOOL_NAMES; these bounds refuse junk early.
1507
+ const WEB_REMOTE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1508
+ const webRemoteServicePairStart = z.object({
1509
+ name: z.string().min(1).max(64).regex(/^[^\r\n]+$/),
1510
+ homeCwd: z.string().min(1).max(4096),
1511
+ scope: z.array(z.string().min(1).max(64)).min(1).max(16),
1512
+ }).strict();
1513
+ const webRemoteServiceConfirmSas = z.object({
1514
+ pairingId: z.string().regex(WEB_REMOTE_UUID_RE),
1515
+ sas: z.string().regex(/^[0-9]{6}$/),
1516
+ }).strict();
1517
+ const webRemoteServicePairCancel = z.object({
1518
+ pairingId: z.string().regex(WEB_REMOTE_UUID_RE),
1519
+ }).strict();
1520
+ const webRemoteServiceRevoke = z.object({
1521
+ serviceId: z.string().regex(WEB_REMOTE_UUID_RE),
1522
+ }).strict();
1523
+ const webRemoteRelayClientRevoke = z.object({
1524
+ clientId: z.string().uuid(),
1525
+ }).strict();
1526
+
1449
1527
  const webRemoteAuditTail = z.object({
1450
1528
  lines: z.number().int().min(1).max(500).optional(),
1451
1529
  }).strict();
@@ -1607,10 +1685,12 @@ const telemetrySetConfig = z.object({
1607
1685
 
1608
1686
  const customerFeedbackSubmit = z.object({
1609
1687
  title: z.string().max(120),
1610
- body: z.string().max(4000),
1688
+ body: z.string().max(5000),
1611
1689
  tag: z.enum(['bug', 'feature', 'discussion']),
1612
1690
  images: z.array(z.object({ dataUrl: z.string().max(35_000_000) })).max(5).optional(),
1613
1691
  imagePaths: z.array(z.string().max(4096)).max(5).optional(),
1692
+ // Validated by feedbackReport.parseContext downstream (Report v1 rules, <= 262144 bytes).
1693
+ context: z.unknown().optional(),
1614
1694
  });
1615
1695
  const customerFeedbackMarkSeen = z.object({ ids: z.array(z.string().max(200)).max(500).optional() });
1616
1696
  const customerFeedbackInboxList = z.object({ includeHidden: z.boolean().optional() });
@@ -1622,6 +1702,54 @@ const customerFeedbackInboxSetStatus = z.object({
1622
1702
  const customerFeedbackInboxLinkEpic = z.object({ id: z.string().max(200), epicId: z.string().max(200) });
1623
1703
  const customerFeedbackInboxImage = z.object({ id: z.string().min(1).max(200), index: z.number().int().min(0).max(4) }).strict();
1624
1704
 
1705
+ // ──────────────────────────────────────────── Website-feedback widgets (siteFeedbackIpc.cjs)
1706
+ // Every object is .strict() so a renderer can never smuggle key material or paths through.
1707
+ // siteFeedbackService re-normalises label/origins; these bounds only refuse junk early.
1708
+ // Each schema mirrors the api.d.ts interface of the same name + `Input`, field for field:
1709
+ // siteFeedbackWidgetCreate = SiteFeedbackWidgetCreateInput, siteFeedbackWidgetList =
1710
+ // SiteFeedbackWidgetListInput, … siteFeedbackInboxLinkEpic = SiteFeedbackInboxLinkEpicInput;
1711
+ // sfInboxStatus = SiteFeedbackStatus. Results (SiteFeedbackWidget, SiteFeedbackInboxItem,
1712
+ // SiteFeedbackItemDetail) are typed in api.d.ts only — main builds them, nothing parses them.
1713
+ const sfCwd = z.string().min(1).max(4096);
1714
+ const sfBoxId = z.string().min(1).max(200);
1715
+ const sfHostId = z.string().regex(/^FB-[0-9A-Z]{5}$/);
1716
+ const sfLabel = z.string().min(1).max(80);
1717
+ const sfOrigins = z.array(z.string().min(1).max(2048)).min(1).max(10);
1718
+ const sfInboxStatus = z.enum(['open', 'in_progress', 'resolved', 'wontfix']);
1719
+ /** Mirrors SiteFeedbackWidgetCreateInput (src/preload/api.d.ts). */
1720
+ const siteFeedbackWidgetCreate = z.object({ cwd: sfCwd, label: sfLabel, allowedOrigins: sfOrigins }).strict();
1721
+ /** Mirrors SiteFeedbackWidgetListInput (src/preload/api.d.ts). */
1722
+ const siteFeedbackWidgetList = z.object({ cwd: sfCwd.optional() }).strict().default({});
1723
+ /** Mirrors SiteFeedbackWidgetUpdateInput (src/preload/api.d.ts). */
1724
+ const siteFeedbackWidgetUpdate = z.object({
1725
+ boxId: sfBoxId,
1726
+ label: sfLabel.optional(),
1727
+ allowedOrigins: sfOrigins.optional(),
1728
+ state: z.enum(['open', 'paused']).optional(),
1729
+ }).strict();
1730
+ /** Mirrors SiteFeedbackWidgetBoxInput (src/preload/api.d.ts). */
1731
+ const siteFeedbackWidgetBox = z.object({ boxId: sfBoxId }).strict();
1732
+ /** Mirrors SiteFeedbackInboxListInput (src/preload/api.d.ts). */
1733
+ const siteFeedbackInboxList = z.object({ cwd: sfCwd, status: sfInboxStatus.optional() }).strict();
1734
+ /** Mirrors SiteFeedbackInboxGetInput (src/preload/api.d.ts). */
1735
+ const siteFeedbackInboxGet = z.object({ cwd: sfCwd, hostId: sfHostId }).strict();
1736
+ /** Mirrors SiteFeedbackInboxImageInput (src/preload/api.d.ts). */
1737
+ const siteFeedbackInboxImage = z.object({ cwd: sfCwd, hostId: sfHostId, which: z.enum(['screenshot', 'annotated']).optional() }).strict();
1738
+ /** Mirrors SiteFeedbackInboxSetStatusInput (src/preload/api.d.ts). */
1739
+ const siteFeedbackInboxSetStatus = z.object({
1740
+ cwd: sfCwd, hostId: sfHostId, status: sfInboxStatus, note: z.string().max(500).nullable().optional(),
1741
+ }).strict();
1742
+ /** Mirrors SiteFeedbackInboxLinkEpicInput (src/preload/api.d.ts). */
1743
+ const siteFeedbackInboxLinkEpic = z.object({
1744
+ cwd: sfCwd, hostId: sfHostId, epicId: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/),
1745
+ }).strict();
1746
+ const siteFeedbackDrainNow = z.object({}).strict().optional();
1747
+
1748
+ // ──────────────────────────────────────────── Artifacts store + Epic worktrees (lib/epic/artifactIpc.cjs)
1749
+ // Read-only; .strict() so nothing but the project cwd crosses the bridge.
1750
+ const artifactsList = z.object({ cwd: z.string().min(1).max(4096) }).strict();
1751
+ const artifactsWorktrees = z.object({ cwd: z.string().min(1).max(4096) }).strict();
1752
+
1625
1753
  /**
1626
1754
  * Wrap an IPC handler with schema validation. Returns a new handler that
1627
1755
  * parses the payload before calling the original. On invalid payload throws
@@ -1721,6 +1849,11 @@ module.exports = {
1721
1849
  webRemoteRevokeDevice,
1722
1850
  webRemoteAuditTail,
1723
1851
  webRemoteConfirmSas,
1852
+ webRemoteServicePairStart,
1853
+ webRemoteServiceConfirmSas,
1854
+ webRemoteServicePairCancel,
1855
+ webRemoteServiceRevoke,
1856
+ webRemoteRelayClientRevoke,
1724
1857
  sessionSubscribe,
1725
1858
  ptySpawn,
1726
1859
  ptyTabId,
@@ -1824,6 +1957,8 @@ module.exports = {
1824
1957
  promptSessionsListRestorableRecent,
1825
1958
  promptSessionsCreateWorktree,
1826
1959
  promptSessionsReopen,
1960
+ epicRefreshAgentSnapshot,
1961
+ epicPurge,
1827
1962
  promptSessionsCwd,
1828
1963
  promptSessionsReadArchived,
1829
1964
  promptSessionsReadSessionTranscript,
@@ -1869,8 +2004,14 @@ module.exports = {
1869
2004
  projectVideosReviewList,
1870
2005
  projectVideosReviewDecide,
1871
2006
  projectVideosReviewRetry,
2007
+ voicesList,
2008
+ voicesPreview,
2009
+ voicesApprove,
2010
+ voicesUnapprove,
2011
+ voicesDelete,
1872
2012
  needsYouList,
1873
2013
  needsYouAnswer,
2014
+ schedulerConfirmTool,
1874
2015
  agentsGetPersonaBody,
1875
2016
  agentsResolveModelInfo,
1876
2017
  modelsCatalog,
@@ -1885,6 +2026,18 @@ module.exports = {
1885
2026
  customerFeedbackInboxSetStatus,
1886
2027
  customerFeedbackInboxLinkEpic,
1887
2028
  customerFeedbackInboxImage,
2029
+ siteFeedbackWidgetCreate,
2030
+ siteFeedbackWidgetList,
2031
+ siteFeedbackWidgetUpdate,
2032
+ siteFeedbackWidgetBox,
2033
+ siteFeedbackInboxList,
2034
+ siteFeedbackInboxGet,
2035
+ siteFeedbackInboxImage,
2036
+ siteFeedbackInboxSetStatus,
2037
+ siteFeedbackInboxLinkEpic,
2038
+ siteFeedbackDrainNow,
2039
+ artifactsList,
2040
+ artifactsWorktrees,
1888
2041
  },
1889
2042
  validated,
1890
2043
  };
@@ -1,6 +1,6 @@
1
1
  # src/main/lib/ — scoped context
2
2
 
3
- Shared main-process helpers (CommonJS `.cjs`). Layout source of truth: `scripts/lib-layout.json`.
3
+ Shared main-process helpers (CommonJS `.cjs`). `scripts/lib-layout.json` maps top-level lib modules only: a module inside an existing subfolder needs no entry, and listing the file in a PRD's files makes that PRD wait for every other PRD that lists it.
4
4
 
5
5
  ## What's here
6
6
 
@@ -121,6 +121,8 @@ async function recoverInflightTurns(deps) {
121
121
  await ledger.end(sessionId);
122
122
  run({
123
123
  tabId, sessionId, cwd, prompt: CONTINUE_PROMPT, resume: true,
124
+ // Marks the re-send as automation: chatRunner.recordHumanMessage never logs it as human.message.
125
+ bootRecovery: true,
124
126
  ...(entry.promptId ? { promptId: entry.promptId } : {}),
125
127
  ...(entry.origin ? { origin: entry.origin } : {}),
126
128
  ...(entry.worktreeDirHint ? { worktreeDirHint: entry.worktreeDirHint } : {}),
@@ -236,47 +236,69 @@ function buildPersonaBodyText(rawBody, personaPath, { uncapped = false } = {}) {
236
236
  return `${truncated}\n\n[Truncated — ${pathLabel} exceeds ${AGENT_BODY_CHAR_CAP} characters; see the file for the full body.]`;
237
237
  }
238
238
 
239
+ /** The persona a PRD with no `agentType` runs as — same default prdAgentType.cjs documents. */
240
+ const DEFAULT_PRD_AGENT_TYPE = 'dev-lead';
241
+
239
242
  /**
240
243
  * Resolves the persona system-prompt + model a scheduled PRD's `agentType`
241
- * should launch its headless `claude -p` spawn with. Never throws — a
242
- * missing agentType, or one that no longer resolves to a readable persona
243
- * file (renamed/deleted), falls back to `{ systemPrompt: null, model:
244
- * fallbackModel, personaPath: null }` and logs once via prdAgentType.cjs's
245
- * reportDanglingAgentTypeOnce (the PRD-frontmatter FK's own dangling-read
246
- * convention) — a dangling persona must never park or fail the job.
244
+ * should launch its headless `claude -p` spawn with. A null/absent agentType
245
+ * resolves as 'dev-lead'.
246
+ *
247
+ * REFUSAL, not fallback (Managed Agents C-rule "an agent definition is
248
+ * validated"): when the persona is missing, unreadable, or its frontmatter
249
+ * fails personaFrontmatterSchema.cjs's validatePersonaFrontmatter, this
250
+ * returns `{ refusal: { code: 'persona_missing'|'persona_invalid', detail },
251
+ * model: null, systemPrompt: null, personaPath, tools: null }` — the scheduler
252
+ * parks the job instead of spawning it as "no persona + sonnet". A dangling
253
+ * agentType is still logged once via prdAgentType.cjs's
254
+ * reportDanglingAgentTypeOnce (the read-time log). Never throws.
247
255
  *
248
256
  * Reuses agentLibrary.cjs's getPersonaBody (project-overlay-then-global
249
- * read, same precedence resolvePersonaPaths documents) rather than a second
250
- * persona-file reader, and this module's own frontmatter-stripped-body cap
251
- * (mirroring epicIntake.ts's Epic-path treatment) so the PRD path gets the
252
- * same runaway-file protection.
257
+ * read) and this module's frontmatter-stripped-body cap.
253
258
  *
254
- * @param {{ cwd: string, agentType: string|null, fallbackModel?: string, deps?: object }} opts
255
- * @returns {Promise<{ model: string, systemPrompt: string|null, personaPath: string|null, tools: string[]|null }>}
259
+ * @param {{ cwd: string, agentType: string|null, deps?: object }} opts
260
+ * @returns {Promise<{ model: string|null, systemPrompt: string|null, personaPath: string|null, tools: string[]|null, refusal: null|{ code: 'persona_missing'|'persona_invalid', detail: string } }>}
256
261
  */
257
- async function resolvePrdPersonaForSpawn({ cwd, agentType, fallbackModel = FALLBACK_MODEL, deps = {} } = {}) {
258
- const miss = { model: fallbackModel, systemPrompt: null, personaPath: null, tools: null };
259
- if (!agentType) return miss;
262
+ async function resolvePrdPersonaForSpawn({ cwd, agentType, deps = {} } = {}) {
263
+ const name = agentType || DEFAULT_PRD_AGENT_TYPE;
264
+ const refuse = (code, detail, personaPath = null) => ({
265
+ model: null, systemPrompt: null, personaPath, tools: null, refusal: { code, detail },
266
+ });
267
+ let persona;
260
268
  try {
261
269
  const getBody = deps.getPersonaBody || require('../../agentLibrary.cjs').getPersonaBody;
262
- const persona = await getBody({ cwd, name: agentType });
263
- if (!persona) {
270
+ persona = await getBody({ cwd, name });
271
+ } catch (err) {
272
+ const msg = err && err.message ? err.message : String(err);
273
+ return refuse('persona_missing', `agentType '${name}' persona could not be read: ${msg}`);
274
+ }
275
+ if (!persona) {
276
+ try {
264
277
  const reportOnce = deps.reportDanglingAgentTypeOnce || require('../prd/prdAgentType.cjs').reportDanglingAgentTypeOnce;
265
- reportOnce(cwd, agentType, deps);
266
- return miss;
267
- }
278
+ reportOnce(cwd, name, deps);
279
+ } catch { /* the read-time log must never change the result */ }
280
+ return refuse('persona_missing', `agentType '${name}' does not resolve to a readable persona file`);
281
+ }
282
+ try {
268
283
  // getPersonaBody returns the MERGED persona (fm + body); a bare `{ path, text }`
269
284
  // (older injected reader) is parsed here.
270
285
  const { fm, body } = persona.fm ? persona : splitFrontmatter(persona.text);
271
- const model = fm.model && fm.model !== 'inherit' ? fm.model : fallbackModel;
286
+ const validate = deps.validatePersonaFrontmatter
287
+ || require('../persona-macro/personaFrontmatterSchema.cjs').validatePersonaFrontmatter;
288
+ const check = validate(fm);
289
+ if (!check.ok) {
290
+ return refuse('persona_invalid', `agentType '${name}' persona ${persona.path || '(unknown path)'} frontmatter is invalid: ${check.errors.join('; ')}`, persona.path || null);
291
+ }
292
+ const model = String(fm.model).trim();
272
293
  const digest = shippedBodyHash(body);
273
- const uncapped = (SHIPPED_PERSONA_SEEDS[agentType] || []).some((e) => e.bodySha256 === digest);
294
+ const uncapped = (SHIPPED_PERSONA_SEEDS[name] || []).some((e) => e.bodySha256 === digest);
274
295
  const systemPrompt = buildPersonaBodyText(body, persona.path, { uncapped });
275
296
  const parseTools = deps.parseTools || require('../../agentLibrary.cjs').parseTools;
276
297
  const list = parseTools(typeof fm.tools === 'string' ? fm.tools : '');
277
- return { model, systemPrompt, personaPath: persona.path, tools: list.length ? list : null };
278
- } catch {
279
- return miss;
298
+ return { model, systemPrompt, personaPath: persona.path, tools: list.length ? list : null, refusal: null };
299
+ } catch (err) {
300
+ const msg = err && err.message ? err.message : String(err);
301
+ return refuse('persona_invalid', `agentType '${name}' persona ${persona.path || '(unknown path)'} could not be parsed: ${msg}`, persona.path || null);
280
302
  }
281
303
  }
282
304
 
@@ -293,4 +315,8 @@ module.exports = {
293
315
  readOverlayAwarePersona,
294
316
  isProjectOverlayPersonaPath,
295
317
  resolvePrdPersonaForSpawn,
318
+ DEFAULT_PRD_AGENT_TYPE,
319
+ // The frontmatter parser dispatch validates personas with — re-exported so
320
+ // tests parse tracked personas the same way (trackedPersonasValid.test.cjs).
321
+ splitFrontmatter,
296
322
  };
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * agentSnapshot.cjs — the immutable AgentSnapshot (Managed Agents' versioned
5
+ * agent), stored locally and content-addressed.
6
+ *
7
+ * A snapshot freezes exactly the agent definition a run used:
8
+ * { name, bodySha256, body, model, effort, tools, mcpServers, packs, seedVersion, environment }
9
+ * Its id is the sha256 of its canonical JSON (keys sorted at every depth), so
10
+ * equal definitions share one id and any edit (body, model, tools, ...) mints
11
+ * a new one. A resume can therefore re-run precisely the definition it pinned.
12
+ *
13
+ * Store: session-manager-operations/agents/snapshots/<id>.json, written ONCE
14
+ * (an existing id is a no-op) via util/atomicFs.cjs, writer 'agents'
15
+ * (opsOwnership.cjs). Reads re-hash the file: a missing, unparsable or
16
+ * tampered (hash != id) file reads as null.
17
+ *
18
+ * No second persona reader: the body/model/tools come from
19
+ * agentModelResolve.cjs's resolvePrdPersonaForSpawn (its refusal is passed
20
+ * through unchanged), effort from agentEffortResolve.cjs's resolveEpicEffort,
21
+ * seedVersion from agentModelResolve.cjs's readOverlayAwarePersona (the same
22
+ * merged-persona reader resolveEpicEffort uses).
23
+ *
24
+ * mcpServers = the server names named by the persona's mcp__<server>__<tool>
25
+ * tools (personaToolScope.cjs's naming rule) until personas declare servers.
26
+ *
27
+ * environment = { id, hash } of the persona's `environment:` profile
28
+ * (environmentProfiles.cjs's loadEnvironment; absent = headless-default), so
29
+ * an edit to the profile file mints a new snapshot. An unknown or invalid
30
+ * profile is refused ({ code: 'environment_unknown'|'environment_invalid' }).
31
+ *
32
+ * Not wired into dispatch here (ma-agent-snapshot-pin-dispatch does that).
33
+ */
34
+
35
+ const crypto = require('node:crypto');
36
+ const fsp = require('node:fs/promises');
37
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
38
+ const atomicFs = require('../util/atomicFs.cjs');
39
+
40
+ const WRITER = 'agents';
41
+ const ID_RE = /^[0-9a-f]{64}$/;
42
+
43
+ const sha256 = (s) => crypto.createHash('sha256').update(String(s)).digest('hex');
44
+
45
+ /** JSON with object keys sorted at every depth; arrays keep their order. */
46
+ function canonicalJson(value) {
47
+ if (value === null || typeof value !== 'object') return JSON.stringify(value === undefined ? null : value);
48
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
49
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
50
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
51
+ }
52
+
53
+ /** Content address of a snapshot: sha256 of its canonical JSON. */
54
+ function snapshotId(snap) {
55
+ return sha256(canonicalJson(snap));
56
+ }
57
+
58
+ /** Server names from mcp__<server>__<tool> entries (personaToolScope.cjs rule), sorted + unique. */
59
+ function mcpServersFromTools(tools) {
60
+ if (!Array.isArray(tools)) return [];
61
+ const names = new Set();
62
+ for (const t of tools.map(String)) {
63
+ if (!t.startsWith('mcp__')) continue;
64
+ const server = t.slice(5).split('__')[0];
65
+ if (server) names.add(server);
66
+ }
67
+ return [...names].sort();
68
+ }
69
+
70
+ /** The persona's seedVersion stamp as an integer, or null when absent/invalid. */
71
+ function seedVersionOf(fm) {
72
+ const raw = fm && fm.seedVersion;
73
+ if (raw === undefined || raw === null || raw === '') return null;
74
+ const n = Number(raw);
75
+ return Number.isInteger(n) && n >= 0 ? n : null;
76
+ }
77
+
78
+ /**
79
+ * Build (do not write) the snapshot for `agentType` in `cwd`.
80
+ * @param {{ cwd: string, agentType?: string|null, packs?: string[], deps?: object }} opts
81
+ * @returns {Promise<{ id: string|null, snapshot: object|null, refusal: null|{ code: string, detail: string } }>}
82
+ * On a persona refusal: { id: null, snapshot: null, refusal } (passed through unchanged).
83
+ */
84
+ async function buildAgentSnapshot({ cwd, agentType, packs, deps = {} } = {}) {
85
+ const modelResolve = require('./agentModelResolve.cjs');
86
+ const resolvePersona = deps.resolvePrdPersonaForSpawn || modelResolve.resolvePrdPersonaForSpawn;
87
+ const resolveEffort = deps.resolveEpicEffort || require('./agentEffortResolve.cjs').resolveEpicEffort;
88
+ const readPersona = deps.readOverlayAwarePersona || modelResolve.readOverlayAwarePersona;
89
+ const name = agentType || modelResolve.DEFAULT_PRD_AGENT_TYPE;
90
+
91
+ const resolved = await resolvePersona({ cwd, agentType: name, deps });
92
+ if (resolved.refusal) return { id: null, snapshot: null, refusal: resolved.refusal };
93
+
94
+ const { effort } = resolveEffort({ cwd, agentType: name, deps });
95
+ let seedVersion = null;
96
+ let fm = null;
97
+ try { fm = (readPersona(name, { ...deps, cwd }) || {}).fm || null; } catch { /* stays null */ }
98
+ seedVersion = seedVersionOf(fm);
99
+
100
+ const loadEnvironment = deps.loadEnvironment || require('./environmentProfiles.cjs').loadEnvironment;
101
+ const envName = fm && typeof fm.environment === 'string' && fm.environment.trim() ? fm.environment.trim() : null;
102
+ const env = loadEnvironment({ cwd, name: envName });
103
+ if (env.code) {
104
+ const detail = env.code === 'environment_invalid'
105
+ ? `environment "${env.name}" is invalid (${env.file}): ${(env.errors || []).join('; ')}`
106
+ : `environment "${env.name}" is not declared (no project, global or built-in profile)`;
107
+ return { id: null, snapshot: null, refusal: { code: env.code, detail } };
108
+ }
109
+
110
+ const body = resolved.systemPrompt || '';
111
+ const tools = Array.isArray(resolved.tools) ? resolved.tools.map(String) : null;
112
+ const snapshot = {
113
+ name,
114
+ bodySha256: sha256(body),
115
+ body,
116
+ model: resolved.model || null,
117
+ effort: effort || null,
118
+ tools,
119
+ mcpServers: mcpServersFromTools(tools),
120
+ packs: Array.isArray(packs) ? packs.map(String) : [],
121
+ seedVersion,
122
+ environment: { id: env.id, hash: env.hash },
123
+ };
124
+ return { id: snapshotId(snapshot), snapshot, refusal: null };
125
+ }
126
+
127
+ function snapshotFile(cwd, id) {
128
+ if (typeof id !== 'string' || !ID_RE.test(id)) throw new Error(`agentSnapshot: invalid snapshot id "${id}"`);
129
+ return opsPath(cwd, 'agents', 'snapshots', `${id}.json`);
130
+ }
131
+
132
+ /**
133
+ * Write `snap` once under its content id. An existing id is a no-op.
134
+ * @returns {Promise<{ id: string, written: boolean, path: string }>}
135
+ */
136
+ async function writeAgentSnapshot(cwd, snap) {
137
+ if (!snap || typeof snap !== 'object' || Array.isArray(snap)) throw new Error('agentSnapshot: snapshot object required');
138
+ const id = snapshotId(snap);
139
+ const file = snapshotFile(cwd, id);
140
+ try {
141
+ await fsp.access(file);
142
+ return { id, written: false, path: file };
143
+ } catch { /* absent — write it */ }
144
+ assertOpsWrite(file, WRITER);
145
+ await atomicFs.writeTextAtomic(file, `${canonicalJson(snap)}\n`);
146
+ return { id, written: true, path: file };
147
+ }
148
+
149
+ /**
150
+ * Read snapshot `id`. Missing, unparsable or tampered (re-hash != id) → null.
151
+ * @returns {Promise<object|null>}
152
+ */
153
+ async function readAgentSnapshot(cwd, id) {
154
+ let file;
155
+ try { file = snapshotFile(cwd, id); } catch { return null; }
156
+ let parsed;
157
+ try { parsed = JSON.parse(await fsp.readFile(file, 'utf8')); } catch { return null; }
158
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
159
+ return snapshotId(parsed) === id ? parsed : null;
160
+ }
161
+
162
+ /**
163
+ * Sync twin of readAgentSnapshot, same rules (missing/unparsable/tampered → null).
164
+ * For epicSpawnPlan.cjs's planEpicSpawn, which must stay synchronous (chatRunner.cjs
165
+ * registers its cancel handle in the same tick — see agentModelResolve.cjs's
166
+ * readOverlayAwarePersona note).
167
+ * @returns {object|null}
168
+ */
169
+ function readAgentSnapshotSync(cwd, id) {
170
+ let file;
171
+ try { file = snapshotFile(cwd, id); } catch { return null; }
172
+ let parsed;
173
+ try { parsed = JSON.parse(require('node:fs').readFileSync(file, 'utf8')); } catch { return null; }
174
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
175
+ return snapshotId(parsed) === id ? parsed : null;
176
+ }
177
+
178
+ module.exports = {
179
+ buildAgentSnapshot,
180
+ writeAgentSnapshot,
181
+ readAgentSnapshot,
182
+ readAgentSnapshotSync,
183
+ snapshotId,
184
+ canonicalJson,
185
+ mcpServersFromTools,
186
+ };