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
@@ -17,6 +17,7 @@ const { validated } = require('../../ipcSchemas.cjs');
17
17
  const registry = require('./agentCliRegistry.cjs');
18
18
  const { readNativeSession } = require('./agentCliSessionStore.cjs');
19
19
  const { findEpicByClaudeSessionId } = require('../claude/agentModelResolve.cjs');
20
+ const { ensureGeminiSystemDefaults } = require('./geminiContextDefaults.cjs');
20
21
 
21
22
  const detectSchema = z.object({ refresh: z.boolean().optional() }).strict();
22
23
  const terminalCommandSchema = z.object({
@@ -37,6 +38,8 @@ function withDefaults(deps) {
37
38
  readNativeSession: d.readNativeSession || readNativeSession,
38
39
  adapterFor: d.adapterFor || registry.adapterFor,
39
40
  detectAgentClis: d.detectAgentClis || registry.detectAgentClis,
41
+ ensureGeminiSystemDefaults: d.ensureGeminiSystemDefaults || ensureGeminiSystemDefaults,
42
+ platform: typeof d.platform === 'string' ? d.platform : process.platform,
40
43
  };
41
44
  }
42
45
 
@@ -89,8 +92,21 @@ async function buildTerminalCommand({ cwd, claudeSessionId }, deps) {
89
92
  } catch (e) {
90
93
  return { ok: false, message: `Could not build the ${entry.label} command: ${e && e.message ? e.message : String(e)}` };
91
94
  }
92
- const command = [binPath, ...(Array.isArray(args) ? args : [])].map(shellQuote).join(' ');
93
- return { ok: true, command };
95
+ const base = [binPath, ...(Array.isArray(args) ? args : [])].map(shellQuote).join(' ');
96
+ return { ok: true, command: geminiEnvPrefix(cli, d) + base };
97
+ }
98
+
99
+ /**
100
+ * Gemini only: `GEMINI_CLI_SYSTEM_DEFAULTS_PATH='<file>' ` so the Terminal view
101
+ * loads the same AGENTS.md map as chat turns. POSIX `VAR=value cmd` syntax, so
102
+ * win32 gets no prefix; a null/throwing defaults helper also yields ''.
103
+ */
104
+ function geminiEnvPrefix(cli, d) {
105
+ if (cli !== 'gemini' || d.platform === 'win32') return '';
106
+ let res = null;
107
+ try { res = d.ensureGeminiSystemDefaults({ platform: d.platform }); } catch { res = null; }
108
+ if (!res || typeof res.path !== 'string' || !res.path) return '';
109
+ return `GEMINI_CLI_SYSTEM_DEFAULTS_PATH=${shellQuote(res.path)} `;
94
110
  }
95
111
 
