claude-code-session-manager 0.140.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -10,26 +10,31 @@
10
10
  *
11
11
  * Deliberately NOT here:
12
12
  * - slot acquisition (lib/scheduler/sessionSlots.cjs) — the route holds the slot;
13
- * - a persona body — `--system-prompt` is passed only when the caller gives one,
14
- * and it REPLACES the system prompt (never --append-system-prompt);
13
+ * - a persona body — never added. `--system-prompt` is passed only when the
14
+ * caller gives one, and it REPLACES the system prompt; `--append-system-prompt`
15
+ * carries only the caller's runtime.appendSystemPrompt;
15
16
  * - ledger writes / HTTP.
16
17
  *
17
18
  * Spawn pattern mirrors lib/claude/runClaudeP.cjs (resolveClaudeBin,
18
19
  * claudeSpawnTarget, feedChildStdin) inside a memory scope like chatRunner.cjs.
19
20
  */
20
21
 
22
+ const nodeFs = require('node:fs');
21
23
  const path = require('node:path');
22
24
  const os = require('node:os');
23
25
  const { spawn: nodeSpawn } = require('node:child_process');
26
+ const { StringDecoder } = require('node:string_decoder');
24
27
  const { resolveClaudeBin, claudeSpawnTarget } = require('../claude/claudeBin.cjs');
25
28
  const { headlessPermissionArgs, ensureCliCapsProbed } = require('../claude/claudeCliCaps.cjs');
26
29
  const { detectRateLimitInText } = require('../claude/rateLimitDetect.cjs');
27
30
  const { feedChildStdin } = require('../process/childStdin.cjs');
28
- const { withProcRole } = require('../process/cleanEnv.cjs');
31
+ const { withProcRole, stripCredentials, assertNoCredentials } = require('../process/cleanEnv.cjs');
29
32
  const { killTree, detachedSpawnOpts } = require('../process/killTree.cjs');
30
33
  const memoryScope = require('../process/memoryScope.cjs');
31
34
  const { writeToolRiskGuardSettingsFile } = require('../epic/guardSpawnSettings.cjs');
32
35
  const { buildJobSandboxSettings } = require('../claude/jobSandboxPolicy.cjs');
36
+ const { personaToolScopeArgs } = require('../claude/personaToolScope.cjs');
37
+ const artifactStore = require('../epic/artifactStore.cjs');
33
38
 
34
39
  const MAX_STDOUT_BYTES = 8 * 1024 * 1024;
35
40
  const STDERR_TAIL_BYTES = 16 * 1024;
