claude-code-session-manager 0.139.0 → 0.140.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 (150) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  3. package/dist/assets/History--JwsFnbn.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-ijEXs--3.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-CALyU0pe.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-sdlA-fUb.js} +1 -1
  7. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-DtRzghn5.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-DApeu7x8.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-B7qLXRAH.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-DtStfv1H.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-ydfnwepc.js} +1 -1
  14. package/dist/assets/index-CtxruO1L.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/develop/SKILL.md +26 -19
  23. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  32. package/scripts/README.md +1 -0
  33. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  34. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  35. package/scripts/ops-sweep.cjs +53 -23
  36. package/scripts/scheduler-mcp-server.cjs +200 -18
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/config.cjs +112 -8
  39. package/src/main/docEdit.cjs +6 -1
  40. package/src/main/files.cjs +7 -27
  41. package/src/main/health.cjs +48 -15
  42. package/src/main/historyAggregator.cjs +88 -5
  43. package/src/main/historyDashboard.cjs +69 -4
  44. package/src/main/index.cjs +56 -2
  45. package/src/main/ipcSchemas.cjs +112 -16
  46. package/src/main/lib/AGENTS.md +54 -0
  47. package/src/main/lib/CLAUDE.md +1 -54
  48. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  49. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  50. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  51. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  52. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  53. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  54. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  55. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  56. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  57. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  58. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  59. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  60. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  61. package/src/main/lib/ephemeralCwd.cjs +37 -2
  62. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  63. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  64. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  65. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  66. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  67. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  68. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  69. package/src/main/lib/externalContract.cjs +31 -5
  70. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  71. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  72. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  73. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  75. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  76. package/src/main/lib/git/branchSweep.cjs +209 -4
  77. package/src/main/lib/git/gitWorktree.cjs +41 -5
  78. package/src/main/lib/guardShims.cjs +1 -1
  79. package/src/main/lib/historyRollup.cjs +26 -0
  80. package/src/main/lib/insideHome.cjs +27 -1
  81. package/src/main/lib/mcpToolCatalog.cjs +122 -12
  82. package/src/main/lib/mdDocCensus.cjs +59 -78
  83. package/src/main/lib/mdDocRefs.cjs +71 -93
  84. package/src/main/lib/mdNetworkScan.cjs +245 -250
  85. package/src/main/lib/mdReviewRecord.cjs +22 -9
  86. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  87. package/src/main/lib/opsOwnership.cjs +18 -2
  88. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  89. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  90. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  91. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  92. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  93. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  96. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  97. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  98. package/src/main/lib/prd/prdCreate.cjs +351 -23
  99. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  100. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  101. package/src/main/lib/process/loginItem.cjs +171 -0
  102. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  103. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  104. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  105. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  106. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  107. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  108. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  109. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  110. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  111. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  112. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  113. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  114. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  115. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  116. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  117. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  118. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  119. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  120. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  121. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  122. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  123. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  124. package/src/main/lib/tasks/taskRun.cjs +313 -0
  125. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  126. package/src/main/loginItemIpc.cjs +35 -0
  127. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  128. package/src/main/projectPages.cjs +6 -15
  129. package/src/main/promptSessionEvents.cjs +9 -1
  130. package/src/main/queueOps.cjs +260 -3
  131. package/src/main/runVerify.cjs +53 -25
  132. package/src/main/scheduler/AGENTS.md +26 -0
  133. package/src/main/scheduler/CLAUDE.md +1 -26
  134. package/src/main/scheduler/budget.cjs +239 -9
  135. package/src/main/scheduler/cancelDependents.cjs +154 -0
  136. package/src/main/scheduler/prdParser.cjs +4 -1
  137. package/src/main/scheduler/starvation.cjs +20 -18
  138. package/src/main/scheduler.cjs +745 -64
  139. package/src/main/supervisor.cjs +5 -1
  140. package/src/main/templates/PRD_AUTHORING.md +6 -1
  141. package/src/main/validationQualityHandlers.cjs +199 -0
  142. package/src/main/webRemote.cjs +10 -2
  143. package/src/preload/api.d.ts +364 -21
  144. package/src/preload/apiSurface.json +89 -10
  145. package/src/preload/index.cjs +23 -2
  146. package/src/seed/agents/validator.md +19 -8
  147. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  148. package/dist/assets/History-DDnqaLyw.js +0 -2
  149. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  150. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -0,0 +1,313 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * taskRun.cjs — run ONE headless `claude -p` for a Task.