96
112
  /**
@@ -145,6 +145,7 @@ function createTranscriptWriter({ claudeSessionId, cwd, cli } = {}) {
145
145
  }
146
146
 
147
147
  module.exports = {
148
+ rootDir,
148
149
  readNativeSession,
149
150
  writeNativeSession,
150
151
  transcriptPathFor,
@@ -11,6 +11,7 @@
11
11
 
12
12
  const registry = require('./agentCliRegistry.cjs');
13
13
  const sessionStore = require('./agentCliSessionStore.cjs');
14
+ const geminiContextDefaults = require('./geminiContextDefaults.cjs');
14
15
 
15
16
  const NOOP_TRANSCRIPT = Object.freeze({ userPrompt() {}, event() {}, close() {} });
16
17
 
@@ -22,6 +23,7 @@ function withDefaults(deps) {
22
23
  catalog: d.catalog || registry.AGENT_CLI_CATALOG,
23
24
  readNativeSession: d.readNativeSession || sessionStore.readNativeSession,
24
25
  createTranscriptWriter: d.createTranscriptWriter || sessionStore.createTranscriptWriter,
26
+ ensureGeminiSystemDefaults: d.ensureGeminiSystemDefaults || geminiContextDefaults.ensureGeminiSystemDefaults,
25
27
  env: d.env || process.env,
26
28
  };
27
29
  }
@@ -37,9 +39,22 @@ function pickAuthEnv(entry, env) {
37
39
  return out;
38
40
  }
39
41
 
42
+ /**
43
+ * Gemini only: point GEMINI_CLI_SYSTEM_DEFAULTS_PATH at the SM-owned defaults
44
+ * file that adds AGENTS.md to context.fileName. Null / throw → no key, the
45
+ * turn runs exactly as before.
46
+ */
47
+ function geminiContextEnv(d) {
48
+ try {
49
+ const res = d.ensureGeminiSystemDefaults({ env: d.env });
50
+ if (res && typeof res.path === 'string' && res.path) return { GEMINI_CLI_SYSTEM_DEFAULTS_PATH: res.path };
51
+ } catch { /* best effort: no AGENTS.md map, turn still runs */ }
52
+ return {};
53
+ }
54
+
40
55
  /**
41
56
  * @param {{ epic: object, claudeSessionId: string, cwd: string, prompt: string, deps?: object }} opts
42
- * @returns {{ ok: true, command: string, args: string[], stdin: string, envExtra: Record<string,string>,
57
+ * @returns {{ ok: true, command: string, args: string[], cwd: string, stdin: string, envExtra: Record<string,string>,
43
58
  * parser: { push(line: string): object[], end(o: { exitCode: number|null }): object[] },
44
59
  * transcript: { userPrompt(t: string): void, event(e: object): void, close(): void }, cli: string }
45
60
  * | { ok: false, code: string, message: string }}
@@ -87,9 +102,12 @@ function planAgentCliTurn({ epic, claudeSessionId, cwd, prompt, deps } = {}) {
87
102
  return {
88
103
  ok: true,
89
104
  command,
105
+ // The spawn cwd is the one passed in (chatRunner passes the Epic worktree's execCwd) —
106
+ // Codex starts its AGENTS.md / CLAUDE.md walk there.
107
+ cwd,
90
108
  args: Array.isArray(spawnPlan.args) ? spawnPlan.args : [],
91
109
  stdin: typeof spawnPlan.stdin === 'string' ? spawnPlan.stdin : '',
92
- envExtra: pickAuthEnv(entry, d.env),
110
+ envExtra: cli === 'gemini' ? { ...pickAuthEnv(entry, d.env), ...geminiContextEnv(d) } : pickAuthEnv(entry, d.env),
93
111
  parser: adapter.createParser(),
94
112
  transcript,
95
113
  cli,
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+ // SM-owned Gemini CLI system-defaults file. Gemini CLI reads only GEMINI.md as
3
+ // context by default, so a Gemini Epic in an AGENTS.md project would start with
4
+ // no project map. This writes a copy of the machine's real system-defaults
5
+ // file (lowest settings layer, so user/project context.fileName still wins)
6
+ // with AGENTS.md and GEMINI.md added to context.fileName, under the agent-cli
7
+ // state root, and returns its path for GEMINI_CLI_SYSTEM_DEFAULTS_PATH.
8
+ // CLAUDE.md is deliberately NOT added: Gemini follows @-imports, so a
9
+ // CLAUDE.md stub (@AGENTS.md) beside AGENTS.md would load the map twice.
10
+ // Pure helper: injected env/platform/fs/dir; no spawn, no network.
11
+
12
+ const nodeFs = require('node:fs');
13
+ const path = require('node:path');
14
+ const { writeJsonAtomicSync } = require('../util/atomicFs.cjs');
15
+ const { rootDir } = require('./agentCliSessionStore.cjs');
16
+
17
+ const OUTPUT_FILE = 'gemini-system-defaults.json';
18
+ const CONTEXT_NAMES = ['AGENTS.md', 'GEMINI.md'];
19
+
20
+ const PLATFORM_DEFAULTS = {
21
+ linux: '/etc/gemini-cli/system-defaults.json',
22
+ darwin: '/Library/Application Support/GeminiCli/system-defaults.json',
23
+ win32: 'C:\\ProgramData\\gemini-cli\\system-defaults.json',
24
+ };
25
+
26
+ function isPlainObject(v) {
27
+ return !!v && typeof v === 'object' && !Array.isArray(v);
28
+ }
29
+
30
+ /** The path Gemini CLI itself would read system defaults from. */
31
+ function realSystemDefaultsPath({ env = process.env, platform = process.platform } = {}) {
32
+ const override = env && env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH;
33
+ if (typeof override === 'string' && override.trim()) return override;
34
+ return PLATFORM_DEFAULTS[platform] || PLATFORM_DEFAULTS.linux;
35
+ }
36
+
37
+ /**
38
+ * Read the real file. Missing → {}; unreadable, malformed, or not a JSON
39
+ * object → undefined (caller returns null and writes nothing).
40
+ */
41
+ function readRealDefaults(fs, file) {
42
+ let raw;
43
+ try {
44
+ raw = fs.readFileSync(file, 'utf8');
45
+ } catch (e) {
46
+ if (e && e.code === 'ENOENT') return {};
47
+ return undefined;
48
+ }
49
+ if (String(raw).trim() === '') return {};
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(raw);
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ return isPlainObject(parsed) ? parsed : undefined;
57
+ }
58
+
59
+ function mergedFileNames(existing) {
60
+ const base = typeof existing === 'string'
61
+ ? [existing]
62
+ : Array.isArray(existing) ? existing.filter((n) => typeof n === 'string') : [];
63
+ const out = [];
64
+ for (const n of [...base, ...CONTEXT_NAMES]) if (!out.includes(n)) out.push(n);
65
+ return out;
66
+ }
67
+
68
+ function ensureGeminiSystemDefaults({
69
+ env = process.env,
70
+ platform = process.platform,
71
+ fs = nodeFs,
72
+ dir,
73
+ } = {}) {
74
+ const real = readRealDefaults(fs, realSystemDefaultsPath({ env, platform }));
75
+ if (real === undefined) return null;
76
+ const context = isPlainObject(real.context) ? real.context : {};
77
+ const merged = {
78
+ ...real,
79
+ context: { ...context, fileName: mergedFileNames(context.fileName) },
80
+ };
81
+ const outFile = path.join(dir || rootDir(), OUTPUT_FILE);
82
+ const next = `${JSON.stringify(merged, null, 2)}\n`;
83
+ let current = null;
84
+ try { current = fs.readFileSync(outFile, 'utf8'); } catch { /* not written yet */ }
85
+ if (current !== next) writeJsonAtomicSync(outFile, merged, { mode: 0o600 });
86
+ return { path: outFile };
87
+ }
88
+
89
+ module.exports = {
90
+ ensureGeminiSystemDefaults,
91
+ realSystemDefaultsPath,
92
+ OUTPUT_FILE,
93
+ CONTEXT_NAMES,
94
+ };
@@ -201,39 +201,105 @@ function readTail(filePath, maxBytes, deps) {
201
201
  }