@@ -45,10 +50,31 @@ function nonEmptyString(v) {
45
50
  * Build the claude argv for a Task. Pure (reads only the cached CLI-caps probe
46
51
  * via headlessPermissionArgs()). Never includes the prompt.
47
52
  *
48
- * @param {{ model: string, effort: string, runtime?: Record<string, any>, projectCwd?: string }} o
53
+ * MCP is always strict: --strict-mcp-config is pushed unconditionally (the
54
+ * CLI then ignores the user/project MCP config), and the only servers loaded
55
+ * inline are the persona's declared `mcpServers:` (`declaredMcpServers`),
56
+ * each resolved in `knownMcpServers` via personaToolScopeArgs. A declared
57
+ * name that resolves nowhere throws { code: 'capability_unknown' } — it never
58
+ * widens to every server. The caller's explicit `runtime.mcpConfig` files are
59
+ * still appended to the same --mcp-config list.
60
+ *
61
+ * runtime.appendSystemPrompt → '--append-system-prompt', <text> right after the
62
+ * --system-prompt pair (single-valued, so never in the variadic block).
63
+ * runtime.disallowedTools (non-empty) → one '--disallowedTools=<rule>' argv
64
+ * element per rule, in order, after --tools. The '=' form is required: after a
65
+ * bare variadic '--disallowedTools' the CLI takes only the first value
66
+ * literally and parses any later value starting with '-' as a NEW flag, so
67
+ * ['X', '--mcp-config', '/x.json'] would inject a flag and drop the deny.
68
+ * Repeated '=' elements accumulate. Rules are never joined: the CLI splits one
69
+ * element on commas and spaces outside parentheses, so one bad rule could
70
+ * swallow the rest. The route has already refused unbalanced rules and rules
71
+ * not starting with a letter.
72
+ *
73
+ * @param {{ model: string, effort: string, runtime?: Record<string, any>, projectCwd?: string,
74
+ * declaredMcpServers?: readonly string[], knownMcpServers?: Record<string, object> }} o
49
75
  * @returns {string[]}
50
76
  */
51
- function buildTaskArgs({ model, effort, runtime, projectCwd } = /** @type {any} */ ({})) {
77
+ function buildTaskArgs({ model, effort, runtime, projectCwd, declaredMcpServers = [], knownMcpServers = {} } = /** @type {any} */ ({})) {
52
78
  if (!nonEmptyString(model)) throw new Error('buildTaskArgs: model is required');
53
79
  if (!nonEmptyString(effort)) throw new Error('buildTaskArgs: effort is required');
54
80
  const rt = runtime && typeof runtime === 'object' ? runtime : {};
@@ -59,9 +85,10 @@ function buildTaskArgs({ model, effort, runtime, projectCwd } = /** @type {any}
59
85
  if (nonEmptyString(rt.resume)) args.push('--resume', rt.resume);
60
86
  if (!(rt.persistSession === true || nonEmptyString(rt.resume))) args.push('--no-session-persistence');
61
87
  if (typeof rt.settingSources === 'string') args.push('--setting-sources', rt.settingSources);
62
- if (rt.strictMcpConfig === true) args.push('--strict-mcp-config');
88
+ args.push('--strict-mcp-config');
63
89
  if (rt.maxTurns !== undefined && rt.maxTurns !== null) args.push('--max-turns', String(rt.maxTurns));
64
90
  if (typeof rt.systemPrompt === 'string') args.push('--system-prompt', rt.systemPrompt);
91
+ if (typeof rt.appendSystemPrompt === 'string') args.push('--append-system-prompt', rt.appendSystemPrompt);
65
92
  if (rt.dangerouslySkipPermissions === true) {
66
93
  // Tool-rules level of the job sandbox policy: bypass kept, home secrets denied.
67
94
  // '--settings' takes one value, so it sits here, not in the variadic block below.
@@ -74,12 +101,24 @@ function buildTaskArgs({ model, effort, runtime, projectCwd } = /** @type {any}
74
101
  }
75
102
 
76
103
  // Variadic flags last-but-one: a following flag (--output-format) always ends their list.
104
+ const strict = personaToolScopeArgs(null, { mcpServers: knownMcpServers || {}, declaredServers: declaredMcpServers || [] });
105
+ if (strict.refusal) {
106
+ const err = /** @type {Error & { code?: string }} */ (new Error(`buildTaskArgs: declared MCP server '${strict.refusal.name}' is not a known server`));
107
+ err.code = strict.refusal.code;
108
+ throw err;
109
+ }
110
+ const at = strict.args.indexOf('--mcp-config');
111
+ const declaredInline = at === -1 ? [] : [strict.args[at + 1]];
77
112
  const mcp = rt.mcpConfig === undefined || rt.mcpConfig === null
78
- ? null
113
+ ? []
79
114
  : (Array.isArray(rt.mcpConfig) ? rt.mcpConfig : [rt.mcpConfig]);
80
- if (mcp && mcp.length) args.push('--mcp-config', ...mcp.map((p) => path.resolve(base, String(p))));
115
+ const mcpList = [...declaredInline, ...mcp.map((p) => path.resolve(base, String(p)))];
116
+ if (mcpList.length) args.push('--mcp-config', ...mcpList);
81
117
  if (Array.isArray(rt.allowedTools)) args.push('--allowedTools', rt.allowedTools.join(','));
82
118
  if (Array.isArray(rt.tools)) args.push('--tools', rt.tools.join(','));
119
+ if (Array.isArray(rt.disallowedTools) && rt.disallowedTools.length) {
120
+ for (const rule of rt.disallowedTools) args.push('--disallowedTools=' + String(rule));
121
+ }
83
122
 
84
123
  if (rt.outputFormat === 'stream-json') args.push('--output-format', 'stream-json', '--verbose');
85
124
  else args.push('--output-format', 'json');
@@ -95,12 +134,13 @@ function buildTaskArgs({ model, effort, runtime, projectCwd } = /** @type {any}
95
134
  }
96
135
 
97
136
  /**
98
- * baseEnv + the three Task markers. No other caller env is ever added.
137
+ * baseEnv (secret-shaped keys stripped) + the three Task markers. No other
138
+ * caller env is ever added.
99
139
  * @param {Record<string, any>} runtime
100
140
  * @param {Record<string, string|undefined>} baseEnv
101
141
  */
102
142
  function buildTaskEnv(runtime, baseEnv) {
103
- const env = withProcRole({ ...(baseEnv || {}), SM_KG_INTERNAL: '1' }, PROC_ROLE);
143
+ const env = withProcRole({ ...stripCredentials(baseEnv), SM_KG_INTERNAL: '1' }, PROC_ROLE);
104
144
  if (runtime && runtime.disableAutoMemory === true) env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = '1';
105
145
  return env;
106
146
  }
@@ -160,6 +200,12 @@ function parseResetsAt(stdout) {
160
200
  return out;
161
201
  }
162
202
 
203
+ /** ISO resetsAt of one rejected rate_limit_event object, else null (same conversion as parseResetsAt). */
204
+ function resetsAtOf(ev) {
205
+ const r = Number(ev && ev.rate_limit_info && ev.rate_limit_info.resetsAt);
206
+ return Number.isFinite(r) && r > 0 ? new Date(r < 1e12 ? r * 1000 : r).toISOString() : null;
207
+ }
208
+
163
209
  /** Text form of an envelope for callers that want `--output-format text` stdout. */
164
210
  function textStdoutFor(envelope) {
165
211
  const r = envelope && typeof envelope.result === 'string' ? envelope.result : '';
@@ -169,10 +215,66 @@ function textStdoutFor(envelope) {
169
215
  /**
170
216
  * Spawn claude, feed the prompt on stdin, capture. Resolves — never throws.
171
217
  *
218
+ * onStdoutLine(line): called once per complete stdout line, in order ('\n' and a
219
+ * trailing '\r' removed), and once at close for a final unterminated line. It sees
220
+ * every line, including those after the MAX_STDOUT_BYTES capture cap; a single
221
+ * line longer than the cap is delivered truncated to MAX_STDOUT_BYTES. A throwing
222
+ * callback never changes the run's result.
223
+ *
224
+ * Result gains stdoutCapped: true when the cap cut stdout. When capped, the last
225
+ * `type: 'result'` line seen line by line becomes the envelope, and a rejected
226
+ * rate_limit_event seen after the cap still sets quota.rateLimited / resetsAt.
227
+ *
228
+ * @param {{ args: string[], env: Record<string, string|undefined>, prompt: string, cwd: string,
229
+ * timeoutMs?: number, signal?: AbortSignal, onSpawn?: (pid: number) => void,
230
+ * Artifacts: with a `taskId`, the child gets SM_ARTIFACTS_DIR =
231
+ * artifactStore.stagingDirFor({ runId: taskId }) (outside the repo), and when
232
+ * the run ends that folder is ingested into artifacts/_tasks/<taskId>/ under
233
+ * `projectRoot` (default `cwd`) BEFORE the result resolves. Result gains
234
+ * `artifacts: { published, skipped } | null`. Staging/ingest failures are
235
+ * logged and never change the run's status.
236
+ * The emptied staging folder is then removed (rmdirSync, never recursive); a
237
+ * folder still holding files is kept and logged.
238
+ *
172
239
  * @param {{ args: string[], env: Record<string, string|undefined>, prompt: string, cwd: string,
173
- * timeoutMs?: number, signal?: AbortSignal, onSpawn?: (pid: number) => void }} o
240
+ * timeoutMs?: number, signal?: AbortSignal, onSpawn?: (pid: number) => void,
241
+ * onStdoutLine?: (line: string) => void, taskId?: string, projectRoot?: string, deps?: Record<string, any> }} o
174
242
  */
175
- async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, onSpawn, deps = {} } = /** @type {any} */ ({})) {
243
+ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, onSpawn, onStdoutLine, taskId, projectRoot, deps = {} } = /** @type {any} */ ({})) {
244
+ const store = deps.artifactStore || artifactStore;
245
+ /** @type {string|null} */
246
+ let artifactsDir = null;
247
+ if (typeof taskId === 'string' && taskId) {
248
+ try { artifactsDir = store.stagingDirFor({ runId: taskId }); } catch (e) {
249
+ console.error('[taskRun] artifact staging dir unavailable', taskId, (e && e.message) || e);
250
+ }
251
+ }
252
+ const result = await spawnTask({ args, env: artifactsDir ? { ...(env || {}), SM_ARTIFACTS_DIR: artifactsDir } : env, prompt, cwd, timeoutMs, signal, onSpawn, onStdoutLine, deps });
253
+ if (!artifactsDir) return { ...result, artifacts: null };
254
+ /** @type {any} */
255
+ let artifacts = null;
256
+ try {
257
+ artifacts = await store.ingestDir({
258
+ projectRoot: projectRoot || cwd, taskId, srcDir: artifactsDir, producer: { taskId },
259
+ });
260
+ for (const sk of (artifacts && artifacts.skipped) || []) console.error('[taskRun] artifact not ingested', sk.path, sk.reason);
261
+ } catch (e) {
262
+ console.error('[taskRun] artifact ingest failed', taskId, (e && e.message) || e);
263
+ }
264
+ // The folder is per-Task and single-use: drop it once ingest emptied it. Never recursive —
265
+ // anything left behind (skipped / failed ingest) stays for the daily staging sweep.
266
+ try {
267
+ nodeFs.rmdirSync(artifactsDir);
268
+ } catch (e) {
269
+ const code = e && e.code;
270
+ if (code === 'ENOTEMPTY' || code === 'EEXIST') console.error('[taskRun] artifact staging folder kept (not empty)', artifactsDir);
271
+ else if (code !== 'ENOENT') console.error('[taskRun] artifact staging folder not removed', artifactsDir, (e && e.message) || e);
272
+ }
273
+ return { ...result, artifacts };
274
+ }
275
+
276
+ /** runTask without the artifacts step. Resolves — never throws. */
277
+ async function spawnTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, onSpawn, onStdoutLine, deps = {} } = /** @type {any} */ ({})) {
176
278
  const startedAt = Date.now();
177
279
  const base = () => ({
178
280
  status: /** @type {string} */ ('spawn_failed'),
@@ -188,6 +290,7 @@ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, on
188
290
  sessionId: null,
189
291
  durationMs: 0,
190
292
  quota: { rateLimited: false, resetsAt: null },
293
+ stdoutCapped: false,
191
294
  });
192
295
  try { await ensureCliCapsProbed(); } catch { /* probe is best effort */ }
193
296
  if (signal && signal.aborted) return { ...base(), status: 'caller_gone', durationMs: Date.now() - startedAt };
@@ -209,6 +312,64 @@ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, on
209
312
  let stdout = '';
210
313
  let stdoutBytes = 0;
211
314
  let stderrTail = '';
315
+ let stdoutCapped = false;
316
+
317
+ // Line splitter over EVERY stdout byte (not just the captured ones).
318
+ // O(bytes) total: each chunk is decoded once and scanned once for '\n';
319
+ // only one partial line is held, never more than MAX_STDOUT_BYTES of it.
320
+ const decoder = new StringDecoder('utf8');
321
+ let partial = '';
322
+ let partialBytes = 0;
323
+ let droppingLine = false; // the current line already overflowed and was delivered truncated
324
+ /** @type {any} */
325
+ let lastResult = null;
326
+ let sawRejectedRateLimit = false;
327
+ /** @type {string|null} */
328
+ let lastRejectedResetsAt = null;
329
+ const deliver = (line) => {
330
+ if (typeof onStdoutLine === 'function') {
331
+ try { onStdoutLine(line); } catch { /* caller hook must not break the run */ }
332
+ }
333
+ if (line[0] !== '{' || !(line.includes('"result"') || line.includes('rate_limit_event'))) return;
334
+ let ev;
335
+ try { ev = JSON.parse(line); } catch { return; }
336
+ if (!ev || typeof ev !== 'object') return;
337
+ if (ev.type === 'result') lastResult = ev;
338
+ else if (ev.type === 'rate_limit_event' && ev.rate_limit_info && ev.rate_limit_info.status === 'rejected') {
339
+ sawRejectedRateLimit = true;
340
+ const r = resetsAtOf(ev);
341
+ if (r) lastRejectedResetsAt = r;
342
+ }
343
+ };
344
+ const feedLines = (str) => {
345
+ let start = 0;
346
+ for (;;) {
347
+ const nl = str.indexOf('\n', start);
348
+ const piece = nl === -1 ? str.slice(start) : str.slice(start, nl);
349
+ if (!droppingLine && piece) {
350
+ partial += piece;
351
+ partialBytes += Buffer.byteLength(piece, 'utf8');
352
+ if (partialBytes > MAX_STDOUT_BYTES) {
353
+ deliver(Buffer.from(partial, 'utf8').subarray(0, MAX_STDOUT_BYTES).toString('utf8'));
354
+ partial = '';
355
+ partialBytes = 0;
356
+ droppingLine = true;
357
+ }
358
+ }
359
+ if (nl === -1) return;
360
+ if (!droppingLine) deliver(partial.endsWith('\r') ? partial.slice(0, -1) : partial);
361
+ partial = '';
362
+ partialBytes = 0;
363
+ droppingLine = false;
364
+ start = nl + 1;
365
+ }
366
+ };
367
+ const flushLines = () => {
368
+ feedLines(decoder.end());
369
+ if (!droppingLine && partial) deliver(partial.endsWith('\r') ? partial.slice(0, -1) : partial);
370
+ partial = '';
371
+ partialBytes = 0;
372
+ };
212
373
 
213
374
  const finish = (r) => {
214
375
  if (settled) return;
@@ -224,6 +385,7 @@ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, on
224
385
  };
225
386
 
226
387
  try {
388
+ assertNoCredentials(env, { site: 'task' });
227
389
  const bin = resolveClaudeBin();
228
390
  let target = claudeSpawnTarget(PROC_ROLE, PROC_DETAIL, bin, args);
229
391
  let spawnArgs = target.args || args;
@@ -260,9 +422,11 @@ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, on
260
422
  }
261
423
 
262
424
  child.stdout.on('data', (d) => {
263
- if (stdoutBytes >= MAX_STDOUT_BYTES) return;
264
- const room = MAX_STDOUT_BYTES - stdoutBytes;
265
425
  const buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
426
+ try { feedLines(decoder.write(buf)); } catch { /* line tracking must not break capture */ }
427
+ if (stdoutBytes >= MAX_STDOUT_BYTES) { if (buf.length) stdoutCapped = true; return; }
428
+ const room = MAX_STDOUT_BYTES - stdoutBytes;
429
+ if (buf.length > room) stdoutCapped = true;
266
430
  const take = buf.length > room ? buf.subarray(0, room) : buf;
267
431
  stdout += take.toString('utf8');
268
432
  stdoutBytes += take.length;
@@ -283,9 +447,13 @@ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, on
283
447
  }
284
448
 
285
449
  child.on('close', (code, sig) => {
286
- const envelope = parseEnvelope(stdout);
450
+ try { flushLines(); } catch { /* line tracking must not break the result */ }
451
+ // Under the cap the captured stdout is authoritative (unchanged behavior);
452
+ // once capped, the line-tracked state is what survived past the cut.
453
+ const envelope = stdoutCapped ? (lastResult || parseEnvelope(stdout)) : (parseEnvelope(stdout) || lastResult);
287
454
  const rateLimited = detectRateLimitInText(stdout)
288
- || (envelope ? detectRateLimitInText(JSON.stringify(envelope)) : false);
455
+ || (envelope ? detectRateLimitInText(JSON.stringify(envelope)) : false)
456
+ || (stdoutCapped && sawRejectedRateLimit);
289
457
  let status;
290
458
  if (killedFor) status = killedFor;
291
459
  else if (rateLimited) status = 'rate_limited';
@@ -304,7 +472,8 @@ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, on
304
472
  numTurns: envelope && typeof envelope.num_turns === 'number' ? envelope.num_turns : null,
305
473
  sessionId: (envelope && typeof envelope.session_id === 'string' && envelope.session_id) || null,
306
474
  durationMs: 0,
307
- quota: { rateLimited, resetsAt: rateLimited ? parseResetsAt(stdout) : null },
475
+ quota: { rateLimited, resetsAt: rateLimited ? (parseResetsAt(stdout) || lastRejectedResetsAt) : null },
476
+ stdoutCapped,
308
477
  });
309
478
  });
310
479
  });
