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
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+ // The one list of loopback admin routes the app registers. index.cjs calls
3
+ // registerAppAdminRoutes once at boot; tests call it with a recording fake to see
4
+ // exactly what the running app serves. Every module is required INSIDE the
5
+ // function, so requiring this file has no side effect.
6
+
7
+ /**
8
+ * @param {{ registerRoute: Function }} adminHttp
9
+ * @param {{ onMacrosChanged?: Function, onNeedsYouChanged?: Function }} [deps]
10
+ */
11
+ function registerAppAdminRoutes(adminHttp, deps = {}) {
12
+ const scheduler = require('./scheduler.cjs');
13
+ const chatRunner = require('./chatRunner.cjs');
14
+ scheduler.registerAdminRoutes(adminHttp);
15
+ // GET/POST /admin/scheduler/slots — read the slot cap; change it only on the human's verified words.
16
+ require('./lib/scheduler/slotsRoute.cjs').registerSlotsRoute(adminHttp);
17
+ require('./lib/prd/prdCreate.cjs').registerAdminRoute(adminHttp, scheduler.remote);
18
+ require('./lib/prd/prdAdminRoutes.cjs').registerAdminRoute(adminHttp, scheduler.remote);
19
+ require('./lib/feedback-remote/projectHomeAdminRoutes.cjs').registerAdminRoute(adminHttp);
20
+ // GET /admin/voices + POST /admin/voices/preview — voice library reads for agents; no route changes a voice.
21
+ require('./lib/project-pages/voiceAdminRoutes.cjs').registerAdminRoute(adminHttp);
22
+ require('./lib/feedback-remote/macroAdminRoutes.cjs').registerAdminRoute(adminHttp, {
23
+ onChanged: deps.onMacrosChanged,
24
+ startExternalNewSession: chatRunner.startExternalNewSession,
25
+ isTabBusy: chatRunner.isTabBusy,
26
+ });
27
+ chatRunner.registerAdminRoute(adminHttp);
28
+ // Outside apps' "Needs you" items (lib/feedback-remote/needsYouStore.cjs); changes broadcast `needsYou:changed`.
29
+ require('./lib/feedback-remote/needsYouAdminRoutes.cjs').registerAdminRoute(adminHttp, {
30
+ onChanged: deps.onNeedsYouChanged,
31
+ });
32
+ // Project-to-project feedback conduit — the app is the only process holding
33
+ // several projects' operations roots open, so it performs the cross-folder
34
+ // write (lib/feedback-remote/crossProjectFeedback.cjs).
35
+ require('./lib/feedback-remote/crossProjectFeedback.cjs').registerAdminRoute(adminHttp);
36
+ // Its return leg: the receiving session answers INTO the Epic that asked
37
+ // (lib/feedback-remote/crossProjectReply.cjs).
38
+ require('./lib/feedback-remote/crossProjectReply.cjs').registerAdminRoute(adminHttp);
39
+ require('./lib/feedback-remote/customerFeedbackAdminRoutes.cjs').registerAdminRoute(adminHttp);
40
+ // Website-feedback widgets + their decrypted inbox, behind the Feedback MCP tools.
41
+ require('./lib/feedback-remote/siteFeedbackAdminRoutes.cjs').registerAdminRoute(adminHttp);
42
+ // Per-project Artifacts store (publish + list), behind the artifact MCP tool.
43
+ require('./lib/epic/artifactAdminRoutes.cjs').registerAdminRoute(adminHttp);
44
+ // Cursor read over the audit log for outside scripts (read-only).
45
+ require('./lib/telemetry/eventsAdminRoutes.cjs').registerAdminRoute(adminHttp);
46
+ // Outside-facing Epic records for scripts/other projects (read-only).
47
+ require('./lib/epic/epicAdminRoutes.cjs').registerAdminRoute(adminHttp, {
48
+ isTabBusy: chatRunner.isTabBusy,
49
+ listJobs: () => scheduler.remote.listJobRows(),
50
+ });
51
+ // Validator quality numbers per project for outside callers (read-only).
52
+ require('./validationQualityHandlers.cjs').registerAdminRoute(adminHttp);
53
+ // Persona roster + per-project effective model/effort for outside apps (read-only).
54
+ require('./lib/persona-macro/agentAdminRoutes.cjs').registerAdminRoute(adminHttp);
55
+ // Task primitive: one headless claude -p run for a project, under the slot cap (POST /admin/tasks).
56
+ require('./lib/tasks/taskAdminRoutes.cjs').registerAdminRoute(adminHttp);
57
+ }
58
+
59
+ module.exports = { registerAppAdminRoutes };
@@ -33,6 +33,24 @@ function parseTools(raw) {
33
33
  return raw.split(',').map((t) => t.trim()).filter(Boolean);
34
34
  }
35
35
 
36
+ /**
37
+ * A declared-capability frontmatter value (`mcpServers:` / `packs:`) as a
38
+ * list: a comma string ("a, b") or a string list (structured callers).
39
+ * Trimmed, deduped, order-preserving; anything else → [].
40
+ * @param {unknown} raw
41
+ * @returns {string[]}
42
+ */
43
+ function parseCapabilityList(raw) {
44
+ const items = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(',') : [];
45
+ const out = [];
46
+ for (const it of items) {
47
+ if (typeof it !== 'string') continue;
48
+ const v = it.trim();
49
+ if (v && !out.includes(v)) out.push(v);
50
+ }
51
+ return out;
52
+ }
53
+
36
54
  /** Sentinel `projects:` entry meaning "this agent's Action button shows in every project". */