202
202
  }
203
203
 
204
+ // The alias families whose concrete ids carry the family name (claude-opus-5-5 for opus).
205
+ // best / opusplan / default name no single family, so they get no family check.
206
+ const MODEL_FAMILIES = new Set(['opus', 'sonnet', 'haiku', 'fable']);
207
+
208
+ /** The family an alias names ('opus[1m]' -> 'opus'), or null when it names none. */
209
+ function aliasFamily(modelAlias) {
210
+ if (!modelAlias) return null;
211
+ const base = modelAlias.replace(/\[[^\]]*\]$/, '');
212
+ return MODEL_FAMILIES.has(base) ? base : null;
213
+ }
214
+
215
+ // What a concrete model id looks like: 'claude-' then lower-case letters,
216
+ // digits, dots or hyphens, with an optional bracket suffix ('[1m]'). Anything
217
+ // else — '<synthetic>', a string torn out of quoted source text — is refused.
218
+ const MODEL_ID_SHAPE = /^claude-[a-z0-9.-]+(\[[a-z0-9]+\])?$/;
219
+
220
+ /** Each line of `text` parsed as JSON; lines that do not parse (a cut last line) are skipped. */
221
+ function parseJsonLines(text) {
222
+ const out = [];
223
+ for (const line of text.split('\n')) {
224
+ if (!line.startsWith('{')) continue;
225
+ try {
226
+ out.push(JSON.parse(line));
227
+ } catch {
228
+ // incomplete or non-JSON line — no evidence
229
+ }
230
+ }
231
+ return out;
232
+ }
233
+
234
+ /**
235
+ * True when `id` is acceptable evidence for `modelAlias`: a concrete id (never
236
+ * an alias) and, for a family alias, one whose name contains that family — so
237
+ * an opus persona can never be reported as running a fable or sonnet id.
238
+ */
239
+ function fitsAlias(id, modelAlias) {
240
+ if (typeof id !== 'string' || !MODEL_ID_SHAPE.test(id)) return false;
241
+ if (!isConcreteModelId(id)) return false;
242
+ const family = aliasFamily(modelAlias);
243
+ return !family || id.includes(family);
244
+ }
245
+
204
246
  /**
205
247
  * Evidence source 1: the scheduler already logs the persona-resolved model
206
248
  * at dispatch (scheduler.cjs's executeJob, ~line 4473: `[scheduler]
207
249
  * agentType=... persona=... model=...`). Scans this project's hot queue.json
208
250
  * jobs[] AND its archived history.jsonl for the most recent job whose
209
- * agentType matches, then reads that job's own run log for the line. O(J log
210
- * J) to sort J candidate jobs, O(min(logSize, cap)) per log read.
251
+ * agentType matches, then reads that job's own run log for the line — only
252
+ * from a line that starts with it and stands before the first JSON line, so
253
+ * the same text quoted inside a later line never counts. That line holds what
254
+ * was passed to `--model` — usually the alias itself — so when it is an alias,
255
+ * the concrete id is the `model` field of the first parsed system/init line.
256
+ * A job with no fitting, id-shaped value gives no evidence and the next newest
257
+ * job is tried. O(J log J) to sort J candidate
258
+ * jobs, O(min(logSize, cap)) per log read.
211
259
  */