5
+ *
6
+ * The Task primitive's spawn half. Explicit --model and --effort, the caller's
7
+ * runtime flags passed through unchanged, the prompt on stdin (never argv —
8
+ * E2BIG), and a structured result: exit, stdout, parsed JSON envelope, usage
9
+ * and quota state.
10
+ *
11
+ * Deliberately NOT here:
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);
15
+ * - ledger writes / HTTP.
16
+ *
17
+ * Spawn pattern mirrors lib/claude/runClaudeP.cjs (resolveClaudeBin,
18
+ * claudeSpawnTarget, feedChildStdin) inside a memory scope like chatRunner.cjs.
19
+ */
20
+
21
+ const path = require('node:path');
22
+ const os = require('node:os');
23
+ const { spawn: nodeSpawn } = require('node:child_process');
24
+ const { resolveClaudeBin, claudeSpawnTarget } = require('../claude/claudeBin.cjs');
25
+ const { headlessPermissionArgs, ensureCliCapsProbed } = require('../claude/claudeCliCaps.cjs');
26
+ const { detectRateLimitInText } = require('../claude/rateLimitDetect.cjs');
27
+ const { feedChildStdin } = require('../process/childStdin.cjs');
28
+ const { withProcRole } = require('../process/cleanEnv.cjs');
29
+ const { killTree, detachedSpawnOpts } = require('../process/killTree.cjs');
30
+ const memoryScope = require('../process/memoryScope.cjs');
31
+ const { writeToolRiskGuardSettingsFile } = require('../epic/guardSpawnSettings.cjs');
32
+ const { buildJobSandboxSettings } = require('../claude/jobSandboxPolicy.cjs');
33
+
34
+ const MAX_STDOUT_BYTES = 8 * 1024 * 1024;
35
+ const STDERR_TAIL_BYTES = 16 * 1024;
36
+ const MAX_ARG_BYTES = 100 * 1024;
37
+ const PROC_ROLE = 'aux';
38
+ const PROC_DETAIL = 'task';
39
+
40
+ function nonEmptyString(v) {
41
+ return typeof v === 'string' && v.trim() !== '';
42
+ }
43
+
44
+ /**
45
+ * Build the claude argv for a Task. Pure (reads only the cached CLI-caps probe
46
+ * via headlessPermissionArgs()). Never includes the prompt.
47
+ *
48
+ * @param {{ model: string, effort: string, runtime?: Record<string, any>, projectCwd?: string }} o
49
+ * @returns {string[]}
50
+ */
51
+ function buildTaskArgs({ model, effort, runtime, projectCwd } = /** @type {any} */ ({})) {
52
+ if (!nonEmptyString(model)) throw new Error('buildTaskArgs: model is required');
53
+ if (!nonEmptyString(effort)) throw new Error('buildTaskArgs: effort is required');
54
+ const rt = runtime && typeof runtime === 'object' ? runtime : {};
55
+ const base = typeof projectCwd === 'string' && projectCwd ? projectCwd : process.cwd();
56
+
57
+ const args = ['-p', '--model', model, '--effort', effort];
58
+ if (nonEmptyString(rt.sessionId)) args.push('--session-id', rt.sessionId);
59
+ if (nonEmptyString(rt.resume)) args.push('--resume', rt.resume);
60
+ if (!(rt.persistSession === true || nonEmptyString(rt.resume))) args.push('--no-session-persistence');
61
+ if (typeof rt.settingSources === 'string') args.push('--setting-sources', rt.settingSources);
62
+ if (rt.strictMcpConfig === true) args.push('--strict-mcp-config');
63
+ if (rt.maxTurns !== undefined && rt.maxTurns !== null) args.push('--max-turns', String(rt.maxTurns));
64
+ if (typeof rt.systemPrompt === 'string') args.push('--system-prompt', rt.systemPrompt);
65
+ if (rt.dangerouslySkipPermissions === true) {
66
+ // Tool-rules level of the job sandbox policy: bypass kept, home secrets denied.
67
+ // '--settings' takes one value, so it sits here, not in the variadic block below.
68
+ const root = path.resolve(base);
69
+ const policy = buildJobSandboxSettings({
70
+ agentType: 'task', worktreeDir: root, projectRoot: root,
71
+ homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: { available: false, missing: [] },
72
+ });
73
+ args.push(...policy.argv, ...headlessPermissionArgs());
74
+ }
75
+
76
+ // Variadic flags last-but-one: a following flag (--output-format) always ends their list.
77
+ const mcp = rt.mcpConfig === undefined || rt.mcpConfig === null
78
+ ? null
79
+ : (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))));
81
+ if (Array.isArray(rt.allowedTools)) args.push('--allowedTools', rt.allowedTools.join(','));
82
+ if (Array.isArray(rt.tools)) args.push('--tools', rt.tools.join(','));
83
+
84
+ if (rt.outputFormat === 'stream-json') args.push('--output-format', 'stream-json', '--verbose');
85
+ else args.push('--output-format', 'json');
86
+
87
+ for (const a of args) {
88
+ if (Buffer.byteLength(a, 'utf8') > MAX_ARG_BYTES) {
89
+ const err = /** @type {Error & { code?: string }} */ (new Error(`buildTaskArgs: an argv element exceeds ${MAX_ARG_BYTES} bytes`));
90
+ err.code = 'argv_too_large';
91
+ throw err;
92
+ }
93
+ }
94
+ return args;
95
+ }
96
+
97
+ /**
98
+ * baseEnv + the three Task markers. No other caller env is ever added.
99
+ * @param {Record<string, any>} runtime
100
+ * @param {Record<string, string|undefined>} baseEnv
101
+ */
102
+ function buildTaskEnv(runtime, baseEnv) {
103
+ const env = withProcRole({ ...(baseEnv || {}), SM_KG_INTERNAL: '1' }, PROC_ROLE);
104
+ if (runtime && runtime.disableAutoMemory === true) env.CLAUDE_CODE_DISABLE_AUTO_MEMORY = '1';
105
+ return env;
106
+ }
107
+
108
+ /**
109
+ * Load guard-tool-risk into a Task run: '--settings', <path> right after '-p'
110
+ * (ahead of every variadic flag) and SM_TOOL_RISK_HEADLESS='1' (no clearance —
111
+ * a Task has no PRD riskTools). A null path returns the inputs unchanged.
112
+ * Pure: never mutates args/env.
113
+ *
114
+ * @param {{ args: string[], env: Record<string, string|undefined>, settingsPath: string|null }} o
115
+ */
116
+ function withToolRiskGuard({ args, env, settingsPath }) {
117
+ if (typeof settingsPath !== 'string' || !settingsPath) return { args, env };
118
+ const a = Array.isArray(args) ? args.slice() : [];
119
+ const at = a[0] === '-p' ? 1 : 0;
120
+ a.splice(at, 0, '--settings', settingsPath);
121
+ return { args: a, env: { ...(env || {}), SM_TOOL_RISK_HEADLESS: '1' } };
122
+ }
123
+
124
+ /** Parse json stdout, or the last stream-json `type: 'result'` line. */
125
+ function parseEnvelope(stdout) {
126
+ const text = String(stdout || '').trim();
127
+ if (!text) return null;
128
+ try {
129
+ const v = JSON.parse(text);
130
+ if (v && typeof v === 'object' && !Array.isArray(v)) return v;
131
+ if (Array.isArray(v)) {
132
+ for (let i = v.length - 1; i >= 0; i--) if (v[i] && v[i].type === 'result') return v[i];
133
+ }
134
+ } catch { /* stream-json: fall through */ }
135
+ const lines = text.split('\n');
136
+ for (let i = lines.length - 1; i >= 0; i--) {
137
+ const t = lines[i].trim();
138
+ if (!t || t[0] !== '{') continue;
139
+ try {
140
+ const ev = JSON.parse(t);
141
+ if (ev && ev.type === 'result') return ev;
142
+ } catch { /* partial line */ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ /** resetsAt of the last rejected rate_limit_event, as an ISO string, else null. */
148
+ function parseResetsAt(stdout) {
149
+ let out = null;
150
+ for (const line of String(stdout || '').split('\n')) {
151
+ const t = line.trim();
152
+ if (!t || t[0] !== '{') continue;
153
+ let ev;
154
+ try { ev = JSON.parse(t); } catch { continue; }
155
+ if (!ev || ev.type !== 'rate_limit_event' || !ev.rate_limit_info) continue;
156
+ if (ev.rate_limit_info.status !== 'rejected') continue;
157
+ const r = Number(ev.rate_limit_info.resetsAt);
158
+ if (Number.isFinite(r) && r > 0) out = new Date(r < 1e12 ? r * 1000 : r).toISOString();
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /** Text form of an envelope for callers that want `--output-format text` stdout. */
164
+ function textStdoutFor(envelope) {
165
+ const r = envelope && typeof envelope.result === 'string' ? envelope.result : '';
166
+ return `${r}\n`;
167
+ }
168
+
169
+ /**
170
+ * Spawn claude, feed the prompt on stdin, capture. Resolves — never throws.
171
+ *
172
+ * @param {{ args: string[], env: Record<string, string|undefined>, prompt: string, cwd: string,
173
+ * timeoutMs?: number, signal?: AbortSignal, onSpawn?: (pid: number) => void }} o
174
+ */
175
+ async function runTask({ args, env, prompt, cwd, timeoutMs = 600_000, signal, onSpawn, deps = {} } = /** @type {any} */ ({})) {
176
+ const startedAt = Date.now();
177
+ const base = () => ({
178
+ status: /** @type {string} */ ('spawn_failed'),
179
+ exitCode: null,
180
+ signal: null,
181
+ stdout: '',
182
+ stderrTail: '',
183
+ envelope: null,
184
+ usage: null,
185
+ modelUsage: null,
186
+ cliCostUsd: null,
187
+ numTurns: null,
188
+ sessionId: null,
189
+ durationMs: 0,
190
+ quota: { rateLimited: false, resetsAt: null },
191
+ });
192
+ try { await ensureCliCapsProbed(); } catch { /* probe is best effort */ }
193
+ if (signal && signal.aborted) return { ...base(), status: 'caller_gone', durationMs: Date.now() - startedAt };
194
+
195
+ // guard-tool-risk (PRD scheduler-tool-risk-wiring): a null settings path
196
+ // never blocks the run — log one line and spawn without it.
197
+ const writeRiskSettings = deps.writeToolRiskGuardSettingsFile || writeToolRiskGuardSettingsFile;
198
+ let settingsPath = null;
199
+ try { settingsPath = await writeRiskSettings({ homeDir: os.homedir() }); } catch { settingsPath = null; }
200
+ if (!settingsPath) console.warn('[taskRun] tool-risk guard settings unavailable; running the Task without guard-tool-risk');
201
+ ({ args, env } = withToolRiskGuard({ args, env, settingsPath }));
202
+
203
+ return new Promise((resolve) => {
204
+ let settled = false;
205
+ let child = null;
206
+ let timer = null;
207
+ let onAbort = null;
208
+ let killedFor = null; // 'timeout' | 'caller_gone'
209
+ let stdout = '';
210
+ let stdoutBytes = 0;
211
+ let stderrTail = '';
212
+
213
+ const finish = (r) => {
214
+ if (settled) return;
215
+ settled = true;
216
+ if (timer) clearTimeout(timer);
217
+ if (signal && onAbort) { try { signal.removeEventListener('abort', onAbort); } catch { /* */ } }
218
+ resolve({ ...r, durationMs: Date.now() - startedAt });
219
+ };
220
+ const kill = (why) => {
221
+ if (killedFor || !child) return;
222
+ killedFor = why;
223
+ if (!killTree(child.pid, 'SIGKILL')) { try { child.kill('SIGKILL'); } catch { /* already dead */ } }
224
+ };
225
+
226
+ try {
227
+ const bin = resolveClaudeBin();
228
+ let target = claudeSpawnTarget(PROC_ROLE, PROC_DETAIL, bin, args);
229
+ let spawnArgs = target.args || args;
230
+ const limits = memoryScope.memoryLimitsFor({ totalRamMb: Math.floor(os.totalmem() / 1048576) });
231
+ if (limits && memoryScope.scopeSupported()) {
232
+ const unit = `sm-task-${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
233
+ const wrapped = memoryScope.wrapInMemoryScope({ command: target.command, args: spawnArgs, unit, limits });
234
+ // argv0 cannot pass through systemd-run — dropped on the wrapped path only.
235
+ target = { ...target, command: wrapped.command, argv0: undefined };
236
+ spawnArgs = wrapped.args;
237
+ }
238
+ child = nodeSpawn(target.command, spawnArgs, {
239
+ cwd,
240
+ env,
241
+ stdio: ['pipe', 'pipe', 'pipe'],
242
+ ...(target.argv0 ? { argv0: target.argv0 } : {}),
243
+ ...(target.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
244
+ ...detachedSpawnOpts(),
245
+ });
246
+ } catch (e) {
247
+ finish({ ...base(), status: 'spawn_failed', stderrTail: String((e && e.message) || e) });
248
+ return;
249
+ }
250
+
251
+ child.on('error', (e) => {
252
+ // Spawn-time failure (ENOENT, EACCES): no 'close' with a real exit follows reliably.
253
+ if (child.pid === undefined || child.exitCode === null) {
254
+ finish({ ...base(), status: 'spawn_failed', stdout, stderrTail: (stderrTail + String((e && e.message) || e)).slice(-STDERR_TAIL_BYTES) });
255
+ }
256
+ });
257
+
258
+ if (child.pid !== undefined) {
259
+ try { if (typeof onSpawn === 'function') onSpawn(child.pid); } catch { /* caller hook must not break the run */ }
260
+ }
261
+
262
+ child.stdout.on('data', (d) => {
263
+ if (stdoutBytes >= MAX_STDOUT_BYTES) return;
264
+ const room = MAX_STDOUT_BYTES - stdoutBytes;
265
+ const buf = Buffer.isBuffer(d) ? d : Buffer.from(String(d));
266
+ const take = buf.length > room ? buf.subarray(0, room) : buf;
267
+ stdout += take.toString('utf8');
268
+ stdoutBytes += take.length;
269
+ });
270
+ child.stderr.on('data', (d) => {
271
+ stderrTail += String(d);
272
+ if (stderrTail.length > STDERR_TAIL_BYTES) stderrTail = stderrTail.slice(-STDERR_TAIL_BYTES);
273
+ });
274
+
275
+ feedChildStdin(child, String(prompt == null ? '' : prompt));
276
+
277
+ if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
278
+ timer = setTimeout(() => kill('timeout'), timeoutMs);
279
+ }
280
+ if (signal) {
281
+ onAbort = () => kill('caller_gone');
282
+ signal.addEventListener('abort', onAbort, { once: true });
283
+ }
284
+
285
+ child.on('close', (code, sig) => {
286
+ const envelope = parseEnvelope(stdout);
287
+ const rateLimited = detectRateLimitInText(stdout)
288
+ || (envelope ? detectRateLimitInText(JSON.stringify(envelope)) : false);
289
+ let status;
290
+ if (killedFor) status = killedFor;
291
+ else if (rateLimited) status = 'rate_limited';
292
+ else if (code !== 0 || (envelope && envelope.is_error === true) || sig) status = 'error';
293
+ else status = 'ok';
294
+ finish({
295
+ status,
296
+ exitCode: typeof code === 'number' ? code : null,
297
+ signal: sig || null,
298
+ stdout,
299
+ stderrTail,
300
+ envelope,
301
+ usage: (envelope && envelope.usage) || null,
302
+ modelUsage: (envelope && envelope.modelUsage) || null,
303
+ cliCostUsd: envelope && typeof envelope.total_cost_usd === 'number' ? envelope.total_cost_usd : null,
304
+ numTurns: envelope && typeof envelope.num_turns === 'number' ? envelope.num_turns : null,
305
+ sessionId: (envelope && typeof envelope.session_id === 'string' && envelope.session_id) || null,
306
+ durationMs: 0,
307
+ quota: { rateLimited, resetsAt: rateLimited ? parseResetsAt(stdout) : null },
308
+ });
309
+ });
310
+ });
311
+ }
312
+
313
+ module.exports = { buildTaskArgs, buildTaskEnv, withToolRiskGuard, runTask, textStdoutFor, parseEnvelope, MAX_STDOUT_BYTES, STDERR_TAIL_BYTES, MAX_ARG_BYTES };
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * taskSwitch.cjs — the per-project human switch 'Scripts may run Tasks'.
5
+ *
6
+ * One MACHINE-LEVEL file (schedulerPaths.taskSwitchesPath(), beside the slot
7
+ * config) keyed by absolute project cwd (normalized with path.resolve):
8
+ * { "v": 1, "projects": { "/abs/cwd": { "enabled": true, "changedAt": "ISO" } } }
9
+ * It lives outside every project ops root, so opsOwnership does not govern it.
10
+ *
11
+ * Readers: the Task admin route (refuses with 403 while a project is off), the
12
+ * history surface (finds projects with Task ledgers from listTaskProjects()
13
+ * instead of scanning ~/.claude/projects), and the held interactive slot (on
14
+ * only while anyTaskSwitchOn()).
15
+ *
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
+ *
21
+ * Switching off keeps the entry (enabled:false + changedAt) so the project
22
+ * stays listed. Reads are cached by file mtime (one statSync per read); a
23
+ * missing or corrupt file reads as all-off and never throws.
24
+ */
25
+
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const { taskSwitchesPath } = require('../scheduler/schedulerPaths.cjs');
29
+ const atomicFs = require('../util/atomicFs.cjs');
30
+
31
+ const VERSION = 1;
32
+
33
+ /** @type {{ file: string, mtimeMs: number, data: Record<string, { enabled: boolean, changedAt: string }> } | null} */
34
+ let cache = null;
35
+
36
+ function normalizeCwd(cwd) {
37
+ if (typeof cwd !== 'string' || cwd.trim() === '') return null;
38
+ return path.resolve(cwd);
39
+ }
40
+
41
+ /** Keep only well-formed entries; anything else reads as absent (off). */
42
+ function sanitize(parsed) {
43
+ const out = {};
44
+ const projects = parsed && typeof parsed === 'object' ? parsed.projects : null;
45
+ if (!projects || typeof projects !== 'object' || Array.isArray(projects)) return out;
46
+ for (const [cwd, entry] of Object.entries(projects)) {
47
+ if (!entry || typeof entry !== 'object') continue;
48
+ out[path.resolve(cwd)] = {
49
+ enabled: entry.enabled === true,
50
+ changedAt: typeof entry.changedAt === 'string' ? entry.changedAt : '',
51
+ };
52
+ }
53
+ return out;
54
+ }
55
+
56
+ function readAll() {
57
+ let file;
58
+ try {
59
+ file = taskSwitchesPath();
60
+ } catch {
61
+ return {};
62
+ }
63
+ let mtimeMs;
64
+ try {
65
+ mtimeMs = fs.statSync(file).mtimeMs;
66
+ } catch {
67
+ cache = null;
68
+ return {};
69
+ }
70
+ if (cache && cache.file === file && cache.mtimeMs === mtimeMs) return cache.data;
71
+ const data = sanitize(atomicFs.readJsonOrSync(file, null));
72
+ cache = { file, mtimeMs, data };
73
+ return data;
74
+ }
75
+
76
+ /** True only when `cwd`'s switch is explicitly on. Never throws. */
77
+ function isTaskSwitchOn(cwd) {
78
+ const key = normalizeCwd(cwd);
79
+ if (!key) return false;
80
+ const entry = readAll()[key];
81
+ return !!(entry && entry.enabled);
82
+ }
83
+
84
+ /**
85
+ * HUMAN-ONLY: call from the renderer IPC handler (taskIpc.cjs) and nowhere else.
86
+ * Records { enabled, changedAt }; switching off keeps the entry.
87
+ */
88
+ function setTaskSwitch(cwd, on) {
89
+ const key = normalizeCwd(cwd);
90
+ if (!key) throw new Error('setTaskSwitch: cwd must be a non-empty string');
91
+ const projects = { ...readAll() };
92
+ projects[key] = { enabled: on === true, changedAt: new Date().toISOString() };
93
+ const file = taskSwitchesPath();
94
+ fs.mkdirSync(path.dirname(file), { recursive: true });
95
+ atomicFs.writeJsonAtomicSync(file, { v: VERSION, projects });
96
+ cache = null;
97
+ return { cwd: key, ...projects[key] };
98
+ }
99
+
100
+ /** Every project that ever had the switch set, on or off. */
101
+ function listTaskProjects() {
102
+ return Object.entries(readAll()).map(([cwd, e]) => ({ cwd, enabled: e.enabled, changedAt: e.changedAt }));
103
+ }
104
+
105
+ /** True while at least one project has the switch on. */
106
+ function anyTaskSwitchOn() {
107
+ return Object.values(readAll()).some((e) => e.enabled);
108
+ }
109
+
110
+ function _resetForTests() {
111
+ cache = null;
112
+ }
113
+
114
+ module.exports = {
115
+ isTaskSwitchOn,
116
+ setTaskSwitch,
117
+ listTaskProjects,
118
+ anyTaskSwitchOn,
119
+ _resetForTests,
120
+ };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * loginItemIpc.cjs — registers the `loginItem:*` IPC handlers over a login-item module built by
5
+ * lib/process/loginItem.cjs (createLoginItem). Local renderer only; no remote/relay command reaches it.
6
+ * loginItem:status → the module's status()
7
+ * loginItem:set-enabled { enabled: boolean } → { ok: true, status } | { ok: false, error }
8
+ */
9
+
10
+ const { z } = require('zod');
11
+
12
+ const schemas = {
13
+ setEnabled: z.object({ enabled: z.boolean() }).strict(),
14
+ };
15
+
16
+ /**
17
+ * @param {{ ipcMain: any, loginItem: { status: () => any, setEnabled: (on: boolean) => Promise<any> } }} opts
18
+ */
19
+ function registerLoginItemIpc({ ipcMain, loginItem }) {
20
+ ipcMain.handle('loginItem:status', () => loginItem.status());
21
+ ipcMain.handle('loginItem:set-enabled', async (_event, payload) => {
22
+ const parsed = schemas.setEnabled.safeParse(payload);
23
+ if (!parsed.success) {
24
+ return { ok: false, error: `Invalid payload: ${parsed.error.issues.map((i) => i.message).join('; ') || 'expected { enabled: boolean }'}` };
25
+ }
26
+ try {
27
+ const status = await loginItem.setEnabled(parsed.data.enabled);
28
+ return { ok: true, status };
29
+ } catch (e) {
30
+ return { ok: false, error: (e && e.message) || String(e) };
31
+ }
32
+ });
33
+ }
34
+
35
+ module.exports = { registerLoginItemIpc };
@@ -14,6 +14,7 @@ const path = require('path');
14
14
  const { ipcMain } = require('electron');
15
15
  const { computeLoopEfficiency } = require('./lib/scheduler/loopEfficiency.cjs');
16
16
  const { parseValidationSentinels } = require('./lib/scheduler/validationSentinels.cjs');
17
+ const { parseValidatorVerdict, verdictRowsFromStructured } = require('./lib/scheduler/validatorVerdictSchema.cjs');
17
18
 
18
19
  const WEEK_MS = 7 * 24 * 3600 * 1000;
19
20
  const LOG_TAIL_BYTES = 1024 * 1024;
@@ -60,7 +61,15 @@ async function validationsForLog(logPath) {
60
61
  if (!lines[i].includes('"type":"result"')) continue;
61
62
  try {
62
63
  const obj = JSON.parse(lines[i]);
63
- if (typeof obj.result === 'string') out = parseValidationSentinels(obj.result);
64
+ // `--json-schema` validator runs: the checked JSON is structured_output
65
+ // and `result` is its string form, so read it first. Older logs and
66
+ // non-validator runs fall back to the text sentinels.
67
+ if (obj.structured_output && parseValidatorVerdict(obj.structured_output).ok) {
68
+ out = verdictRowsFromStructured(obj.structured_output)
69
+ .map((r) => ({ slug: r.slug, verdict: r.verdict, reason: r.reason }));
70
+ } else if (typeof obj.result === 'string') {
71
+ out = parseValidationSentinels(obj.result);
72
+ }
64
73
  } catch { /* torn line — treat as no verdicts */ }
65
74
  break;
66
75
  }
@@ -96,34 +96,25 @@ async function get({ cwd }) {
96
96
 
97
97
  const MD_NETWORK_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project to scan';
98
98
 
99
- /** Strip trailing slashes ('docs/' -> 'docs'); undefined stays undefined. */
100
- const stripTrailingSlashes = (folders) => folders && folders.map((f) => f.replace(/\/+$/, ''));
101
-
102
99
  /**
103
100
  * -> MdNetworkResult: the project's markdown link network from its root
104
101
  * CLAUDE.md, scanned once per call (no watcher, no cache). `cwd` is validated
105
102
  * like get() (an invalid path rejects); a cwd get() answers with EMPTY() gets
106
- * `{ ok: false, error }`.
107
- *
108
- * `recordFolders` / `docFolders` are a human's census overrides (mark a folder
109
- * as machine-written records, or as real docs). They are only repo-relative
110
- * path prefixes for classification and never reach the file system — only
111
- * `cwd` is a path that is resolved or read.
103
+ * `{ ok: false, error }`. History folders come only from the tracked
104
+ * .session-manager.json mdNetwork.history and the census heuristic.
112
105
  */
113
- async function mdNetwork({ cwd, recordFolders, docFolders }) {
106
+ async function mdNetwork({ cwd }) {
114
107
  const { root, ephemeral } = tryProjectRoot(config.validatePath(cwd));
115
108
  if (ephemeral) return { ok: false, error: MD_NETWORK_EPHEMERAL };
116
- return scanMdNetwork(root, {}, {
117
- recordFolders: stripTrailingSlashes(recordFolders),
118
- docFolders: stripTrailingSlashes(docFolders),
119
- });
109
+ return scanMdNetwork(root);
120
110
  }
121
111
 
122
112
  const MD_REVIEW_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project review record';
123
113
 
124
114
  /**
125
115
  * -> MdReviewResult: the newest review record under reviews/docs/ and, per
126
- * given Epic id, its reviews/validation/<id>/*.md paths — read once per call
116
+ * given Epic id, its plan-records/<id>/*.md + legacy reviews/validation/<id>/
117
+ * *.md paths — read once per call
127
118
  * (no watcher, no cache). Resolves the project root like mdNetwork(); an
128
119
  * ephemeral cwd gets `{ ok: false, error }`.
129
120
  */
@@ -74,7 +74,9 @@ function mintEventId() {
74
74
  * marker like 'job-not-queued', or PRD 3116's 'build-done'/'build-failed', the
75
75
  * renderer turns into a distinct notice) and `buildOutput` (PRD 3116 — `{ kind,
76
76
  * id, title }` of a macro build's saved entry), and `reply` (`{ fromCwd,
77
- * fromEpicId, outcome, referencePaths }` — a cross-project reply's origin). All
77
+ * fromEpicId, outcome, referencePaths }` — a cross-project reply's origin, plus
78
+ * a receipt's optional `hash`/`delivery`/`toEpicId`/`fallbackEpicId`/`reason`/
79
+ * `reused`). All
78
80
  * keys are added to the event object only when present in `meta`, never as
79
81
  * `undefined`-valued keys, so events appended without them serialize
80
82
  * identically to before.
@@ -116,6 +118,12 @@ async function appendResponseEventWithReason(cwd, sourcePromptId, text, meta = {
116
118
  if (meta && meta.reply && typeof meta.reply === 'object') {
117
119
  const { fromCwd, fromEpicId, outcome, referencePaths } = meta.reply;
118
120
  event.reply = { fromCwd, fromEpicId, outcome, referencePaths };
121
+ // Receipt-only keys (the replier's dedupe hash + the delivery it
122
+ // recorded) — copied only when present, as strings / a boolean.
123
+ for (const k of ['hash', 'delivery', 'toEpicId', 'fallbackEpicId', 'reason']) {
124
+ if (typeof meta.reply[k] === 'string' && meta.reply[k]) event.reply[k] = meta.reply[k];
125
+ }
126
+ if (meta.reply.reused === true) event.reply.reused = true;
119
127
  }
120
128
  data.events[sourcePromptId] = [...events, event];
121
129
  await config.writeJson(path, data, { writer: 'scheduler' });