37
55
  const ALL_PROJECTS = '*';
38
56
 
@@ -75,8 +93,18 @@ function decodeLine(s) {
75
93
  *
76
94
  * `agentCli` / `agentCliModel` are this app's extension too: the persona's
77
95
  * default agent CLI (and its model) for New Session — Claude Code ignores them.
96
+ *
97
+ * `mcpServers` / `packs` are the persona's declared capabilities (comma
98
+ * lists): the exact MCP servers and context packs a scheduler job running as
99
+ * this persona loads (personaToolScope.cjs passes them under
100
+ * --strict-mcp-config; an unknown name parks the job). The Agent Library form
101
+ * has no field for them, so savePersona carries the file's values over.
102
+ *
103
+ * `environment` names the persona's declared environment profile
104
+ * (lib/claude/environmentProfiles.cjs; absent = headless-default). Same
105
+ * carry-over rule as mcpServers/packs.
78
106
  */
79
- const MANAGED_PERSONA_KEYS = new Set(['name', 'description', 'tools', 'model', 'effort', 'color', 'tags', 'projects', 'action', 'actionLabel', 'title', 'seedVersion', 'executorOnly', 'agentCli', 'agentCliModel']);
107
+ const MANAGED_PERSONA_KEYS = new Set(['name', 'description', 'tools', 'model', 'effort', 'color', 'tags', 'projects', 'action', 'actionLabel', 'title', 'seedVersion', 'executorOnly', 'agentCli', 'agentCliModel', 'mcpServers', 'packs', 'environment']);
80
108
 
81
109
  /**
82
110
  * Raw text lines of every top-level frontmatter key block in `raw` whose key
@@ -97,7 +125,7 @@ function extractUnmanagedLines(raw, managed) {
97
125
  return out;
98
126
  }
99
127
 
100
- function serializePersona({ name, description, tools, model, effort, color, tags, projects, action, actionLabel, title, seedVersion, executorOnly, agentCli, agentCliModel, body, preservedLines }) {
128
+ function serializePersona({ name, description, tools, model, effort, color, tags, projects, action, actionLabel, title, seedVersion, executorOnly, agentCli, agentCliModel, mcpServers, packs, environment, body, preservedLines }) {
101
129
  const lines = ['---', `name: ${name}`];
102
130
  if (description) lines.push(`description: ${description}`);
103
131
  if (tools && tools.length) lines.push(`tools: ${tools.join(', ')}`);
@@ -116,6 +144,9 @@ function serializePersona({ name, description, tools, model, effort, color, tags
116
144
  if (title) lines.push(`title: ${title}`);
117
145
  if (typeof seedVersion === 'number' && Number.isFinite(seedVersion)) lines.push(`seedVersion: ${seedVersion}`);
118
146
  if (executorOnly === true) lines.push('executorOnly: true');
147
+ if (Array.isArray(mcpServers) && mcpServers.length) lines.push(`mcpServers: ${mcpServers.join(', ')}`);
148
+ if (Array.isArray(packs) && packs.length) lines.push(`packs: ${packs.join(', ')}`);
149
+ if (typeof environment === 'string' && environment.trim()) lines.push(`environment: ${environment.trim()}`);
119
150
  if (Array.isArray(preservedLines) && preservedLines.length) lines.push(...preservedLines);
120
151
  lines.push('---', '');
121
152
  return lines.join('\n') + (body || '').trim() + '\n';
@@ -196,6 +227,31 @@ async function saveOverlay({ name, projectCwd, model, effort, loadSessions, vali
196
227
  return { ok: true, path: target };
197
228
  }
198
229
 
230
+ /**
231
+ * Throws (before anything is written) when the persona text about to be
232
+ * written fails validatePersonaFrontmatter, naming every failing key. The
233
+ * checked object is the frontmatter as it will land on disk — managed keys
234
+ * re-parsed from the serialized text, plus every preserved unmanaged key
235
+ * (an unmanaged key is by definition unknown to the schema, so it fails).
236
+ * Required lazily: personaFrontmatterSchema.cjs imports MANAGED_PERSONA_KEYS
237
+ * from this module.
238
+ * @param {string} name
239
+ * @param {string} text
240
+ * @param {string[]} preservedLines
241
+ */
242
+ function assertValidPersonaText(name, text, preservedLines) {
243
+ const { validatePersonaFrontmatter } = require('./lib/persona-macro/personaFrontmatterSchema.cjs');
244
+ const fm = { ...splitFrontmatter(text).fm };
245
+ for (const line of preservedLines) {
246
+ const m = line.match(/^([A-Za-z][A-Za-z0-9_-]*)\s*:/);
247
+ if (m && !(m[1] in fm)) fm[m[1]] = '';
248
+ }
249
+ const result = validatePersonaFrontmatter(fm);
250
+ if (!result.ok) {
251
+ throw new Error(`invalid persona frontmatter for ${name}: ${result.errors.join('; ')}`);
252
+ }
253
+ }
254
+
199
255
  /**
200
256
  * Writes a global persona `.md` file — `~/.claude/agents/<name>.md`. Pass
201
257
  * `originalName` when renaming an existing persona so the old file is
@@ -224,6 +280,9 @@ async function savePersona({
224
280
  executorOnly,
225
281
  agentCli,
226
282
  agentCliModel,
283
+ mcpServers,
284
+ packs,
285
+ environment,
227
286
  body,
228
287
  projectCwd,
229
288
  globalDir = path.join(os.homedir(), '.claude', 'agents'),
@@ -253,11 +312,14 @@ async function savePersona({
253
312
  // agentCli undefined = carry the file's pair over; 'claude' (or any non-CLI value) = write neither line.
254
313
  let resolvedAgentCli = agentCli;
255
314
  let resolvedAgentCliModel = agentCliModel;
315
+ let resolvedMcpServers = mcpServers;
316
+ let resolvedPacks = packs;
317
+ let resolvedEnvironment = environment;
256
318
  let preservedLines = [];
257
319
  try {
258
320
  preservedLines = extractUnmanagedLines(fsSync.readFileSync(target, 'utf8'), MANAGED_PERSONA_KEYS);
259
321
  } catch { /* no existing file — nothing to preserve */ }
