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
@@ -6,7 +6,9 @@
6
6
  * cap, recorded in that project's Task ledger. Order:
7
7
  * 1. strict body schema (400 invalid_request), sessionId+resume /
8
8
  * resume+persistSession:false / missing mcpConfig file (400);
9
- * 2. the human switch 'Scripts may run Tasks' (403 tasks_disabled);
9
+ * 2. the held interactive slot is re-synced from the switch file
10
+ * (taskSwitch.syncInteractiveReserve; a throw is ignored), then the
11
+ * human switch 'Scripts may run Tasks' (403 tasks_disabled);
10
12
  * 3. persona → model + effort with the SPAWN-time resolvers
11
13
  * (agentModelResolve.cjs / agentEffortResolve.cjs — never
12
14
  * FALLBACK_MODEL, never effectiveModelInfo.cjs): 404 unknown_agent,
@@ -23,21 +25,49 @@
23
25
  * A req/res 'close' before the reply aborts the wait or the run
24
26
  * ('caller_gone'); the route disables the socket timeout (runs are long).
25
27
  *
28
+ * Stream mode (body stream: true): every refusal before the ledger start
29
+ * line keeps its status + JSON body. After the start line the route answers
30
+ * 200 application/x-ndjson, one JSON object per line:
31
+ * {type:'sm_task_started', taskId, model, effort, sessionId, startedAt}
32
+ * — written before the slot wait;
33
+ * {type:'sm_task_running', slotWaitMs} — once the slot is granted;
34
+ * each child stdout line as it arrives: as-is when it parses as a JSON
35
+ * object, else {type:'sm_task_stdout', text};
36
+ * {type:'sm_task_result', ...} — last: the non-stream 200 reply plus
37
+ * droppedLines, or the error object the JSON reply would carry
38
+ * (e.g. ok:false, error:'slot_timeout', taskId, slotWaitMs).
39
+ * A 'close' before the result line still aborts the wait or the run
40
+ * (caller_gone). While res.writableLength exceeds 8 MiB, output lines are
41
+ * skipped and counted in droppedLines, so a caller that stops reading
42
+ * cannot grow memory. The stream never carries stderr, env or argv.
43
+ *
26
44
  * GET /admin/tasks?cwd=&since=&until=&pipeline=&runId=&step=&agent=&status=&source=&limit=&offset=
27
45
  * → { ok, tasks, total, hasMore } from taskLedger.listTasks. Each task has
28
46
  * exactly TASK_FIELDS (no prompt/output text). Works whatever the switch.
29
- * GET /admin/task?cwd=&id=
47
+ * GET /admin/task?cwd=&id=&after=
30
48
  * → { ok, task } — TASK_FIELDS plus prompt, output, stderrTail, envelope