@@ -5,7 +5,11 @@
5
5
  *
6
6
  * One MACHINE-LEVEL file (schedulerPaths.taskSwitchesPath(), beside the slot
7
7
  * config) keyed by absolute project cwd (normalized with path.resolve):
8
- * { "v": 1, "projects": { "/abs/cwd": { "enabled": true, "changedAt": "ISO" } } }
8
+ * { "v": 1, "projects": { "/abs/cwd": { "enabled": true, "changedAt": "ISO", "by": {...} } } }
9
+ * `by` records WHO made the last change: { via: 'ui' } or
10
+ * { via: 'agent', claudeSessionId, quote, promptAt }. An entry without a
11
+ * well-formed `by` (one written before attribution, or by hand) reads as
12
+ * { via: 'unknown' }; reads never rewrite the file.
9
13
  * It lives outside every project ops root, so opsOwnership does not govern it.
10
14
  *
11
15
  * Readers: the Task admin route (refuses with 403 while a project is off), the
@@ -13,10 +17,12 @@
13
17
  * instead of scanning ~/.claude/projects), and the held interactive slot (on
14
18
  * only while anyTaskSwitchOn()).
15
19
  *
16
- * HUMAN-ONLY WRITER: the switch is a human decision. Only the renderer IPC
17
- * handler (tasks/taskIpc.cjs) may call setTaskSwitch. No admin route, MCP tool,
18
- * script or agent-facing surface may write it — a script that could flip its
19
- * own permission would make the switch meaningless.
20
+ * EXACTLY TWO WRITERS: the switch is a human decision, recorded with who made it.
21
+ * - tasks/taskIpc.cjs (tasks:set-switch) is a human click: by.via 'ui'.
22
+ * - The agent route POST /admin/tasks/switch (lib/tasks/taskSwitchRoute.cjs)
23
+ * writes by.via 'agent', and only on a verified human quote.
24
+ * Any other write (a direct module call, a hand edit) is outside the law and
25
+ * reads as by.via 'unknown'. The switch is a consent gate, not a sandbox.
20
26
  *