212
- function findLatestSchedulerModel(cwd, agentType, deps) {
260
+ function findLatestSchedulerModel(cwd, agentType, modelAlias, deps) {
213
261
  const jobs = [...readHotJobsForCwd(cwd, deps), ...readHistoryEntriesForCwd(cwd, deps)];
214
262
  const matches = jobs.filter((j) => j && j.agentType === agentType && j.runId && j.slug);
215
263
  matches.sort((a, b) => jobTimestampMs(b) - jobTimestampMs(a));
216
264
 
217
- const re = /\[scheduler\] agentType=\S+ persona=.*? model=(\S+)/g;
265
+ const headerRe = /^\[scheduler\] agentType=\S+ persona=.*? model=(\S+)/;
218
266
  for (const job of matches) {
219
267
  const logPath = path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`);
220
268
  const head = readHead(logPath, MAX_RUN_LOG_HEAD_BYTES, deps);
221
269
  if (!head) continue;
222
- let match;
223
- let last = null;
224
- while ((match = re.exec(head))) last = match[1];
225
- if (last) return last;
270
+ const lines = head.split('\n');
271
+ // The scheduler's own header stands before the CLI's first JSON line;
272
+ // the same text inside a later (JSON) line is quoted content, not a header.
273
+ let logged = null;
274
+ let firstJson = lines.length;
275
+ for (let i = 0; i < lines.length; i++) {
276
+ if (lines[i].startsWith('{')) { firstJson = i; break; }
277
+ const m = headerRe.exec(lines[i]);
278
+ if (m && logged === null) logged = m[1];
279
+ }
280
+ if (!logged) continue;
281
+ if (isConcreteModelId(logged)) {
282
+ if (fitsAlias(logged, modelAlias)) return logged;
283
+ continue;
284
+ }
285
+ // Alias: the concrete id is the model field of the first system/init line.
286
+ const init = parseJsonLines(lines.slice(firstJson).join('\n'))
287
+ .find((o) => o && o.type === 'system' && o.subtype === 'init');
288
+ if (init && fitsAlias(init.model, modelAlias)) return init.model;
226
289
  }
227
290
  return null;
228
291
  }
229
292
 
230
293
  /**
231
294
  * Evidence source 2: the most recent Epic (active-index.json entry) created
232
- * with this agentType, read via its own claude-session transcript's last
233
- * `"model":"..."` occurrence. O(E log E) to sort E candidate Epics,
234
- * O(min(transcriptSize, cap)) per transcript read.
295
+ * with this agentType AND the model being resolved — a session whose own
296
+ * `model` override names anything else ran a different model and says
297
+ * nothing about this persona. Read via its own claude-session transcript:
298
+ * message.model of the last parsed `type:'assistant'` line that fits (so
299
+ * '<synthetic>' and quoted text never count). O(E log E) to sort E candidate
300
+ * Epics, O(min(transcriptSize, cap)) per transcript read.
235
301
  */
236
- function findLatestTranscriptModel(cwd, agentType, deps) {
302
+ function findLatestTranscriptModel(cwd, agentType, modelAlias, deps) {
237
303
  const readActiveIndex = deps.readActiveIndex || require('../epic/epicMint.cjs').readActiveIndex;
238
304
  let sessions;
239
305
  try {
@@ -241,20 +307,24 @@ function findLatestTranscriptModel(cwd, agentType, deps) {
241
307
  } catch {
242
308
  return null;
243
309
  }
244
- const matches = Object.values(sessions || {}).filter((s) => s && s.agentType === agentType && s.claudeSessionId);
310
+ const matches = Object.values(sessions || {}).filter((s) => s && s.agentType === agentType && s.claudeSessionId
311
+ && (!s.model || s.model === modelAlias));
245
312
  matches.sort((a, b) => (Date.parse(b.createdAt || 0) || 0) - (Date.parse(a.createdAt || 0) || 0));
246
313
 
247
314
  const homeDir = deps.homeDir || os.homedir();
248
- const re = /"model":"([^"]+)"/g;
249
315
  for (const session of matches) {
250
316
  const filePath = resolveEpicTranscriptPath({ cwd, claudeSessionId: session.claudeSessionId, deps: { homeDir } }).path;
251
317
  if (!filePath) continue;
252
318
  const tail = readTail(filePath, MAX_TRANSCRIPT_TAIL_BYTES, deps);
253
319
  if (!tail) continue;
254
- let match;
255
- let last = null;
256
- while ((match = re.exec(tail))) last = match[1];
257
- if (last) return last;
320
+ // message.model of the last fitting assistant line; quoted text never counts.
321
+ const entries = parseJsonLines(tail);
322
+ for (let i = entries.length - 1; i >= 0; i--) {
323
+ const e = entries[i];
324
+ if (!e || e.type !== 'assistant') continue;
325
+ const id = e.message && e.message.model;
326
+ if (fitsAlias(id, modelAlias)) return id;
327
+ }
258
328
  }
259
329
  return null;
260
330
  }
@@ -313,14 +383,14 @@ async function resolveEffectiveModelInfo({ cwd, agentType, deps = {} } = {}) {
313
383
  // (which prices any unknown id at a family fallback with estimated:true) —
314
384
  // deliberately: that is a pricing heuristic, and borrowing it here would
315
385
  // turn "we don't know" into a confident wrong answer.
316
- const schedulerHit = findLatestSchedulerModel(normalizedCwd, agentType, deps);
386
+ const schedulerHit = findLatestSchedulerModel(normalizedCwd, agentType, modelAlias, deps);
317
387
  if (schedulerHit) {
318
388
  result.resolvedModelId = schedulerHit;
319
389
  result.resolvedFrom = 'scheduler-run';
320
390
  return result;
321
391
  }
322
392
 
323
- const transcriptHit = findLatestTranscriptModel(normalizedCwd, agentType, deps);
393
+ const transcriptHit = findLatestTranscriptModel(normalizedCwd, agentType, modelAlias, deps);
324
394
  if (transcriptHit) {
325
395
  result.resolvedModelId = transcriptHit;
326
396
  result.resolvedFrom = 'transcript';
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+ // @ts-check
3
+
4
+ /**
5
+ * jobSandboxPolicy.cjs — turns a headless PRD job's persona and paths into the
6
+ * claude CLI flags that confine it.
7
+ *
8
+ * Two levels:
9
+ * - 'tool-rules' (every persona): keeps --dangerously-skip-permissions but
10
+ * passes --settings with permissions.deny Read/Edit rules over the secret
11
+ * files below. Probed on CLI 2.1.325: these rules ARE enforced under the
12
+ * bypass flag for the Read/Write tools and plain Bash cat/redirect, but
13
+ * `python3 -c open(...)` or `sh -c 'cat $1'` still read the file — tool
14
+ * rules are not containment.
15
+ * - 'os-sandbox' (validator, dev-lead, when bwrap+socat / sandbox-exec are
16
+ * present): drops the bypass flag, runs under a --permission-mode, and turns
17
+ * on the CLI's OS sandbox (Bash only — in-process tools stay governed by the
18
+ * permission rules): writes only in the worktree plus declared roots, secret
19
+ * files unreadable, Bash network limited to the profile's allowlist.
20
+ *
21
+ * Rule paths: a leading `//` is absolute; a single `/` is relative to the
22
+ * settings file — so every rule here is `//` + the absolute path sans its `/`.
23
+ *
24
+ * Pure: no fs, child_process, os or clock. The caller probes dependencies via
25
+ * sandboxDependencies({ platform, which }) and passes the result in.
26
+ */
27
+
28
+ const path = require('node:path');
29
+
30
+ /** Home-relative paths whose contents no job tool may read or write. */
31
+ const SANDBOX_SECRET_PATHS = Object.freeze([
32
+ '.npmrc',
33
+ '.netrc',
34
+ '.ssh',
35
+ '.gnupg',
36
+ 'Self/secrets',
37
+ '.claude/.credentials.json',
38
+ '.config/gh',
39
+ '.google_workspace_mcp',
40
+ '.config/google-workspace-mcp',
41
+ '.aws',
42
+ '.docker/config.json',
43
+ ]);
44
+
45
+ /**
46
+ * @typedef {{ readonly permissionMode: string, readonly network: readonly string[] }} SandboxProfile
47
+ */
48
+
49
+ /** @type {Readonly<Record<string, SandboxProfile>>} */
50
+ const SANDBOX_PROFILES = Object.freeze({
51
+ validator: Object.freeze({ permissionMode: 'default', network: Object.freeze([]) }),
52
+ 'dev-lead': Object.freeze({ permissionMode: 'acceptEdits', network: Object.freeze(['registry.npmjs.org']) }),
53
+ });
54
+
55
+ /** @type {Readonly<Record<string, readonly string[]>>} */
56
+ const PLATFORM_DEPS = Object.freeze({
57
+ linux: Object.freeze(['bwrap', 'socat']),
58
+ darwin: Object.freeze(['sandbox-exec']),
59
+ });
60
+
61
+ /**
62
+ * @param {{ platform: string, which: (name: string) => string|null }} args
63
+ * @returns {{ available: boolean, missing: string[] }}
64
+ */
65
+ function sandboxDependencies({ platform, which }) {
66
+ const needed = Object.prototype.hasOwnProperty.call(PLATFORM_DEPS, platform) ? PLATFORM_DEPS[platform] : null;
67
+ if (!needed) return { available: false, missing: [`unsupported platform: ${platform}`] };
68
+ const missing = needed.filter((name) => !which(name));
69
+ return { available: missing.length === 0, missing };
70
+ }
71
+
72
+ /** @param {string} abs */
73
+ function denyRulesFor(abs) {
74
+ const p = `/${abs.replace(/^\/+/, '')}`;
75
+ return [`Read(/${p})`, `Read(/${p}/**)`, `Edit(/${p})`, `Edit(/${p}/**)`];
76
+ }
77
+
78
+ /**
79
+ * @param {Record<string, unknown>} args
80
+ * @param {string} field
81
+ * @returns {string}
82
+ */
83
+ function requireAbs(args, field) {
84
+ const v = args[field];
85
+ if (typeof v !== 'string' || v.length === 0 || !path.isAbsolute(v)) {
86
+ throw new TypeError(`buildJobSandboxSettings: ${field} must be an absolute path (got ${JSON.stringify(v)})`);
87
+ }
88
+ return v;
89
+ }
90
+
91
+ /**
92
+ * @typedef {{
93
+ * level: 'os-sandbox'|'tool-rules',
94
+ * argv: string[],
95
+ * settings: Record<string, unknown>,
96
+ * summary: { level: 'os-sandbox'|'tool-rules', profile: string|null, network: string[]|null, reason: string|null },
97
+ * }} JobSandboxResult
98
+ */
99
+
100
+ /**
101
+ * @param {{
102
+ * agentType?: string|null,
103
+ * worktreeDir: string,
104
+ * projectRoot: string,
105
+ * homeDir: string,
106
+ * tmpDir: string,
107
+ * deps?: { available: boolean, missing?: string[] }|null,
108
+ * }} args
109
+ * @returns {JobSandboxResult}
110
+ */
111
+ function buildJobSandboxSettings(args) {
112
+ const raw = /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (args || {}));
113
+ const worktreeDir = requireAbs(raw, 'worktreeDir');
114
+ const projectRoot = requireAbs(raw, 'projectRoot');
115
+ const homeDir = requireAbs(raw, 'homeDir');
116
+ const tmpDir = requireAbs(raw, 'tmpDir');
117
+ const agentType = typeof args.agentType === 'string' && args.agentType ? args.agentType : null;
118
+ const deps = args.deps;
119
+
120
+ const secretAbs = SANDBOX_SECRET_PATHS.map((p) => path.join(homeDir, p));
121
+ const deny = secretAbs.flatMap(denyRulesFor);
122
+
123
+ const profile =
124
+ agentType && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, agentType) ? SANDBOX_PROFILES[agentType] : null;
125
+
126
+ /** @type {string|null} */
127
+ let reason = null;
128
+ if (!profile) {
129
+ reason = `no sandbox profile for persona ${agentType ?? '(none)'}`;
130
+ } else if (!deps || deps.available !== true) {
131
+ const missing = deps && Array.isArray(deps.missing) && deps.missing.length ? deps.missing : ['unknown'];
132
+ reason = `OS sandbox unavailable, missing: ${missing.join(', ')}`;
133
+ }
134
+
135
+ if (!profile || reason) {
136
+ const settings = { permissions: { deny } };
137
+ return {
138
+ level: 'tool-rules',
139
+ argv: ['--dangerously-skip-permissions', '--settings', JSON.stringify(settings)],
140
+ settings,
141
+ summary: { level: 'tool-rules', profile: agentType, network: null, reason },
142
+ };
143
+ }
144
+
145
+ const settings = {
146
+ permissions: {
147
+ allow: ['Read(//**)', 'Glob', 'Grep', 'Bash', 'Skill', 'Agent', 'ToolSearch', 'TodoWrite'],
148
+ deny: [...deny, 'WebFetch', 'WebSearch'],
149
+ },
150
+ sandbox: {
151
+ enabled: true,
152
+ failIfUnavailable: true,
153
+ allowUnsandboxedCommands: false,
154
+ autoAllowBashIfSandboxed: true,
155
+ filesystem: {
156
+ // .git: a job worktree commits into the main checkout's .git (objects,
157
+ // refs, worktrees/<name>); the CLI sandbox keeps .git/hooks and
158
+ // .git/config read-only itself.
159
+ allowWrite: [
160
+ worktreeDir,
161
+ path.join(projectRoot, '.git'),
162
+ tmpDir,
163
+ path.join(homeDir, '.npm'),
164
+ path.join(homeDir, '.cache'),
165
+ path.join(projectRoot, 'node_modules', '.vite'),
166
+ path.join(projectRoot, 'node_modules', '.vitest'),
167
+ ],
168
+ denyRead: secretAbs,
169
+ },
170
+ credentials: { files: secretAbs.map((p) => ({ path: p, mode: 'deny' })) },
171
+ network: { allowedDomains: [...profile.network], strictAllowlist: true },
172
+ },
173
+ };
174
+ return {
175
+ level: 'os-sandbox',
176
+ argv: ['--permission-mode', profile.permissionMode, '--settings', JSON.stringify(settings)],
177
+ settings,
178
+ summary: { level: 'os-sandbox', profile: agentType, network: [...profile.network], reason: null },
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Env vars a job's child process needs for its sandbox level. An os-sandbox
184
+ * job gets TMPDIR/TMP/TEMP pointed at its private temp dir (the only tmp
185
+ * write root its settings declare); tool-rules jobs get no env change.
186
+ *
187
+ * @param {{ level?: string }|null|undefined} policy
188
+ * @param {string} tmpDir
189
+ * @returns {Record<string, string>}
190
+ */
191
+ function sandboxChildEnv(policy, tmpDir) {
192
+ if (!policy || policy.level !== 'os-sandbox') return {};
193
+ return { TMPDIR: tmpDir, TMP: tmpDir, TEMP: tmpDir };
194
+ }
195
+
196
+ module.exports = {
197
+ SANDBOX_SECRET_PATHS,
198
+ SANDBOX_PROFILES,
199
+ sandboxDependencies,
200
+ buildJobSandboxSettings,
201
+ sandboxChildEnv,
202
+ };
@@ -12,9 +12,11 @@
12
12
  * working.
13
13
  *
14
14
  * Scoping is focus, not containment: the scope decides which tools a job is
15
- * offered. Every headless job runs as the owner's OS user with
16
- * --dangerously-skip-permissions, so a job with Bash can still start an MCP
17
- * server or call the admin API itself.
15
+ * offered. Every headless job runs as the owner's OS user. Sandboxed personas
16
+ * (validator, dev-lead when the OS sandbox is available) no longer run with
17
+ * --dangerously-skip-permissions; every other job still does, under secret-path
18
+ * deny rules — see jobSandboxPolicy.cjs. Either way a job with Bash can still
19
+ * start an MCP server or call the admin API itself.
18
20
  *
19
21
  * Pure: no fs, and no require of scheduler.cjs (cycle) — the caller passes its
20
22
  * HEADLESS_DISALLOWED_TOOLS list in.
@@ -29,10 +31,13 @@ const HEADLESS_SCOPE_AGENT_NAME = 'sm-headless-scoped';
29
31
 
30
32
  /**
31
33
  * @param {readonly string[]|null|undefined} tools persona `tools:` list
32
- * @param {{ disallowed?: readonly string[] }} [opts]
34
+ * @param {{ disallowed?: readonly string[], structuredOutput?: boolean }} [opts]
35
+ * structuredOutput: also grant the CLI's StructuredOutput tool (a --json-schema
36
+ * run). Probe 2026-11-22 (CLI 2.1.325): a scoped run without it ends
37
+ * 'success' with structured_output null — the schema is silently skipped.
33
38
  * @returns {{ tools: string[] }|null} null = persona declares no restriction
34
39
  */
35
- function buildPersonaToolScope(tools, { disallowed = [] } = {}) {
40
+ function buildPersonaToolScope(tools, { disallowed = [], structuredOutput = false } = {}) {
36
41
  if (!Array.isArray(tools) || tools.length === 0) return null;
37
42
  const names = tools
38
43
  .filter((t) => typeof t === 'string')
@@ -41,7 +46,8 @@ function buildPersonaToolScope(tools, { disallowed = [] } = {}) {
41
46
  if (names.length === 0 || names.includes('*')) return null;
42
47
  const blocked = new Set(disallowed);
43
48
  const out = [];
44
- for (const name of [...names, ...HEADLESS_TOOL_FLOOR]) {
49
+ const extra = structuredOutput === true ? ['StructuredOutput'] : [];
50
+ for (const name of [...names, ...HEADLESS_TOOL_FLOOR, ...extra]) {
45
51
  if (blocked.has(name) || out.includes(name)) continue;
46
52
  out.push(name);
47
53
  }
@@ -27,7 +27,18 @@ const { readTail } = require('../util/fileTail.cjs');
27
27
  * pause at 58% weekly). Tool output may also mention 429 or "rate limit". */
28
28
  function detectRateLimitInLog(logPath) {
29
29
  try {
30
- const text = readTail(logPath, 16384);
30
+ return detectRateLimitInText(readTail(logPath, 16384));
31
+ } catch {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ /** Same detection over already-captured text (e.g. a captured stdout tail).
37
+ * Only the last 16 KB is scanned, matching the log-tail variant. Never throws. */
38
+ function detectRateLimitInText(rawText) {
39
+ try {
40
+ const all = typeof rawText === 'string' ? rawText : '';
41
+ const text = all.length > 16384 ? all.slice(-16384) : all;
31
42
  if (!text) return false;
32
43
  for (const line of text.split('\n')) {
33
44
  const t = line.trim();
@@ -51,4 +62,4 @@ function detectRateLimitInLog(logPath) {
51
62
  }
52
63
  }
53
64
 
54
- module.exports = { detectRateLimitInLog };
65
+ module.exports = { detectRateLimitInLog, detectRateLimitInText };
@@ -16,8 +16,10 @@
16
16
  */
17
17
 
18
18
  const { spawn } = require('node:child_process');
19
+ const os = require('node:os');
19
20
  const { resolveClaudeBin, claudeSpawnTarget } = require('./claudeBin.cjs');
20
21
  const { headlessPermissionArgs, ensureCliCapsProbed } = require('./claudeCliCaps.cjs');
22
+ const { buildJobSandboxSettings } = require('./jobSandboxPolicy.cjs');
21
23
  const { feedChildStdin } = require('../process/childStdin.cjs');
22
24
  const { withProcRole } = require('../process/cleanEnv.cjs');
23
25
 
@@ -29,10 +31,13 @@ async function runClaudeP(prompt, { model = 'sonnet', timeoutMs = 180_000, syste
29
31
  return new Promise((resolve) => {
30
32
  let bin;
31
33
  try { bin = resolveClaudeBin(); } catch (e) { resolve({ ok: false, error: `claude not found: ${e?.message}` }); return; }
34
+ // No spawn cwd is set, so the child inherits process.cwd() — the sandbox roots there.
35
+ const sandboxDir = process.cwd();
36
+ const sandbox = buildJobSandboxSettings({ agentType: 'aux', worktreeDir: sandboxDir, projectRoot: sandboxDir, homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: { available: false, missing: [] } });
32
37
  const args = [
33
38
  '-p',
34
39
  '--model', model,
35
- '--dangerously-skip-permissions',
40
+ ...sandbox.argv,
36
41
  ...headlessPermissionArgs(),
37
42
  '--strict-mcp-config',
38
43
  '--output-format', 'text',