260
- if ([seedVersion, title, projects, action, actionLabel, executorOnly, agentCli].some((v) => v === undefined)) {
322
+ if ([seedVersion, title, projects, action, actionLabel, executorOnly, agentCli, mcpServers, packs, environment].some((v) => v === undefined)) {
261
323
  try {
262
324
  const { fm } = splitFrontmatter(fsSync.readFileSync(target, 'utf8'));
263
325
  if (resolvedSeedVersion === undefined) {
@@ -274,9 +336,13 @@ async function savePersona({
274
336
  if (resolvedProjects === undefined && fm.projects) resolvedProjects = parseTools(fm.projects);
275
337
  if (resolvedAction === undefined && fm.action) resolvedAction = decodeLine(fm.action);
276
338
  if (resolvedActionLabel === undefined && fm.actionLabel) resolvedActionLabel = decodeLine(fm.actionLabel);
339
+ if (resolvedMcpServers === undefined && fm.mcpServers) resolvedMcpServers = parseCapabilityList(fm.mcpServers);
340
+ if (resolvedPacks === undefined && fm.packs) resolvedPacks = parseCapabilityList(fm.packs);
341
+ if (resolvedEnvironment === undefined && typeof fm.environment === 'string' && fm.environment.trim()) resolvedEnvironment = fm.environment.trim();
277
342
  } catch { /* no existing file (or unreadable) — nothing to carry over */ }
278
343
  }
279
- const text = serializePersona({ name, description, tools, model, effort, color, tags, projects: resolvedProjects, action: resolvedAction, actionLabel: resolvedActionLabel, title: resolvedTitle, seedVersion: resolvedSeedVersion, executorOnly: resolvedExecutorOnly, agentCli: resolvedAgentCli, agentCliModel: resolvedAgentCliModel, body, preservedLines });
344
+ const text = serializePersona({ name, description, tools, model, effort, color, tags, projects: resolvedProjects, action: resolvedAction, actionLabel: resolvedActionLabel, title: resolvedTitle, seedVersion: resolvedSeedVersion, executorOnly: resolvedExecutorOnly, agentCli: resolvedAgentCli, agentCliModel: resolvedAgentCliModel, mcpServers: resolvedMcpServers, packs: resolvedPacks, environment: resolvedEnvironment, body, preservedLines });
345
+ assertValidPersonaText(name, text, preservedLines);
280
346
  await writeTextAtomic(target, text);
281
347
  if (originalName && originalName !== name) {
282
348
  const oldReal = validatePath(path.join(globalDir, `${originalName}.md`));
@@ -485,4 +551,6 @@ module.exports = {
485
551
  getPersonaBody,
486
552
  PERSONA_NAME_RE,
487
553
  ALL_PROJECTS,
554
+ MANAGED_PERSONA_KEYS,
555
+ parseCapabilityList,
488
556
  };
@@ -63,9 +63,10 @@ function registerAgentsHandlers({ ipcMain, getWindow }) {
63
63
  // (agentModelResolve.cjs's resolveEpicModel), reached here so Terminal's
64
64
  // launch (EpicTerminalPane.tsx, a renderer module with no fs access) agrees
65
65
  // with Chat by calling the identical function rather than a second one that
66
- // is merely supposed to. Never throws (resolveEpicModel's own contract).
66
+ // is merely supposed to. Pinned Epics (agentSnapshotId) read the model from
67
+ // their AgentSnapshot (epicSpawnPlan.cjs's resolveEpicTurnModel). Never throws.
67
68
  ipcMain.handle('agents:resolve-epic-model', validated(schemas.agentsResolveEpicModel, (payload) =>
68
- agentModelResolve.resolveEpicModel(payload)));
69
+ require('./lib/epic/epicSpawnPlan.cjs').resolveEpicTurnModel(payload)));
69
70
  // Effort twin of the above (agentEffortResolve.cjs): Terminal appends
70
71
  // `--effort <level>` only when `effort` is non-null. Never throws.
71
72
  ipcMain.handle('agents:resolve-epic-effort', validated(schemas.agentsResolveEpicEffort, (payload) =>
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.141.0",
3
- "gitSha": "0db73892da43176f003e4495092dfb8283045331",
4
- "gitShortSha": "0db73892",
2
+ "version": "0.142.0",
3
+ "gitSha": "7cc6a105688133e6318bf204efc9dbbc932540c5",
4
+ "gitShortSha": "7cc6a105",
5
5
  "gitBranch": "HEAD",
6
- "builtAt": "2026-11-23T02:26:13.633Z",
6
+ "builtAt": "2026-11-24T16:38:14.867Z",
7
7
  "dirty": false
8
8
  }
@@ -19,6 +19,8 @@ const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
19
19
  * — pure parser for `/context`
20
20
  * STOP_SENTINEL: string — exported for tests
21
21
  * __setExecutor(fn): void — test seam
22
+ * recordNeedsInput / recordAnswerIfOpen — Epic event log: job.needs_input
23
+ * on a stop-signal turn, human.answer on the reply
22
24
  *
23
25
  * IPC events broadcast to the renderer:
24
26
  * chat:run:queued { tabId, sessionId, position } — waiting behind a busy lane
@@ -39,9 +41,9 @@ const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
39
41
  const { spawn } = require('node:child_process');
40
42
  const { ipcMain } = require('electron');
41
43
  const { resolveClaudeBin, claudeSpawnTarget } = require('./lib/claude/claudeBin.cjs');
42
- const { cleanChildEnv, pathWithUserBins } = require('./lib/process/cleanEnv.cjs');
44
+ const { cleanChildEnv, pathWithUserBins, assertNoCredentials } = require('./lib/process/cleanEnv.cjs');
43
45
  const { recordExchange, formatAskedResult } = require('./exchanges.cjs');
44
- const { classifyToolUse } = require('./lib/toolUseClassify.cjs');
46
+ const { classifyToolUse, humanMessageSummary } = require('./lib/toolUseClassify.cjs');
45
47
  const { extractJson } = require('./lib/util/extractJson.cjs');
46
48
  const { classifyPromptTicket } = require('./lib/classifyPromptTicket.cjs');
47
49
  const sessionSlots = require('./lib/scheduler/sessionSlots.cjs');
@@ -53,7 +55,7 @@ const { developLoopOffSettingsArgs } = require('./lib/epic/developLoopSpawn.cjs'
53
55
  // Called through the module object (not destructured) so tests can inject a catalog.
54
56
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
55
57
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
56
- const { planEpicSpawn } = require('./lib/epic/epicSpawnPlan.cjs');
58
+ const { planEpicSpawn, resolveEpicTurnModel } = require('./lib/epic/epicSpawnPlan.cjs');
57
59
  const epicWorktreeMint = require('./lib/epic/epicWorktreeMint.cjs');
58
60
  const logs = require('./logs.cjs');
59
61
  const chatInflight = require('./lib/chatInflight.cjs');
@@ -63,6 +65,10 @@ const { createHeadTailBuffer } = require('./lib/util/headTailBuffer.cjs');
63
65
  const { isNonClaudeAgentCli } = require('./lib/agent-cli/agentCliEvents.cjs');
64
66
  const { planAgentCliTurn } = require('./lib/agent-cli/agentCliTurn.cjs');
65
67
  const { writeNativeSession } = require('./lib/agent-cli/agentCliSessionStore.cjs');
68
+ // Module object (not destructured) so tests can stub the append.
69
+ const epicEventLog = require('./lib/epic/epicEventLog.cjs');
70
+ const artifactStore = require('./lib/epic/artifactStore.cjs');
71
+ const { postArtifactReadyNotice } = require('./lib/epic/artifactNotice.cjs');
66
72
 
67
73
  // Caps on per-run stream buffers (a run can last hours).
68
74
  const STDERR_TAIL_MAX = 64 * 1024;
@@ -275,8 +281,8 @@ const SCHEDULER_TURN_INSTRUCTION =
275
281
  `IMPORTANT: This turn was started by the scheduler and nobody is watching. ` +
276
282
  `Never ask questions and never print ${STOP_SENTINEL}. Act on the message below with ` +
277
283
  `the /develop skill's Phase 2 rules (reset, fix the spec, archive, or queue a fix wave). ` +
278
- `Make the safest reasonable choice for anything left open, and end with a short report ` +
279
- `of what you did.\n\n`;
284
+ `Give everything left open an outcome (queue, decide, schedule or close it), and end ` +
285
+ `with a short report of what you did.\n\n`;
280
286
 
281
287
  /**
282
288
  * Picks the instruction block that opens a turn: scheduler turns and
@@ -320,9 +326,10 @@ function consumeSchedulerPrompt(tabId, prompt) {
320
326
  }
321
327
 
322
328
  // ─── Hard wall-clock kill ceiling ────────────────────────────────────────
323
- // Defined here (ahead of CHAT_MODE_TRUTH_INSTRUCTION) so the prompt's stated
324
- // budget is always derived from this single constant — never a hand-written
325
- // duplicate that could drift from the real timer below.
329
+ // Defined here (ahead of the relay-note TTL and CHAT_MODE_TRUTH_INSTRUCTION) so
330
+ // the relay TTL and the prompt's stated budget are always derived from this
331
+ // single constant — never a hand-written duplicate that could drift from the
332
+ // real timer below.
326
333
  const KILL_CEILING_MS = 30 * 60 * 1000; // 30 minutes
327
334
  const KILL_CEILING_MIN = KILL_CEILING_MS / 60_000;
328
335
  // 80% warning point — gives the model a turn-visible nudge to wrap up before
@@ -330,6 +337,57 @@ const KILL_CEILING_MIN = KILL_CEILING_MS / 60_000;
330
337
  // re: making KILL_CEILING_MS itself configurable.
331
338
  const WARN_CEILING_MS = Math.floor(KILL_CEILING_MS * 0.8);
332
339
 
340
+ // tab+prompt keys of relayed external sends (Web Remote phone / admin API) awaiting
341
+ // their run(): each entry is a FIFO of relay names, consumed once per EXTERNAL run.
342
+ // A note only lives as long as its send can still produce a run: the ack window,
343
+ // plus the time a 'queued' send waits for the in-flight turn ahead of it (bounded by
344
+ // the kill ceiling). A send that resolves without a run drops its note at once.
345
+ const EXTERNAL_RELAYS = new Set(['web-remote', 'admin-api']);
346
+ const relayPrompts = new Map();
347
+ const EXTERNAL_SEND_ACK_TIMEOUT_MS = 8000;
348
+ const RELAY_RUN_START_WINDOW_MS = KILL_CEILING_MS;
349
+ const RELAY_PROMPT_TTL_MS = EXTERNAL_SEND_ACK_TIMEOUT_MS + RELAY_RUN_START_WINDOW_MS;
350
+ function noteRelayPrompt(tabId, prompt, relay) {
351
+ if (!EXTERNAL_RELAYS.has(relay)) return null;
352
+ const now = Date.now();
353
+ for (const [k, v] of relayPrompts) {
354
+ const live = v.filter((e) => e.expires >= now);
355
+ if (live.length) relayPrompts.set(k, live); else relayPrompts.delete(k);
356
+ }
357
+ const key = `${tabId}\n${prompt}`;
358
+ const list = relayPrompts.get(key) || [];
359
+ const entry = { relay, expires: now + RELAY_PROMPT_TTL_MS };
360
+ list.push(entry);
361
+ relayPrompts.set(key, list);
362
+ return entry;
363
+ }
364
+ // Removes exactly one send's note (by identity) — a same-text note of another send stays.
365
+ function dropRelayPrompt(tabId, prompt, entry) {
366
+ const key = `${tabId}\n${prompt}`;
367
+ const list = relayPrompts.get(key);
368
+ if (!list) return;
369
+ const i = list.indexOf(entry);
370
+ if (i >= 0) list.splice(i, 1);
371
+ if (!list.length) relayPrompts.delete(key);
372
+ }
373
+ function relayNoteCount(tabId, prompt) {
374
+ const now = Date.now();
375
+ return (relayPrompts.get(`${tabId}\n${prompt}`) || []).filter((e) => e.expires >= now).length;
376
+ }
377
+ function consumeRelayPrompt(tabId, prompt) {
378
+ const key = `${tabId}\n${prompt}`;
379
+ const list = relayPrompts.get(key);
380
+ if (!list) return null;
381
+ const now = Date.now();
382
+ let hit = null;
383
+ while (list.length && !hit) {
384
+ const e = list.shift();
385
+ if (e.expires >= now) hit = e.relay;
386
+ }
387
+ if (!list.length) relayPrompts.delete(key);
388
+ return hit;
389
+ }
390
+
333
391
  // Instruction prepended to every prompt. Tells the agent the truth about this
334
392
  // execution mode: this Chat tab is a one-shot headless `claude -p` run — no
335
393
  // process survives after this turn ends, so background shells, scheduled
@@ -346,7 +404,8 @@ const CHAT_MODE_TRUTH_INSTRUCTION =
346
404
  `timeout, then report the actual result. This turn is hard-killed after ` +
347
405
  `${KILL_CEILING_MIN} minutes of wall-clock. Size every synchronous poll to ` +
348
406
  `finish inside that budget; if the work cannot fit, do the part that fits, ` +
349
- `report exactly what landed, and say what remains. End this turn with ` +
407
+ `report exactly what landed, and queue or schedule what remains; only a step ` +
408
+ `that needs the human goes back to them. End this turn with ` +
350
409
  `either a real result or an explicit statement that the user needs to ` +
351
410
  `reply for the work to continue.\n\n`;
352
411
 
@@ -382,6 +441,126 @@ function releaseOrphanSession(sessionId) { orphanSessions.delete(sessionId); pum
382
441
  // flight (tabId → opts). Counted by run()'s tabBusy; cancel() can drop them.
383
442
  const pendingStart = new Map();
384
443
 
444
+ // ─── Epic event log: questions and answers ────────────────────────────────
445
+ // An Epic chat's sessionId IS its Epic id (EPIC : CLI session = 1:1). A run
446
+ // that ends on the stop signal appends job.needs_input (Epic-level: no slug)
447
+ // with the parsed questions; the next human-sent prompt on that session is
448
+ // the answer and appends human.answer. Fire-and-forget: an event-log failure
449
+ // never breaks a chat turn.
450
+
451
+ /** sessionId → { cwd, questions } for a question still waiting on a human. */
452
+ const openQuestions = new Map();
453
+
454
+ function appendChatEpicEvent(cwd, epicId, event) {
455
+ if (typeof cwd !== 'string' || !cwd || typeof epicId !== 'string' || !epicId) return Promise.resolve(null);
456
+ let p;
457
+ try {
458
+ p = epicEventLog.appendEpicEvent(cwd, epicId, event);
459
+ } catch (err) {
460
+ p = Promise.reject(err);
461
+ }
462
+ return Promise.resolve(p).catch((err) => {
463
+ console.error('[chatRunner] epic event append failed', event?.kind, err?.message ?? err);
464
+ return null;
465
+ });
466
+ }
467
+
468
+ /** Staging folder for a chat session's artifacts, or null (unsafe id / mkdir failure — logged). */
469
+ function chatArtifactsDir(sessionId) {
470
+ try {
471
+ return artifactStore.stagingDirFor({ runId: sessionId });
472
+ } catch (err) {
473
+ console.error('[chatRunner] artifact staging dir unavailable', sessionId, err?.message ?? err);
474
+ return null;
475
+ }
476
+ }
477
+
478
+ /**
479
+ * Ingest a finished turn's staging folder into artifacts/<epic-id>/. An Epic chat's sessionId IS
480
+ * its Epic id. Fire-and-forget: errors and skipped files are logged, never thrown.
481
+ */
482
+ function ingestChatArtifacts({ cwd, sessionId, srcDir }) {
483
+ let p;
484
+ try {
485
+ p = artifactStore.ingestDir({ projectRoot: cwd, epicId: sessionId, srcDir, producer: { epicId: sessionId, sessionId } });
486
+ } catch (err) {
487
+ p = Promise.reject(err);
488
+ }
489
+ return Promise.resolve(p).then(async (res) => {
490
+ for (const s of res?.skipped || []) console.error('[chatRunner] artifact not ingested', s.path, s.reason);
491
+ // One 'artifact-ready' notice per ingest batch, only when something landed (never throws).
492
+ if (res && Array.isArray(res.published) && res.published.length > 0) {
493
+ await postArtifactReadyNotice({ cwd, epicId: sessionId, entries: res.published });
494
+ }
495
+ return res;
496
+ }).catch((err) => {
497
+ console.error('[chatRunner] artifact ingest failed', sessionId, err?.message ?? err);
498
+ return null;
499
+ });
500
+ }
501
+
502
+ /**
503
+ * Append job.needs_input for an Epic chat turn that asked questions and
504
+ * remember them so the next human prompt is recorded as the answer.
505
+ * @param {{ cwd: string, sessionId: string, questions: string[], answerBody?: string }} args
506
+ */
507
+ function recordNeedsInput({ cwd, sessionId, questions, answerBody }) {
508
+ const qs = Array.isArray(questions) ? questions.filter((q) => typeof q === 'string') : [];
509
+ openQuestions.set(sessionId, { cwd, questions: qs });
510
+ return appendChatEpicEvent(cwd, sessionId, {
511
+ kind: 'job.needs_input',
512
+ source: 'chat',
513
+ sessionId,
514
+ questions: qs,
515
+ ...(typeof answerBody === 'string' && answerBody ? { answerBody } : {}),
516
+ });
517
+ }
518
+
519
+ /**
520
+ * Append human.answer when a human-sent prompt answers this session's open
521
+ * questions. Scheduler-originated prompts are not answers (the question stays
522
+ * open). Returns the append promise, or null when nothing was open.
523
+ * @param {{ cwd?: string, sessionId: string, prompt: string, origin?: string }} args
524
+ */
525
+ function recordAnswerIfOpen({ cwd, sessionId, prompt, origin }) {
526
+ const open = openQuestions.get(sessionId);
527
+ if (!open || origin === 'scheduler') return null;
528
+ openQuestions.delete(sessionId);
529
+ return appendChatEpicEvent(cwd || open.cwd, sessionId, {
530
+ kind: 'human.answer',
531
+ source: 'chat',
532
+ sessionId,
533
+ questions: open.questions,
534
+ answer: typeof prompt === 'string' ? prompt : '',
535
+ });
536
+ }
537
+
538
+ /**
539
+ * Append the message event for a prompt on an Epic chat (sessionId = Epic id):
540
+ * - origin 'human' (a desktop composer submit) → human.message { via: 'desktop' };
541
+ * - origin 'external' tagged relay 'web-remote' (the paired phone) → human.message { via: 'web-remote' };
542
+ * - origin 'external' tagged relay 'admin-api' (POST /admin/chat/send-prompt, which
543
+ * agents also call) → external.message { via: 'admin-api' }.
544
+ * The relay tag is noted by enqueueExternalPrompt and consumed once by run().
545
+ * Untagged external, 'scheduler', 'inbound-proposal', no origin and a boot-recovery
546
+ * re-send (chatBootRecovery.cjs stamps bootRecovery: true) log nothing. This is the
547
+ * event log only — the auto-approval human-prompt ledger (noteChatRunOrigin) still
548
+ * counts origin 'human' alone. Fire-and-forget; a failure is logged by
549
+ * appendChatEpicEvent, never thrown.
550
+ * @param {{ cwd?: string, sessionId: string, prompt: string, origin?: string, bootRecovery?: boolean, relay?: string | null }} args
551
+ */
552
+ function recordHumanMessage({ cwd, sessionId, prompt, origin, bootRecovery, relay }) {
553
+ if (bootRecovery === true) return null;
554
+ let kind; let via;
555
+ if (origin === 'human') { kind = 'human.message'; via = 'desktop'; }
556
+ else if (origin === 'external' && relay === 'web-remote') { kind = 'human.message'; via = 'web-remote'; }
557
+ else if (origin === 'external' && relay === 'admin-api') { kind = 'external.message'; via = 'admin-api'; }
558
+ else return null;
559
+ let summary;
560
+ try { summary = humanMessageSummary(prompt); } catch { return null; }
561
+ return appendChatEpicEvent(cwd, sessionId, { kind, source: 'chat', sessionId, via, ...summary });
562
+ }
563
+
385
564
  // Indirection so tests can stub the spawn without launching claude.
386
565
  let executor = executeRun;
387
566
  function __setExecutor(fn) { executor = fn || executeRun; }
@@ -399,6 +578,8 @@ function __resetQueueForTests() {
399
578
  orphanSessions.clear();
400
579
  waiting.length = 0;
401
580
  pendingStart.clear();
581
+ openQuestions.clear();
582
+ relayPrompts.clear();
402
583
  sessionSlots.__resetForTests();
403
584
  }
404
585
 
@@ -429,6 +610,10 @@ function run(opts) {
429
610
  // A scheduler-originated prompt (tagged by enqueueExternalPrompt) is re-identified
430
611
  // here by tab + exact text, since it travels through the renderer's chat:run.
431
612
  if (!opts.silent && consumeSchedulerPrompt(opts.tabId, opts.prompt)) opts = { ...opts, origin: 'scheduler' };
613
+ // A relayed external send (Web Remote / admin API) is re-identified the same way;
614
+ // the relay only picks the event-log kind, never the origin. Only an external run
615
+ // takes a note: a same-text desktop prompt must not steal a queued phone send's tag.
616
+ if (!opts.silent && opts.origin === 'external' && opts.relay === undefined) opts = { ...opts, relay: consumeRelayPrompt(opts.tabId, opts.prompt) };
432
617
  // Per-tab exclusivity still holds — two `claude -p --resume` against ONE
433
618
  // sessionId must never overlap — but it is now enforced in pump() (which
434
619
  // refuses to start a run for a tab that already has one live) rather than by
@@ -453,6 +638,13 @@ function run(opts) {
453
638
  // still dropped, since queueing one would delay real work to no benefit.
454
639
  return { accepted: false, reason: 'tab-busy-silent' };
455
640
  }
641
+ // A human prompt sent after a needs-input turn is that question's answer.
642
+ if (!opts.silent) recordAnswerIfOpen(opts);
643
+ // Once per prompt: the held-for-worktree re-entry below carries the mark.
644
+ if (!opts.silent && !opts.humanMessageRecorded) {
645
+ recordHumanMessage(opts);
646
+ opts = { ...opts, humanMessageRecorded: true };
647
+ }
456
648
 
457
649
  // A New Epic's turn 1 races the fire-and-forget worktree mint: only when a mint is
458
650
  // actually in flight for this Epic, hold the submission (<=90s, never rejects) so the
@@ -623,7 +815,13 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
623
815
  // originProjectRoot on create-prd/open-session/readiness calls so those
624
816
  // routes can resolve the right project even from a worktree pwd. See
625
817
  // projectRootResolve.cjs.
626
- const childEnv = cleanChildEnv({ PATH: pathWithUserBins(), SM_CHAT_SESSION_ID: sessionId, SM_PROJECT_ROOT: cwd });
818
+ // SM_ARTIFACTS_DIR: a per-session staging folder OUTSIDE the repo (artifactStore.stagingDirFor);
819
+ // whatever the agent writes there is ingested into the Artifacts store when the turn closes
820
+ // (ingestChatArtifacts below), so it shows in the File Explorer with no merge. runId = sessionId,
821
+ // the same folder the Epic's Terminal view gets (pty.cjs) — EPIC : CLI session = 1:1.
822
+ const artifactsDir = chatArtifactsDir(sessionId);
823
+ const artifactsEnv = artifactsDir ? { SM_ARTIFACTS_DIR: artifactsDir } : {};
824
+ const childEnv = cleanChildEnv({ PATH: pathWithUserBins(), SM_CHAT_SESSION_ID: sessionId, SM_PROJECT_ROOT: cwd, ...artifactsEnv });
627
825
 
628
826
  // Prepend the stop-signal protocol instruction and the chat-mode truth
629
827
  // instruction to every prompt
@@ -639,7 +837,9 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
639
837
  // throws; falls back to the hardcoded 'sonnet' literal when there's no
640
838
  // Epic, no agentType, or the persona has no model/'inherit' — --model
641
839
  // must never be left unpinned (CLAUDE.md model-pinning rule).
642
- const model = isAgentCli ? null : agentModelResolve.resolveEpicModel({ cwd, claudeSessionId: sessionId });
840
+ // A pinned Epic (agentSnapshotId, epicSpawnPlan.cjs's resolveEpicTurnModel) takes its model
841
+ // from the AgentSnapshot frozen at mint, so a later persona edit never reaches it.
842
+ const model = isAgentCli ? null : resolveEpicTurnModel({ cwd, claudeSessionId: sessionId });
643
843
  // Persona `effort:` (same overlay-aware persona, agentEffortResolve.cjs);
644
844
  // effortArgs() yields NO tokens for inherit/absent/dangling.
645
845
  const effortFlags = isAgentCli ? [] : effortArgs(resolveEpicEffort({ cwd, claudeSessionId: sessionId }).effort);
@@ -700,7 +900,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
700
900
  }
701
901
  }
702
902
  const agentEnv = agentPlan
703
- ? cleanChildEnv({ PATH: pathWithUserBins(), SM_CHAT_SESSION_ID: sessionId, SM_PROJECT_ROOT: cwd, ...agentPlan.envExtra })
903
+ ? cleanChildEnv({ PATH: pathWithUserBins(), SM_CHAT_SESSION_ID: sessionId, SM_PROJECT_ROOT: cwd, ...artifactsEnv, ...agentPlan.envExtra })
704
904
  : null;
705
905
 
706
906
  const useResume = plan.useResume;
@@ -837,6 +1037,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
837
1037
  target = { ...target, command: wrapped.command, args: wrapped.args, argv0: undefined };
838
1038
  }
839
1039
  }
1040
+ assertNoCredentials(agentPlan ? agentEnv : childEnv, { site: agentPlan ? 'chat-agent' : 'chat' });
840
1041
  if (agentPlan) agentPlan.transcript.userPrompt(fullPrompt);
841
1042
  thisChild = spawn(target.command, target.args || chatArgs, {
842
1043
  ...(target.argv0 ? { argv0: target.argv0 } : {}),
@@ -934,6 +1135,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
934
1135
  answerBody: signal.answerBody,
935
1136
  raw: text,
936
1137
  });
1138
+ recordNeedsInput({ cwd, sessionId, questions: signal.questions, answerBody: signal.answerBody });
937
1139
  // Record durable exchange off the hot path — UI must not wait on Haiku
938
1140
  recordExchange({
939
1141
  sessionId,
@@ -1118,6 +1320,7 @@ function executeRun({ tabId, sessionId, prompt, cwd, resume, silent, onSilentRes
1118
1320
  }, { code: 'exit-no-result' });
1119
1321
  }
1120
1322
  }
1323
+ if (artifactsDir) ingestChatArtifacts({ cwd, sessionId, srcDir: artifactsDir });
1121
1324
  settle();
1122
1325
  });
1123
1326
  };