21
27
  * Switching off keeps the entry (enabled:false + changedAt) so the project
22
28
  * stays listed. Reads are cached by file mtime (one statSync per read); a
@@ -30,7 +36,7 @@ const atomicFs = require('../util/atomicFs.cjs');
30
36
 
31
37
  const VERSION = 1;
32
38
 
33
- /** @type {{ file: string, mtimeMs: number, data: Record<string, { enabled: boolean, changedAt: string }> } | null} */
39
+ /** @type {{ file: string, mtimeMs: number, data: Record<string, { enabled: boolean, changedAt: string, by: object | null }> } | null} */
34
40
  let cache = null;
35
41
 
36
42
  function normalizeCwd(cwd) {
@@ -38,6 +44,33 @@ function normalizeCwd(cwd) {
38
44
  return path.resolve(cwd);
39
45
  }
40
46
 
47
+ const BY_ERROR = "setTaskSwitch: by must be {via:'ui'} or {via:'agent', claudeSessionId, quote, promptAt}";
48
+ const UNKNOWN_BY = Object.freeze({ via: 'unknown' });
49
+
50
+ function boundedString(v, max) {
51
+ return typeof v === 'string' && v.length >= 1 && v.length <= max;
52
+ }
53
+
54
+ /**
55
+ * Normalized copy of a well-formed attribution, or null.
56
+ * { via:'ui' } exactly; agent keeps exactly claudeSessionId (1-128),
57
+ * quote (1-2000), promptAt (parseable ISO string).
58
+ */
59
+ function validBy(by) {
60
+ if (!by || typeof by !== 'object' || Array.isArray(by)) return null;
61
+ if (by.via === 'ui') {
62
+ return Object.keys(by).length === 1 ? { via: 'ui' } : null;
63
+ }
64
+ if (by.via === 'agent') {
65
+ const { claudeSessionId, quote, promptAt } = by;
66
+ if (!boundedString(claudeSessionId, 128)) return null;
67
+ if (!boundedString(quote, 2000)) return null;
68
+ if (typeof promptAt !== 'string' || promptAt.trim() === '' || Number.isNaN(Date.parse(promptAt))) return null;
69
+ return { via: 'agent', claudeSessionId, quote, promptAt };
70
+ }
71
+ return null;
72
+ }
73
+
41
74
  /** Keep only well-formed entries; anything else reads as absent (off). */
42
75
  function sanitize(parsed) {
43
76
  const out = {};
@@ -48,6 +81,7 @@ function sanitize(parsed) {
48
81
  out[path.resolve(cwd)] = {
49
82
  enabled: entry.enabled === true,
50
83
  changedAt: typeof entry.changedAt === 'string' ? entry.changedAt : '',
84
+ by: validBy(entry.by),
51
85
  };
52
86
  }
53
87
  return out;
@@ -82,24 +116,47 @@ function isTaskSwitchOn(cwd) {
82
116
  }
83
117
 
84
118
  /**
85
- * HUMAN-ONLY: call from the renderer IPC handler (taskIpc.cjs) and nowhere else.
86
- * Records { enabled, changedAt }; switching off keeps the entry.
119
+ * One of the two sanctioned writers only (see header): taskIpc.cjs with
120
+ * { via: 'ui' }, the agent route with { via: 'agent', ... }. Records
121
+ * { enabled, changedAt, by }; switching off keeps the entry. An invalid `by`
122
+ * throws before any fs call.
87
123
  */
88
- function setTaskSwitch(cwd, on) {
124
+ function setTaskSwitch(cwd, on, by) {
125
+ const attribution = validBy(by);
126
+ if (!attribution) throw new Error(BY_ERROR);
89
127
  const key = normalizeCwd(cwd);
90
128
  if (!key) throw new Error('setTaskSwitch: cwd must be a non-empty string');
91
129
  const projects = { ...readAll() };
92
- projects[key] = { enabled: on === true, changedAt: new Date().toISOString() };
130
+ projects[key] = { enabled: on === true, changedAt: new Date().toISOString(), by: attribution };
93
131
  const file = taskSwitchesPath();
94
132
  fs.mkdirSync(path.dirname(file), { recursive: true });
95
133
  atomicFs.writeJsonAtomicSync(file, { v: VERSION, projects });
96
134
  cache = null;
97
- return { cwd: key, ...projects[key] };
135
+ return { cwd: key, enabled: projects[key].enabled, changedAt: projects[key].changedAt, by: { ...attribution } };
136
+ }
137
+
138
+ /**
139
+ * One project's entry with attribution. changedAt/by null when there is no
140
+ * entry; by { via:'unknown' } for an entry without a well-formed by; null for
141
+ * a non-string or empty cwd. Never throws.
142
+ */
143
+ function getTaskSwitch(cwd) {
144
+ try {
145
+ const key = normalizeCwd(cwd);
146
+ if (!key) return null;
147
+ const entry = readAll()[key];
148
+ if (!entry) return { cwd: key, enabled: false, changedAt: null, by: null };
149
+ return { cwd: key, enabled: entry.enabled, changedAt: entry.changedAt, by: entry.by ? { ...entry.by } : { ...UNKNOWN_BY } };
150
+ } catch {
151
+ return null;
152
+ }
98
153
  }
99
154
 
100
155
  /** Every project that ever had the switch set, on or off. */
101
156
  function listTaskProjects() {
102
- return Object.entries(readAll()).map(([cwd, e]) => ({ cwd, enabled: e.enabled, changedAt: e.changedAt }));
157
+ return Object.entries(readAll()).map(([cwd, e]) => ({
158
+ cwd, enabled: e.enabled, changedAt: e.changedAt, by: e.by ? { ...e.by } : { ...UNKNOWN_BY },
159
+ }));
103
160
  }
104
161
 
105
162
  /** True while at least one project has the switch on. */
@@ -107,6 +164,20 @@ function anyTaskSwitchOn() {
107
164
  return Object.values(readAll()).some((e) => e.enabled);
108
165
  }
109
166
 
167
+ /**
168
+ * The one shared way to keep the held interactive slot in step with the file:
169
+ * setInteractiveReserve(anyTaskSwitchOn()). sessionSlots is required lazily so
170
+ * this module stays requirable without loading the slot pool. Never throws.
171
+ */
172
+ function syncInteractiveReserve() {
173
+ try {
174
+ const sessionSlots = require('../scheduler/sessionSlots.cjs');
175
+ return sessionSlots.setInteractiveReserve(anyTaskSwitchOn()) === true;
176
+ } catch {
177
+ return false;
178
+ }
179
+ }
180
+
110
181
  function _resetForTests() {
111
182
  cache = null;
112
183
  }
@@ -114,7 +185,9 @@ function _resetForTests() {
114
185
  module.exports = {
115
186
  isTaskSwitchOn,
116
187
  setTaskSwitch,
188
+ getTaskSwitch,
117
189
  listTaskProjects,
118
190
  anyTaskSwitchOn,
191
+ syncInteractiveReserve,
119
192
  _resetForTests,
120
193
  };
@@ -0,0 +1,172 @@
1
+ /**
2
+ * taskSwitchRoute.cjs — the agent path for 'Scripts may run Tasks'.
3
+ *
4
+ * POST /admin/tasks/switch (body ≤ 64 KiB)
5
+ * { enabled, humanRequestQuote, originClaudeSessionId, cwd?, originProjectRoot? }
6
+ * Sets ONE project's switch on or off, and only on a verbatim quote of what
7
+ * the human typed in the calling chat session (humanPromptLedger). Checks,
8
+ * in order, each refusal writing and auditing nothing:
9
+ * 1. 403 human_request_unverified — the quote is not in a prompt the
10
+ * human typed in originClaudeSessionId (the ledger is the only proof);
11
+ * 2. 403 quote_does_not_name_switch — the quote does not say
12
+ * 'Scripts may run Tasks' (quoteNamesTaskSwitch);
13
+ * 3. 403 quote_does_not_name_project — the target is not the calling
14
+ * session's own project and the quote does not name it
15
+ * (crossProjectFeedback.quoteNamesTarget);
16
+ * 4. 409 request_older_than_switch — the matched prompt is not later
17
+ * than the switch's last change: one human instruction authorizes one
18
+ * write, and never undoes a later click.
19
+ * Success: setTaskSwitch(target, enabled, { via:'agent', claudeSessionId,
20
+ * quote, promptAt }), one task_switch_changed audit event, the held
21
+ * interactive slot re-synced, 200 { ok, cwd, enabled, changedAt, by, previous }.
22
+ * Setting the value the switch already has re-stamps the attribution.
23
+ *
24
+ * Scripts, scheduled jobs and Tasks cannot reach this: their prompts are never
25
+ * recorded in humanPromptLedger (only the Chat view records them).
26
+ * Registered by taskAdminRoutes.cjs registerAdminRoute.
27
+ */
28
+ 'use strict';
29
+
30
+ const path = require('node:path');
31
+ const { z } = require('zod');
32
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
33
+
34
+ const MAX_SWITCH_BODY_BYTES = 64 * 1024;
35
+
36
+ const switchBodySchema = z.object({
37
+ enabled: z.boolean(),
38
+ humanRequestQuote: z.string().min(1).max(2000),
39
+ originClaudeSessionId: z.string().min(1).max(128),
40
+ cwd: z.string().min(1).optional(),
41
+ originProjectRoot: z.string().min(1).optional(),
42
+ }).strict();
43
+
44
+ const SWITCH_RE = /(^|[^a-z0-9])scripts?\s+(may|can)\s+run\s+tasks?($|[^a-z0-9])/;
45
+
46
+ /** True when the quote names the 'Scripts may run Tasks' switch (case, quote-mark, hyphen variants). */
47
+ function quoteNamesTaskSwitch(quote) {
48
+ if (typeof quote !== 'string') return false;
49
+ const q = quote
50
+ .toLowerCase()
51
+ .replace(/[-_'"‘’‚‛“”„‟′″`]/g, ' ')
52
+ .replace(/\s+/g, ' ');
53
+ return SWITCH_RE.test(q);
54
+ }
55
+
56
+ /**
57
+ * @param {{ registerRoute: Function }} adminHttp
58
+ * @param {{ findHumanPromptContaining?: Function, resolveProjectContext?: Function,
59
+ * resolveProjectRoot?: Function, taskSwitch?: any, appendAuditEvent?: Function,
60
+ * quoteNamesTarget?: Function, now?: () => number }} [deps]
61
+ */
62
+ function registerTaskSwitchRoute(adminHttp, deps = {}) {
63
+ const findPrompt = deps.findHumanPromptContaining
64
+ || ((/** @type {string} */ s, /** @type {string} */ q, /** @type {number} */ n) => require('../feedback-remote/humanPromptLedger.cjs').findHumanPromptContaining(s, q, n));
65
+ const resolveContext = deps.resolveProjectContext
66
+ || ((/** @type {any} */ o) => require('../projectRootResolve.cjs').resolveProjectContext(o));
67
+ const projectRoot = deps.resolveProjectRoot
68
+ || ((/** @type {string} */ c, /** @type {any} */ o) => require('../opsOwnership.cjs').resolveProjectRoot(c, o));
69
+ const taskSwitch = () => deps.taskSwitch || require('./taskSwitch.cjs');
70
+ const audit = deps.appendAuditEvent
71
+ || ((/** @type {string} */ k, /** @type {any} */ f) => require('../telemetry/auditLog.cjs').appendAuditEvent(k, f));
72
+ const namesTarget = deps.quoteNamesTarget
73
+ || ((/** @type {string} */ q, /** @type {string} */ c) => require('../feedback-remote/crossProjectFeedback.cjs').quoteNamesTarget(q, c));
74
+ const now = deps.now || Date.now;
75
+
76
+ adminHttp.registerRoute('POST', '/admin/tasks/switch', async (/** @type {any} */ req, /** @type {any} */ res) => {
77
+ const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
78
+ const refuse = (/** @type {number} */ status, /** @type {string} */ error, /** @type {string} */ reason) =>
79
+ sendJson(res, status, { ok: false, error, reason });
80
+
81
+ let raw;
82
+ try {
83
+ raw = await readBody(req, MAX_SWITCH_BODY_BYTES);
84
+ } catch (e) {
85
+ bad(e instanceof Error ? e.message : String(e));
86
+ return;
87
+ }
88
+ let json;
89
+ try { json = JSON.parse(raw || '{}'); } catch {
90
+ bad('body is not valid JSON');
91
+ return;
92
+ }
93
+ const parsed = switchBodySchema.safeParse(json);
94
+ if (!parsed.success) {
95
+ bad(parsed.error.issues);
96
+ return;
97
+ }
98
+ const { enabled, humanRequestQuote: quote, originClaudeSessionId, cwd: rawCwd, originProjectRoot } = parsed.data;
99
+
100
+ // The calling session's own project.
101
+ let origin = null;
102
+ try {
103
+ const ctx = resolveContext({ originClaudeSessionId, originProjectRoot });
104
+ const o = ctx && (ctx.epicCwd || ctx.cwd);
105
+ if (typeof o === 'string' && o) origin = path.resolve(o);
106
+ } catch { origin = null; }
107
+
108
+ let target = origin;
109
+ if (rawCwd !== undefined) {
110
+ try {
111
+ const root = projectRoot(rawCwd, { opsInternal: 'refuse' });
112
+ if (path.resolve(root) !== path.resolve(rawCwd)) throw new Error(`cwd is not a project root (its root is "${root}")`);
113
+ target = path.resolve(root);
114
+ } catch (e) {
115
+ bad(e instanceof Error ? e.message : String(e));
116
+ return;
117
+ }
118
+ }
119
+ if (!target) {
120
+ bad('no target project: pass cwd, or call from a Session Manager chat session whose project can be resolved');
121
+ return;
122
+ }
123
+
124
+ const found = findPrompt(originClaudeSessionId, quote, now());
125
+ if (!found) {
126
+ refuse(403, 'human_request_unverified', 'humanRequestQuote was not found in a prompt the human typed in this chat session');
127
+ return;
128
+ }
129
+ if (!quoteNamesTaskSwitch(quote)) {
130
+ refuse(403, 'quote_does_not_name_switch', "the human's quote does not name the 'Scripts may run Tasks' switch");
131
+ return;
132
+ }
133
+ if (target !== origin && !namesTarget(quote, target)) {
134
+ refuse(403, 'quote_does_not_name_project', `the target is not this session's project and the human's quote does not name it (${path.basename(target)})`);
135
+ return;
136
+ }
137
+ const current = taskSwitch().getTaskSwitch(target);
138
+ const promptMs = Number(found.at);
139
+ const changedMs = current && current.changedAt ? Date.parse(current.changedAt) : NaN;
140
+ if (!Number.isFinite(promptMs) || (Number.isFinite(changedMs) && !(promptMs > changedMs))) {
141
+ refuse(409, 'request_older_than_switch', "the human's request is not newer than the switch's last change; ask the human again");
142
+ return;
143
+ }
144
+
145
+ const promptAt = new Date(promptMs).toISOString();
146
+ let saved;
147
+ try {
148
+ saved = taskSwitch().setTaskSwitch(target, enabled, { via: 'agent', claudeSessionId: originClaudeSessionId, quote, promptAt });
149
+ } catch (e) {
150
+ sendJson(res, 500, { ok: false, error: 'switch_write_failed', details: e instanceof Error ? e.message : String(e) });
151
+ return;
152
+ }
153
+ try {
154
+ audit('task_switch_changed', { cwd: saved.cwd, enabled: saved.enabled, via: 'agent', claudeSessionId: originClaudeSessionId, quote });
155
+ } catch { /* audit is best-effort, like taskIpc */ }
156
+ try { taskSwitch().syncInteractiveReserve(); } catch { /* a failed sync never changes the response */ }
157
+
158
+ sendJson(res, 200, {
159
+ ok: true,
160
+ cwd: saved.cwd,
161
+ enabled: saved.enabled,
162
+ changedAt: saved.changedAt,
163
+ by: saved.by,
164
+ previous: {
165
+ enabled: !!(current && current.enabled),
166
+ by: current ? current.by : null,
167
+ },
168
+ });
169
+ });
170
+ }
171
+
172
+ module.exports = { registerTaskSwitchRoute, quoteNamesTaskSwitch, MAX_SWITCH_BODY_BYTES };