31
- * (and the truncation flags) from the body file; 404 unknown_task.
49
+ * (and the truncation flags) from the body file, plus live; 404 unknown_task.
50
+ * A Task this process is still running (the in-process live registry,
51
+ * filled from every POST run's stdout lines) answers status 'running',
52
+ * output = the captured lines from byte offset `after` (default 0), up to
53
+ * 1 MiB cut at a line boundary, outputTruncated when more remain, and
54
+ * live = { slotAcquired, outputEnd, outputCapped } (pass outputEnd as the
55
+ * next `after`). Any other Task: live null; `after` slices the stored
56
+ * output by bytes, rounded forward to a line boundary. GET /admin/tasks
57
+ * also reports a live Task as 'running', never 'interrupted'.
32
58
  * POST /admin/tasks/import (body ≤ 8 MiB)
33
59
  * { cwd, records: 1-100 } — direct `claude -p` calls a caller made while
34
- * Session Manager was down. 403 tasks_disabled when the switch is off.
60
+ * Session Manager was down. Re-syncs the held interactive slot from the
61
+ * switch file, then 403 tasks_disabled when the switch is off.
35
62
  * Each record is validated on its own and recorded with
36
63
  * taskLedger.appendImported (source 'direct'); a known (cwd, importId) is
37
64
  * skipped. costUsd is recomputed with costOfUsage when usage is present
38
65
  * (the caller's figure is kept as cliCostUsd).
39
66
  * → { ok, imported, alreadyImported, rejected: [{ index, error }] }.
40
67
  * Read and import routes take a cwd that must be a project root (400).
68
+ * POST /admin/tasks/switch (taskSwitchRoute.cjs, registered from here)
69
+ * The agent path for the switch: sets one project's switch only on a
70
+ * verified verbatim quote of the human's own chat prompt naming it.
41
71
  *
42
72
  * No caller environment variable ever reaches the child (buildTaskEnv adds
43
73
  * only the Task markers to process.env). Auth/loopback binding are the
@@ -51,18 +81,49 @@ const crypto = require('node:crypto');
51
81
  const { z } = require('zod');
52
82
  const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
53
83
  const { resolveProjectRoot } = require('../opsOwnership.cjs');
84
+ const { phaseOfTask } = require('../phaseProjection.cjs');
85
+ const { registerTaskSwitchRoute } = require('./taskSwitchRoute.cjs');
54
86
 
55
87
  const MAX_BODY_BYTES = 4 * 1024 * 1024;
56
88
  const MAX_IMPORT_BODY_BYTES = 8 * 1024 * 1024;
57
89
  const MAX_IMPORT_RECORDS = 100;
58
90
  const MAX_SYSTEM_PROMPT_BYTES = 100 * 1024;
59
- const SWITCH_HINT = "Turn on 'Scripts may run Tasks' for this project on the Scheduler → Tasks page (a human-only switch).";
91
+ const SWITCH_HINT = "Turn on 'Scripts may run Tasks' for this project: a human flips it on the Scheduler → Tasks page, or an agent in a Session Manager chat calls task_switch_set with the human's own words asking for it.";
60
92
 
61
93
  function isAbsoluteDir(p) {
62
94
  if (typeof p !== 'string' || !path.isAbsolute(p)) return false;
63
95
  try { return fs.statSync(p).isDirectory(); } catch { return false; }
64
96
  }
65
97
 
98
+ const MAX_TOOL_RULES = 50;
99
+ const MAX_TOOL_RULE_CHARS = 500;
100
+
101
+ /**
102
+ * A permission rule the CLI's --disallowedTools list parser reads as ONE rule:
103
+ * trimmed-non-empty, <= 500 chars, no control characters, and when it has '('
104
+ * a tool name before it, a trailing ')' and balanced parentheses. An unbalanced
105
+ * '(' would make the CLI swallow later text into one broken rule — a deny that
106
+ * silently never applies — so it is refused, never passed on. The first
107
+ * character must be an ASCII letter (tool names and mcp__ rules all are), so a
108
+ * '-'-leading or space-leading value can never be read as a CLI flag.
109
+ * @param {unknown} s
110
+ */
111
+ function isValidToolRule(s) {
112
+ if (typeof s !== 'string') return false;
113
+ if (!/^[A-Za-z]/.test(s)) return false;
114
+ if (s.trim() === '' || s.length > MAX_TOOL_RULE_CHARS) return false;
115
+ if (/[\u0000-\u001f\u007f]/.test(s)) return false;
116
+ if (!s.includes('(') && !s.includes(')')) return true;
117
+ const open = s.indexOf('(');
118
+ if (open <= 0 || s.slice(0, open).trim() === '' || !s.endsWith(')')) return false;
119
+ let depth = 0;
120
+ for (const ch of s) {
121
+ if (ch === '(') depth += 1;
122
+ else if (ch === ')') { depth -= 1; if (depth < 0) return false; }
123
+ }
124
+ return depth === 0;
125
+ }
126
+
66
127
  const runtimeSchema = z.object({
67
128
  outputFormat: z.enum(['json', 'text', 'stream-json']).default('json'),
68
129
  settingSources: z.string().optional(),
@@ -75,6 +136,13 @@ const runtimeSchema = z.object({
75
136
  systemPrompt: z.string()
76
137
  .refine((s) => Buffer.byteLength(s, 'utf8') <= MAX_SYSTEM_PROMPT_BYTES, { message: `systemPrompt exceeds ${MAX_SYSTEM_PROMPT_BYTES} bytes` })
77
138
  .optional(),
139
+ appendSystemPrompt: z.string()
140
+ .refine((s) => Buffer.byteLength(s, 'utf8') <= MAX_SYSTEM_PROMPT_BYTES, { message: `appendSystemPrompt exceeds ${MAX_SYSTEM_PROMPT_BYTES} bytes` })
141
+ .optional(),
142
+ // Permission deny rules ('WebFetch(domain:localhost)'); each reaches the CLI as one
143
+ // '--disallowedTools=<rule>' element — after a bare variadic flag a '-'-leading value
144
+ // is parsed as a new flag, so the '=' form plus the leading-letter check stop injection.
145
+ disallowedTools: z.array(z.string().refine(isValidToolRule, { message: 'invalid tool rule' })).max(MAX_TOOL_RULES).optional(),
78
146
  skipPermissions: z.boolean().optional(),
79
147
  disableAutoMemory: z.boolean().optional(),
80
148
  sessionId: z.string().uuid().optional(),
@@ -98,8 +166,13 @@ const bodySchema = z.object({
98
166
  attempt: z.number().int().min(0).optional(),
99
167
  }).strict().default({}),
100
168
  runtime: runtimeSchema.default({ outputFormat: 'json' }),
169
+ // true → 200 application/x-ndjson after the ledger start line (see the header).
170
+ stream: z.boolean().optional(),
101
171
  }).strict();
102
172
 
173
+ /** Past this many unsent bytes in the response buffer, stream-mode output lines are dropped (and counted). */
174
+ const MAX_STREAM_BUFFER_BYTES = 8 * 1024 * 1024;
175
+
103
176
  /** Outcome statuses an imported record may carry: the ledger's end statuses (taskRun + route). */
104
177
  const IMPORT_STATUSES = /** @type {const} */ ([
105
178
  'ok', 'error', 'rate_limited', 'timeout', 'spawn_failed', 'caller_gone', 'slot_timeout', 'too_many_waiting', 'interrupted',
@@ -110,7 +183,7 @@ const TASK_FIELDS = Object.freeze([
110
183
  'taskId', 'source', 'importId', 'importedAt', 'agent', 'missionId', 'model', 'effort', 'priority', 'caller',
111
184
  'outputFormat', 'timeoutSec', 'slotWaitSec', 'sessionId', 'persisted', 'startedAt', 'endedAt', 'status',
112
185
  'exitCode', 'signal', 'durationMs', 'slotWaitMs', 'usage', 'costUsd', 'cliCostUsd', 'numTurns', 'quota',
113
- 'promptBytes', 'promptSha256', 'outputBytes', 'outputSha256',
186
+ 'promptBytes', 'promptSha256', 'outputBytes', 'outputSha256', 'phase',
114
187
  ]);
115
188
 
116
189
  /** @param {Record<string, any>} t a folded ledger Task → exactly TASK_FIELDS (missing → null). */
@@ -121,6 +194,7 @@ function publicTask(t) {
121
194
  if (!out.source) out.source = 'sm';
122
195
  if (out.caller == null) out.caller = {};
123
196
  out.persisted = t.persisted === true;
197
+ out.phase = phaseOfTask(t); // phaseProjection.cjs — never stored, derived from status
124
198
  return out;
125
199
  }
126
200
 
@@ -143,8 +217,90 @@ const listQuerySchema = z.object({
143
217
  const getQuerySchema = z.object({
144
218
  cwd: z.string().min(1),
145
219
  id: z.string().min(1).max(200),
220
+ // Byte offset into the Task's stdout to read from (a live Task's live.outputEnd).
221
+ after: z.string().regex(/^\d+$/).transform(Number).pipe(z.number().int().min(0)).optional(),
146
222
  }).strict();
147
223
 
224
+ /** Keys POST /admin/tasks accepts at the top level and under runtime, and GET /admin/task query keys (advertised on the health route via externalContract.cjs). */
225
+ const TASK_BODY_KEYS = Object.freeze(Object.keys(bodySchema.shape));
226
+ const TASK_RUNTIME_KEYS = Object.freeze(Object.keys(runtimeSchema.shape));
227
+ const TASK_GET_KEYS = Object.freeze(Object.keys(getQuerySchema.shape));
228
+
229
+ /** One GET /admin/task page of a live Task's captured output. */
230
+ const LIVE_PAGE_BYTES = 1024 * 1024;
231
+
232
+ /**
233
+ * A live Task's captured stdout: lines plus cumulative end byte offsets
234
+ * (ends[i] = bytes of lines[0..i] each counted with its '\n').
235
+ * @typedef {{ cwd: string, lines: string[], ends: number[], bytes: number,
236
+ * slotAcquired: boolean, outputCapped: boolean }} LiveTask
237
+ */
238
+
239
+ /** @param {number} cap @param {string} cwd @returns {LiveTask & { append: (line: string) => void }} */
240
+ function newLiveTask(cwd, cap) {
241
+ /** @type {any} */
242
+ const lt = { cwd, lines: [], ends: [], bytes: 0, slotAcquired: false, outputCapped: false };
243
+ lt.append = (/** @type {string} */ line) => {
244
+ if (lt.outputCapped) return;
245
+ const b = Buffer.byteLength(line + '\n', 'utf8');
246
+ if (lt.bytes + b > cap) { lt.outputCapped = true; return; }
247
+ lt.lines.push(line);
248
+ lt.bytes += b;
249
+ lt.ends.push(lt.bytes);
250
+ if (lt.bytes >= cap) lt.outputCapped = true;
251
+ };
252
+ return lt;
253
+ }
254
+
255
+ /**
256
+ * The page of a live Task's lines starting at byte offset `after`.
257
+ * Binary search for the first line whose START offset (ends[i-1], or 0) is
258
+ * >= after: O(log n) over n captured lines, then O(k) over the k lines taken
259
+ * (at most LIVE_PAGE_BYTES of them).
260
+ * @param {LiveTask} lt @param {number} after
261
+ * @returns {{ output: string, outputTruncated: boolean, outputEnd: number }}
262
+ */
263
+ function livePage(lt, after) {
264
+ const { lines, ends } = lt;
265
+ let lo = 0;
266
+ let hi = lines.length;
267
+ while (lo < hi) {
268
+ const mid = (lo + hi) >>> 1;
269
+ const start = mid === 0 ? 0 : ends[mid - 1];
270
+ if (start >= after) hi = mid; else lo = mid + 1;
271
+ }
272
+ const first = lo;
273
+ const pageStart = first === 0 ? 0 : ends[first - 1];
274
+ let i = first;
275
+ while (i < lines.length && ends[i] - pageStart <= LIVE_PAGE_BYTES) i += 1;
276
+ // A single line longer than a page is still delivered alone, so a reader always advances.
277
+ if (i === first && i < lines.length) i += 1;
278
+ const taken = lines.slice(first, i);
279
+ return {
280
+ output: taken.length ? taken.join('\n') + '\n' : '',
281
+ outputTruncated: i < lines.length,
282
+ outputEnd: i > first ? ends[i - 1] : after,
283
+ };
284
+ }
285
+
286
+ /**
287
+ * A finished Task's stored output from byte offset `after`, rounded forward to
288
+ * the next line boundary; an offset at or past the end gives ''. O(output bytes).
289
+ * @param {string} text @param {number} after
290
+ */
291
+ function sliceFromByte(text, after) {
292
+ if (!after) return text;
293
+ const buf = Buffer.from(text, 'utf8');
294
+ if (after >= buf.length) return '';
295
+ let start = after;
296
+ if (buf[start - 1] !== 0x0a) {
297
+ const nl = buf.indexOf(0x0a, start);
298
+ if (nl === -1) return '';
299
+ start = nl + 1;
300
+ }
301
+ return buf.subarray(start).toString('utf8');
302
+ }
303
+
148
304
  const callerSchema = z.object({
149
305
  pipeline: z.string().max(200).optional(),
150
306
  runId: z.string().max(200).optional(),
@@ -196,19 +352,27 @@ function issueText(/** @type {any} */ error) {
196
352
  * discarded here); model = persona `model` (overlay-aware) else the Settings
197
353
  * model — never agentModelResolve's FALLBACK_MODEL.
198
354
  * @param {{ cwd: string, agent: string }} a
199
- * @returns {Promise<{ personaFound: boolean, resolvedModelId: string|null, personaEffort: string|null }>}
355
+ * declaredMcpServers = the persona's `mcpServers:` (overlay-aware), the only
356
+ * MCP servers the strict Task spawn loads.
357
+ * @returns {Promise<{ personaFound: boolean, resolvedModelId: string|null, personaEffort: string|null, declaredMcpServers: string[] }>}
200
358
  */
201
359
  async function defaultResolveInfo({ cwd, agent }) {
202
- const { getPersonaBody } = require('../../agentLibrary.cjs');
360
+ const { getPersonaBody, parseCapabilityList } = require('../../agentLibrary.cjs');
203
361
  const persona = await getPersonaBody({ cwd, name: agent });
204
- if (!persona) return { personaFound: false, resolvedModelId: null, personaEffort: null };
362
+ if (!persona) return { personaFound: false, resolvedModelId: null, personaEffort: null, declaredMcpServers: [] };
205
363
  const { readOverlayAwarePersonaModel } = require('../claude/agentModelResolve.cjs');
206
364
  const { resolveEpicEffort } = require('../claude/agentEffortResolve.cjs');
207
365
  const { readSettingsModel } = require('../claude/modelCatalog.cjs');
208
366
  let model = readOverlayAwarePersonaModel(agent, { cwd });
209
367
  if (!model || model === 'inherit') model = readSettingsModel(cwd);
210
368
  const { effort } = resolveEpicEffort({ cwd, agentType: agent });
211
- return { personaFound: true, resolvedModelId: model || null, personaEffort: effort || null };
369
+ let declaredMcpServers = [];
370
+ try {
371
+ const { readOverlayAwarePersona } = require('../claude/agentModelResolve.cjs');
372
+ const p = readOverlayAwarePersona(agent, { cwd });
373
+ declaredMcpServers = parseCapabilityList(p && p.fm ? p.fm.mcpServers : undefined);
374
+ } catch { /* unreadable frontmatter → no declared servers (strict mode loads none) */ }
375
+ return { personaFound: true, resolvedModelId: model || null, personaEffort: effort || null, declaredMcpServers };
212
376
  }
213
377
 
214
378
  /** A real `--model` value: a non-empty string that is not the 'inherit' sentinel. */
@@ -237,13 +401,41 @@ function costFor(model, run, costOfUsage) {
237
401
  }
238
402
  }
239
403
 
404
+ /**
405
+ * The live registry (taskId → LiveTask) of the most recently registered
406
+ * POST /admin/tasks route. Production registers the route once; in tests the
407
+ * last registerAdminRoute call wins. null until a route is registered.
408
+ * @type {Map<string, { cwd: string }> | null}
409
+ */
410
+ let activeLiveTasks = null;
411
+
412
+ /**
413
+ * taskIds the most recently registered POST /admin/tasks route is running for
414
+ * project root `root` (path.resolve equality) — [] when none, or when no route
415
+ * is registered. The GET routes and the desktop Tasks IPC (taskIpc.cjs) pass
416
+ * these as liveTaskIds so every Task read folds a live run as running.
417
+ * Production registers the route once; in tests the last registration wins.
418
+ * @param {string} root
419
+ * @returns {string[]}
420
+ */
421
+ function liveTaskIdsFor(root) {
422
+ const ids = [];
423
+ if (!activeLiveTasks) return ids;
424
+ const want = path.resolve(root);
425
+ for (const [id, lt] of activeLiveTasks) if (path.resolve(lt.cwd) === want) ids.push(id);
426
+ return ids;
427
+ }
428
+
240
429
  /**
241
430
  * @param {{ registerRoute: Function }} adminHttp
242
431
  * @param {{ taskSwitch?: any, resolveInfo?: Function, sessionSlots?: any, runTask?: Function,
243
432
  * buildTaskArgs?: Function, buildTaskEnv?: Function, ledger?: any, costOfUsage?: Function,
244
- * now?: () => number, randomUUID?: () => string, resolveProjectRoot?: Function }} [deps]
433
+ * now?: () => number, randomUUID?: () => string, resolveProjectRoot?: Function,
434
+ * syncInteractiveReserve?: () => any, knownMcpServers?: () => Record<string, object>,
435
+ * switchRouteDeps?: Record<string, any> }} [deps]
245
436
  */
246
437
  function registerAdminRoute(adminHttp, deps = {}) {
438
+ registerTaskSwitchRoute(adminHttp, deps.switchRouteDeps || {});
247
439
  // Lazy defaults: agentLibrary / slots / spawn pull in heavy modules.
248
440
  const taskSwitch = () => deps.taskSwitch || require('./taskSwitch.cjs');
249
441
  const resolveInfo = deps.resolveInfo || defaultResolveInfo;
@@ -253,23 +445,58 @@ function registerAdminRoute(adminHttp, deps = {}) {
253
445
  const buildArgs = (/** @type {any} */ o) => (deps.buildTaskArgs || taskRun().buildTaskArgs)(o);
254
446
  const buildEnv = (/** @type {any} */ rt, /** @type {any} */ env) => (deps.buildTaskEnv || taskRun().buildTaskEnv)(rt, env);
255
447
  const ledger = () => deps.ledger || require('./taskLedger.cjs');
448
+ // The servers a declared `mcpServers:` name may resolve to — the scheduler's own set.
449
+ const knownMcpServers = deps.knownMcpServers || (() => {
450
+ const seed = require('../../seedSchedulerMcp.cjs');
451
+ return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
452
+ });
256
453
  const costOfUsage = (/** @type {any} */ m, /** @type {any} */ b) => (deps.costOfUsage || require('../claude/modelPricing.cjs').costOfUsage)(m, b);
257
454
  const now = deps.now || Date.now;
258
455
  const newId = deps.randomUUID || (() => crypto.randomUUID());
259
456
  const projectRoot = deps.resolveProjectRoot || resolveProjectRoot;
457
+ // The switch file can change outside the renderer IPC (e.g. a direct module
458
+ // call); re-sync the held interactive slot from it on every switch check.
459
+ // setInteractiveReserve is a no-op when unchanged, so this is cheap.
460
+ const syncReserve = deps.syncInteractiveReserve || (() => require('./taskSwitch.cjs').syncInteractiveReserve());
461
+ const safeSync = () => {
462
+ try { syncReserve(); } catch { /* a failed sync never changes the response */ }
463
+ };
260
464
 
261
465
  /** sessionId → taskId for every Task currently between its start line and its end line. */
262
466
  const busySessions = new Map();
467
+ /**
468
+ * taskId → its live output for every POST /admin/tasks run between its
469
+ * ledger start line and the end of the handler (removed in finally, after
470
+ * the end line). In-process only: never persisted.
471
+ * @type {Map<string, LiveTask & { append: (line: string) => void }>}
472
+ */
473
+ const liveTasks = new Map();
474
+ const liveCap = () => Number(taskRun().MAX_STDOUT_BYTES) || 8 * 1024 * 1024;
475
+ /** @param {string} id @param {string} root */
476
+ const liveFor = (id, root) => {
477
+ const lt = liveTasks.get(id);
478
+ return lt && path.resolve(lt.cwd) === path.resolve(root) ? lt : null;
479
+ };
480
+ activeLiveTasks = liveTasks;
263
481
 
264
482
  adminHttp.registerRoute('POST', '/admin/tasks', async (/** @type {any} */ req, /** @type {any} */ res) => {
265
483
  try { if (typeof res.setTimeout === 'function') res.setTimeout(0); } catch { /* */ }
266
484
  try { if (typeof req.setTimeout === 'function') req.setTimeout(0); } catch { /* */ }
267
485
 
268
486
  let replied = false;
487
+ // Stream mode: set once the 200 NDJSON head is written (after the ledger start line).
488
+ let streaming = false;
489
+ const canWrite = () => !(res.writableEnded || res.destroyed);
490
+ const writeLine = (/** @type {any} */ obj) => { if (canWrite()) res.write(JSON.stringify(obj) + '\n'); };
269
491
  const reply = (/** @type {number} */ status, /** @type {any} */ obj) => {
270
492
  if (replied) return;
271
493
  replied = true;
272
- if (res.writableEnded || res.destroyed) return;
494
+ if (!canWrite()) return;
495
+ if (streaming) {
496
+ writeLine({ type: 'sm_task_result', ...obj });
497
+ res.end();
498
+ return;
499
+ }
273
500
  sendJson(res, status, obj);
274
501
  };
275
502
 
@@ -319,6 +546,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
319
546
  }
320
547
  }
321
548
 
549
+ safeSync();
322
550
  if (!taskSwitch().isTaskSwitchOn(cwd)) {
323
551
  reply(403, { ok: false, error: 'tasks_disabled', hint: SWITCH_HINT });
324
552
  return;
@@ -358,7 +586,8 @@ function registerAdminRoute(adminHttp, deps = {}) {
358
586
 
359
587
  let args;
360
588
  try {
361
- args = buildArgs({ model, effort, runtime: argsRuntime, projectCwd: cwd });
589
+ const declaredMcpServers = Array.isArray(info.declaredMcpServers) ? info.declaredMcpServers : [];
590
+ args = buildArgs({ model, effort, runtime: argsRuntime, projectCwd: cwd, declaredMcpServers, knownMcpServers: knownMcpServers() });
362
591
  } catch (e) {
363
592
  reply(400, { ok: false, error: (e && /** @type {any} */ (e).code) || 'invalid_request', details: e instanceof Error ? e.message : String(e) });
364
593
  return;
@@ -390,6 +619,14 @@ function registerAdminRoute(adminHttp, deps = {}) {
390
619
  persisted,
391
620
  prompt: input.prompt,
392
621
  });
622
+ const live = newLiveTask(cwd, liveCap());
623
+ liveTasks.set(taskId, live);
624
+
625
+ if (input.stream === true && canWrite()) {
626
+ res.writeHead(200, { 'Content-Type': 'application/x-ndjson', 'Cache-Control': 'no-store' });
627
+ streaming = true;
628
+ writeLine({ type: 'sm_task_started', taskId, model, effort, sessionId, startedAt });
629
+ }
393
630
 
394
631
  const end = (/** @type {Record<string, any>} */ row) => ledger().appendTaskEnd(cwd, {
395
632
  taskId,
@@ -408,8 +645,9 @@ function registerAdminRoute(adminHttp, deps = {}) {
408
645
  token = await slots().waitForSlot(`task:${taskId}`, { lane, timeoutMs: input.slotWaitSec * 1000, signal: ac.signal });
409
646
  } catch (e) {
410
647
  const code = (e && /** @type {any} */ (e).code) || 'slot_error';
411
- await end({ status: code, slotWaitMs: now() - waitStart });
412
- reply(code === 'too_many_waiting' ? 429 : 500, { ok: false, error: code, taskId });
648
+ const errWaitMs = now() - waitStart;
649
+ await end({ status: code, slotWaitMs: errWaitMs });
650
+ reply(code === 'too_many_waiting' ? 429 : 500, streaming ? { ok: false, error: code, taskId, slotWaitMs: errWaitMs } : { ok: false, error: code, taskId });
413
651
  return;
414
652
  }
415
653
  const slotWaitMs = now() - waitStart;
@@ -420,6 +658,26 @@ function registerAdminRoute(adminHttp, deps = {}) {
420
658
  return;
421
659
  }
422
660
 
661
+ live.slotAcquired = true;
662
+
663
+ let droppedLines = 0;
664
+ if (streaming) writeLine({ type: 'sm_task_running', slotWaitMs });
665
+ // One callback for every run: the live registry, and in stream mode the NDJSON line too.
666
+ const onStdoutLine = (/** @type {string} */ line) => {
667
+ live.append(line);
668
+ if (streaming) {
669
+ if (!canWrite()) return;
670
+ if ((res.writableLength || 0) > MAX_STREAM_BUFFER_BYTES) { droppedLines += 1; return; }
671
+ let isObject = false;
672
+ try {
673
+ const v = JSON.parse(line);
674
+ isObject = v !== null && typeof v === 'object' && !Array.isArray(v);
675
+ } catch { /* not JSON → wrapped */ }
676
+ if (isObject) res.write(line + '\n');
677
+ else writeLine({ type: 'sm_task_stdout', text: line });
678
+ }
679
+ };
680
+
423
681
  let run;
424
682
  try {
425
683
  run = await runTask({
@@ -430,6 +688,9 @@ function registerAdminRoute(adminHttp, deps = {}) {
430
688
  timeoutMs: input.timeoutSec * 1000,
431
689
  signal: ac.signal,
432
690
  onSpawn: (/** @type {number} */ pid) => { try { slots().stampPid(token, pid); } catch { /* */ } },
691
+ onStdoutLine,
692
+ taskId,
693
+ projectRoot: cwd,
433
694
  });
434
695
  } finally {
435
696
  try { slots().release(token); } catch { /* */ }
@@ -455,7 +716,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
455
716
  });
456
717
 
457
718
  const { textStdoutFor } = taskRun();
458
- reply(200, {
719
+ const result = {
459
720
  ok: true,
460
721
  taskId,
461
722
  status: run.status,
@@ -471,9 +732,11 @@ function registerAdminRoute(adminHttp, deps = {}) {
471
732
  effort,
472
733
  sessionId: finalSessionId,
473
734
  quota: run.quota,
474
- });
735
+ };
736
+ reply(200, streaming ? { ...result, droppedLines } : result);
475
737
  } finally {
476
738
  if (sessionId && busySessions.get(sessionId) === taskId) busySessions.delete(sessionId);
739
+ liveTasks.delete(taskId);
477
740
  req.removeListener('close', onClose);
478
741
  res.removeListener('close', onClose);
479
742
  }
@@ -499,8 +762,10 @@ function registerAdminRoute(adminHttp, deps = {}) {
499
762
  return;
500
763
  }
501
764
  try {
502
- const r = await ledger().listTasks(cwd, { ...filters, now: now() });
503
- sendJson(res, 200, { ok: true, tasks: r.tasks.map(publicTask), total: r.total, hasMore: r.hasMore });
765
+ // A Task this app is still running folds 'running' in the ledger, before its status filter and paging.
766
+ const r = await ledger().listTasks(cwd, { ...filters, now: now(), liveTaskIds: liveTaskIdsFor(cwd) });
767
+ const tasks = r.tasks.map((/** @type {any} */ t) => publicTask(t));
768
+ sendJson(res, 200, { ok: true, tasks, total: r.total, hasMore: r.hasMore });
504
769
  } catch (e) {
505
770
  sendJson(res, 500, { ok: false, error: 'ledger_read_failed', details: e instanceof Error ? e.message : String(e) });
506
771
  }
@@ -519,7 +784,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
519
784
  }
520
785
  let t;
521
786
  try {
522
- t = await ledger().getTask(cwd, parsed.data.id, { now: now() });
787
+ t = await ledger().getTask(cwd, parsed.data.id, { now: now(), liveTaskIds: liveTaskIdsFor(cwd) });
523
788
  } catch (e) {
524
789
  sendJson(res, 500, { ok: false, error: 'ledger_read_failed', details: e instanceof Error ? e.message : String(e) });
525
790
  return;
@@ -529,16 +794,37 @@ function registerAdminRoute(adminHttp, deps = {}) {
529
794
  return;
530
795
  }
531
796
  const body = t.body || {};
797
+ const after = parsed.data.after || 0;
798
+ const live = liveFor(parsed.data.id, cwd);
799
+ if (live) {
800
+ const page = livePage(live, after);
801
+ sendJson(res, 200, {
802
+ ok: true,
803
+ task: {
804
+ ...publicTask(t),
805
+ prompt: typeof body.prompt === 'string' ? body.prompt : null,
806
+ promptTruncated: body.promptTruncated === true,
807
+ output: page.output,
808
+ outputTruncated: page.outputTruncated,
809
+ stderrTail: null,
810
+ envelope: null,
811
+ live: { slotAcquired: live.slotAcquired, outputEnd: page.outputEnd, outputCapped: live.outputCapped },
812
+ },
813
+ });
814
+ return;
815
+ }
816
+ const storedOutput = typeof body.output === 'string' ? body.output : null;
532
817
  sendJson(res, 200, {
533
818
  ok: true,
534
819
  task: {
535
820
  ...publicTask(t),
536
821
  prompt: typeof body.prompt === 'string' ? body.prompt : null,
537
822
  promptTruncated: body.promptTruncated === true,
538
- output: typeof body.output === 'string' ? body.output : null,
823
+ output: storedOutput !== null && after > 0 ? sliceFromByte(storedOutput, after) : storedOutput,
539
824
  outputTruncated: body.outputTruncated === true,
540
825
  stderrTail: typeof body.stderrTail === 'string' ? body.stderrTail : null,
541
826
  envelope: body.envelope === undefined ? null : body.envelope,
827
+ live: null,
542
828
  },
543
829
  });
544
830
  });
@@ -569,6 +855,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
569
855
  sendJson(res, 400, { ok: false, error: 'invalid_request', details: e instanceof Error ? e.message : String(e) });
570
856
  return;
571
857
  }
858
+ safeSync();
572
859
  if (!taskSwitch().isTaskSwitchOn(cwd)) {
573
860
  sendJson(res, 403, { ok: false, error: 'tasks_disabled', hint: SWITCH_HINT });
574
861
  return;
@@ -638,4 +925,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
638
925
  });
639
926
  }
640
927
 
641
- module.exports = { registerAdminRoute, MAX_BODY_BYTES, MAX_IMPORT_BODY_BYTES, TASK_FIELDS, IMPORT_STATUSES };
928
+ module.exports = {
929
+ registerAdminRoute, liveTaskIdsFor, MAX_BODY_BYTES, MAX_IMPORT_BODY_BYTES, TASK_FIELDS, IMPORT_STATUSES,
930
+ TASK_BODY_KEYS, TASK_RUNTIME_KEYS, TASK_GET_KEYS,
931
+ };
@@ -5,31 +5,31 @@
5
5
  *
6
6
  * tasks:list { cwd, ...listTasks filters } → { ok, tasks, total, hasMore, skippedLines }
7
7
  * tasks:get { cwd, id } → { ok, task } (task null when absent)
8
- * tasks:get-switch { cwd } → { ok, enabled }
8
+ * tasks:get-switch { cwd } → { ok, enabled, changedAt, by }
9
9
  * tasks:set-switch { cwd, enabled } → { ok, enabled, changedAt }
10
10
  *
11
- * tasks:set-switch is the ONLY caller of taskSwitch.setTaskSwitch — the switch
12
- * is a human decision made in the renderer (see taskSwitch.cjs). After every
13
- * write, and once at registration, the held interactive slot in sessionSlots
14
- * is set to anyTaskSwitchOn(), so it is held exactly while some project has
15
- * Tasks on. Payloads are validated by strict zod schemas (ipcSchemas.cjs);
11
+ * tasks:list and tasks:get pass the in-process live registry's taskIds
12
+ * (taskAdminRoutes.liveTaskIdsFor) as liveTaskIds, so a Task this app is
13
+ * still running reads 'running' here exactly as it does on GET /admin/tasks
14
+ * and GET /admin/task — never 'interrupted' past its window.
15
+ *
16
+ * tasks:set-switch is the human-click writer of taskSwitch.setTaskSwitch and
17
+ * records by { via: 'ui' } (the other sanctioned writer is the agent route —
18
+ * see taskSwitch.cjs). After every write, and once at registration,
19
+ * taskSwitch.syncInteractiveReserve() holds the interactive slot exactly while
20
+ * some project has Tasks on. Payloads are validated by strict zod schemas (ipcSchemas.cjs);
16
21
  * an invalid payload rejects the invoke.
17
22
  */
18
23
 
19
24
  const { schemas, validated } = require('../../ipcSchemas.cjs');
20
25
  const taskLedger = require('./taskLedger.cjs');
21
26
  const taskSwitch = require('./taskSwitch.cjs');
22
- const sessionSlots = require('../scheduler/sessionSlots.cjs');
23
27
  const auditLog = require('../telemetry/auditLog.cjs');
24
28
 
25
29
  function errMsg(err) {
26
30
  return err && err.message ? err.message : String(err);
27
31
  }
28
32
 
29
- function syncInteractiveReserve() {
30
- return sessionSlots.setInteractiveReserve(taskSwitch.anyTaskSwitchOn());
31
- }
32
-
33
33
  /**
34
34
  * @param {{ ipcMain?: any }} [opts]
35
35
  */
@@ -38,7 +38,8 @@ function registerTaskIpc(opts = {}) {
38
38
 
39
39
  ipcMain.handle('tasks:list', validated(schemas.TaskListQuery, async ({ cwd, ...filters }) => {
40
40
  try {
41
- const res = await taskLedger.listTasks(cwd, filters);
41
+ const { liveTaskIdsFor } = require('./taskAdminRoutes.cjs');
42
+ const res = await taskLedger.listTasks(cwd, { ...filters, liveTaskIds: liveTaskIdsFor(cwd) });
42
43
  return { ok: true, ...res };
43
44
  } catch (err) {
44
45
  return { ok: false, error: errMsg(err) };
@@ -47,7 +48,8 @@ function registerTaskIpc(opts = {}) {
47
48
 
48
49
  ipcMain.handle('tasks:get', validated(schemas.TaskGetQuery, async ({ cwd, id }) => {
49
50
  try {
50
- const task = await taskLedger.getTask(cwd, id);
51
+ const { liveTaskIdsFor } = require('./taskAdminRoutes.cjs');
52
+ const task = await taskLedger.getTask(cwd, id, { liveTaskIds: liveTaskIdsFor(cwd) });
51
53
  return { ok: true, task };
52
54
  } catch (err) {
53
55
  return { ok: false, error: errMsg(err) };
@@ -56,7 +58,9 @@ function registerTaskIpc(opts = {}) {
56
58
 
57
59
  ipcMain.handle('tasks:get-switch', validated(schemas.TaskSwitchQuery, async ({ cwd }) => {
58
60
  try {
59
- return { ok: true, enabled: taskSwitch.isTaskSwitchOn(cwd) };
61
+ const entry = taskSwitch.getTaskSwitch(cwd);
62
+ if (!entry) return { ok: false, error: 'tasks:get-switch: invalid cwd' };
63
+ return { ok: true, enabled: entry.enabled, changedAt: entry.changedAt, by: entry.by };
60
64
  } catch (err) {
61
65
  return { ok: false, error: errMsg(err) };
62
66
  }
@@ -64,17 +68,17 @@ function registerTaskIpc(opts = {}) {
64
68
 
65
69
  ipcMain.handle('tasks:set-switch', validated(schemas.TaskSwitchSet, async ({ cwd, enabled }) => {
66
70
  try {
67
- const saved = taskSwitch.setTaskSwitch(cwd, enabled);
68
- auditLog.appendAuditEvent('task_switch_changed', { cwd: saved.cwd, enabled: saved.enabled });
71
+ const saved = taskSwitch.setTaskSwitch(cwd, enabled, { via: 'ui' });
72
+ auditLog.appendAuditEvent('task_switch_changed', { cwd: saved.cwd, enabled: saved.enabled, via: 'ui' });
69
73
  return { ok: true, enabled: saved.enabled, changedAt: saved.changedAt };
70
74
  } catch (err) {
71
75
  return { ok: false, error: errMsg(err) };
72
76
  } finally {
73
- syncInteractiveReserve();
77
+ taskSwitch.syncInteractiveReserve();
74
78
  }
75
79
  }));
76
80
 
77
- syncInteractiveReserve();
81
+ taskSwitch.syncInteractiveReserve();
78
82
  }
79
83
 
80
84
  module.exports = { registerTaskIpc };