@@ -1170,7 +1373,6 @@ function cancel(tabId) {
1170
1373
  // directly, reusing send()'s existing queued-vs-immediate branching rather
1171
1374
  // than duplicating it here.
1172
1375
 
1173
- const EXTERNAL_SEND_ACK_TIMEOUT_MS = 8000;
1174
1376
  const pendingExternalSends = new Map(); // requestId -> { resolve, timer }
1175
1377
 
1176
1378
  function hasLiveWindow() {
@@ -1184,11 +1386,19 @@ function hasLiveWindow() {
1184
1386
  * { disposition: 'unconfirmed', reason: 'timeout' | 'no-window' }. Never rejects.
1185
1387
  */
1186
1388
  function enqueueExternalPrompt(tabId, prompt, extra = {}) {
1187
- const { sessionId, cwd, origin } = extra ?? {};
1389
+ const { sessionId, cwd, origin, relay } = extra ?? {};
1188
1390
  if (!hasLiveWindow()) return Promise.resolve({ disposition: 'unconfirmed', reason: 'no-window' });
1189
1391
  if (origin === 'scheduler') noteSchedulerPrompt(tabId, prompt);
1392
+ const note = origin !== 'scheduler' && relay !== undefined ? noteRelayPrompt(tabId, prompt, relay) : null;
1190
1393
  const requestId = require('node:crypto').randomUUID();
1191
- return new Promise((resolve) => {
1394
+ return new Promise((done) => {
1395
+ // A send that produced no run (refused / unconfirmed) never leaves its note behind.
1396
+ const resolve = (result) => {
1397
+ if (note && (result.disposition === 'refused' || result.disposition === 'unconfirmed')) {
1398
+ dropRelayPrompt(tabId, prompt, note);
1399
+ }
1400
+ done(result);
1401
+ };
1192
1402
  const timer = setTimeout(() => {
1193
1403
  pendingExternalSends.delete(requestId);
1194
1404
  resolve({ disposition: 'unconfirmed', reason: 'timeout' });
@@ -1287,7 +1497,7 @@ function registerAdminRoute(adminHttp) {
1287
1497
  sendJson(res, 400, { ok: false, error: e?.message ?? 'invalid body' });
1288
1498
  return;
1289
1499
  }
1290
- const outcome = await enqueueExternalPrompt(body.tabId, body.prompt);
1500
+ const outcome = await enqueueExternalPrompt(body.tabId, body.prompt, { relay: 'admin-api' });
1291
1501
  sendJson(res, 200, {
1292
1502
  ok: outcome.disposition !== 'refused',
1293
1503
  disposition: outcome.disposition,
@@ -1363,6 +1573,8 @@ module.exports = {
1363
1573
  shouldFollowUp,
1364
1574
  parseStopSignal,
1365
1575
  splitStopSignal,
1576
+ recordNeedsInput,
1577
+ recordAnswerIfOpen,
1366
1578
  parseContextUsageMarkdown,
1367
1579
  STOP_SENTINEL,
1368
1580
  // Both instruction blocks are exported so the renderer's preamble splitter
@@ -1378,6 +1590,9 @@ module.exports = {
1378
1590
  enqueueExternalPrompt,
1379
1591
  settleExternalSend,
1380
1592
  EXTERNAL_SEND_ACK_TIMEOUT_MS,
1593
+ RELAY_RUN_START_WINDOW_MS,
1594
+ RELAY_PROMPT_TTL_MS,
1595
+ __relayNoteCount: relayNoteCount,
1381
1596
  requestExternalNewSession,
1382
1597
  startExternalNewSession,
1383
1598
  settleExternalNewSession,