claude-code-session-manager 0.143.0 → 0.145.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 (128) hide show
  1. package/README.md +3 -1
  2. package/dist/assets/AppSettings-BR5b6oof.js +2 -0
  3. package/dist/assets/{History-DTttbvPb.js → History-B4U0mCdK.js} +2 -2
  4. package/dist/assets/HomeClaudeConfig-DQqG7lFE.js +5 -0
  5. package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CwsOJ0nI.js} +1 -1
  6. package/dist/assets/ProjectClaudeConfig-BzRowu8x.js +26 -0
  7. package/dist/assets/Scheduler-dr7CNOcL.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-CroBPY4C.js} +1 -1
  9. package/dist/assets/{Skills-cfV7sgk6.js → Skills-BiW2lCnD.js} +23 -23
  10. package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-CYTkQiva.js} +27 -27
  11. package/dist/assets/{Toggle-CYajnSdx.js → Toggle-WFBYo8JI.js} +1 -1
  12. package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-DZu8dTpO.js} +1 -1
  13. package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B7KeXLSE.js} +1 -1
  14. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  15. package/dist/assets/{index-CdTppjKR.js → index-hXRNm0UJ.js} +698 -697
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +442 -439
  19. package/package.json +4 -2
  20. package/plugins/session-manager-dev/skills/develop/SKILL.md +25 -19
  21. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  22. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +91 -0
  23. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +9 -6
  24. package/scripts/README.md +1 -1
  25. package/scripts/scheduler-mcp-server.cjs +77 -0
  26. package/src/main/adminRouteRegistry.cjs +6 -0
  27. package/src/main/agentLibrary.cjs +60 -11
  28. package/src/main/agentsIpc.cjs +19 -0
  29. package/src/main/build-info.json +4 -4
  30. package/src/main/chatRunner.cjs +139 -0
  31. package/src/main/config.cjs +12 -0
  32. package/src/main/health.cjs +59 -17
  33. package/src/main/index.cjs +6 -2
  34. package/src/main/ipcSchemas.cjs +55 -1
  35. package/src/main/lib/claude/agentArmory.cjs +128 -0
  36. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  37. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  38. package/src/main/lib/claude/builtinTools.cjs +110 -0
  39. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  40. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  41. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  42. package/src/main/lib/claude/personaToolScope.cjs +100 -14
  43. package/src/main/lib/demo-video-kit/resumableRun.cjs +21 -14
  44. package/src/main/lib/demo-video-kit/seedKit.cjs +2 -2
  45. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  46. package/src/main/lib/epic/epicOutsideRead.cjs +74 -2
  47. package/src/main/lib/epic/epicSettle.cjs +48 -4
  48. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  49. package/src/main/lib/epic/epicValidationHook.cjs +9 -1
  50. package/src/main/lib/epic/planReviewInput.cjs +125 -0
  51. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  52. package/src/main/lib/epic/scriptStartedBy.cjs +86 -0
  53. package/src/main/lib/externalContract.cjs +12 -0
  54. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  55. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +108 -14
  56. package/src/main/lib/feedback-remote/localAdminHttp.cjs +5 -1
  57. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
  58. package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
  59. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  60. package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
  61. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +35 -4
  62. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  63. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  64. package/src/main/lib/feedback-remote/servicePairings.cjs +95 -7
  65. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +104 -1
  66. package/src/main/lib/git/gitWorktree.cjs +1 -1
  67. package/src/main/lib/git/worktreeDeps.cjs +9 -3
  68. package/src/main/lib/mcpToolCatalog.cjs +47 -7
  69. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  70. package/src/main/lib/opsOwnership.cjs +2 -0
  71. package/src/main/lib/packs/packCatalog.cjs +98 -5
  72. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  73. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  74. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  75. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  76. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  77. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  78. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  79. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
  80. package/src/main/lib/prd/prdCreate.cjs +49 -5
  81. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  82. package/src/main/lib/prd/prdMcpReachWarnings.cjs +46 -0
  83. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  84. package/src/main/lib/process/peerChatSession.cjs +165 -0
  85. package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
  86. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
  87. package/src/main/lib/promptSessionSchema.cjs +2 -0
  88. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  89. package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
  90. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  91. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  92. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  93. package/src/main/lib/scheduler/planReviewStore.cjs +150 -0
  94. package/src/main/lib/scheduler/reviewNotice.cjs +3 -1
  95. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  96. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  97. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  98. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
  99. package/src/main/lib/tasks/memoryConsolidation.cjs +118 -37
  100. package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
  101. package/src/main/lib/tasks/taskRun.cjs +3 -1
  102. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +298 -0
  103. package/src/main/projectPages.cjs +22 -14
  104. package/src/main/pty.cjs +3 -0
  105. package/src/main/runVerify.cjs +80 -5
  106. package/src/main/scheduler/gitTreeGuard.cjs +6 -0
  107. package/src/main/scheduler/planReviewHold.cjs +146 -0
  108. package/src/main/scheduler/prdParser.cjs +1 -0
  109. package/src/main/scheduler/prdPaths.cjs +10 -1
  110. package/src/main/scheduler/reviewLadder.cjs +2 -0
  111. package/src/main/scheduler/utilizationHold.cjs +7 -2
  112. package/src/main/scheduler.cjs +692 -86
  113. package/src/main/seedAgentPersonas.cjs +11 -6
  114. package/src/main/seedStatus.cjs +1 -1
  115. package/src/main/templates/PRD_AUTHORING.md +17 -2
  116. package/src/main/webRemote.cjs +69 -7
  117. package/src/preload/api.d.ts +79 -1
  118. package/src/preload/apiSurface.json +39 -0
  119. package/src/preload/index.cjs +11 -0
  120. package/src/seed/agents/architect.md +28 -43
  121. package/src/seed/agents/dev-lead.md +3 -1
  122. package/src/seed/agents/md-network-curator.md +27 -0
  123. package/src/seed/agents/plan-reviewer.md +47 -0
  124. package/src/seed/agents/validator.md +2 -1
  125. package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
  126. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
  127. package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
  128. package/dist/assets/Scheduler-CNLjn90m.js +0 -16
@@ -35,6 +35,7 @@ const { isIncomplete, resolveChainTerminals, isValidPlanId, mintPlanId, resolveI
35
35
  const { splitFrontmatter, PRD_EFFORT_LEVELS, formatQuotedInlineList } = require('./prdFrontmatter.cjs');
36
36
  const { parseRule: parseToolRiskRule } = require('../claude/toolRiskMarks.cjs');
37
37
  const { normalizePreflight } = require('../scheduler/preflightCheck.cjs');
38
+ const { qualifiesForReview, planReviewEnabled } = require('../../scheduler/planReviewHold.cjs');
38
39
 
39
40
  // Cap on riskTools entries — mirrors ipcSchemas.cjs RiskToolsSchema.
40
41
  const RISK_TOOLS_MAX = 20;
@@ -77,6 +78,25 @@ function normalizeRiskTools(value) {
77
78
  return { ok: true, value: seen };
78
79
  }
79
80
  const { sizingWarnings } = require('./prdSizing.cjs');
81
+ const { sandboxWarnings } = require('./prdSandboxWarnings.cjs');
82
+ const { mcpReachWarnings } = require('./prdMcpReachWarnings.cjs');
83
+
84
+ /** Real deps for mcpReachWarnings: persona servers resolved the way the scheduler snapshot does. Never throws.
85
+ * readPersonaServers: null = persona missing/unreadable (no warning); [] = readable persona with no servers. */
86
+ const mcpReachDeps = {
87
+ resolve: (o) => require('../claude/headlessMcpServers.cjs').resolveHeadlessMcpServers(o),
88
+ readPersonaServers: (input) => {
89
+ try {
90
+ const { readOverlayAwarePersona, DEFAULT_PRD_AGENT_TYPE: dflt } = require('../claude/agentModelResolve.cjs');
91
+ const { parseTools, parseCapabilityList } = require('../../agentLibrary.cjs');
92
+ const { resolvedMcpServerNames } = require('../claude/personaToolScope.cjs');
93
+ const fm = (readOverlayAwarePersona(input.agentType || dflt, { cwd: input.cwd }) || {}).fm;
94
+ if (!fm) return null;
95
+ const tools = parseTools(typeof fm.tools === 'string' ? fm.tools : '');
96
+ return resolvedMcpServerNames(tools, parseCapabilityList(fm.mcpServers));
97
+ } catch { return null; }
98
+ },
99
+ };
80
100
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
81
101
  const { execGit } = require('../git/gitExec.cjs');
82
102
  const { extractRepoPathCandidates, worktreeReachWarnings } = require('./prdWorktreeReach.cjs');
@@ -137,7 +157,7 @@ function isValidMacroId(id) {
137
157
  function buildPrdBody(input) {
138
158
  const {
139
159
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
140
- implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, voiceId, riskTools, preflight,
160
+ implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, voiceId, riskTools, preflight, planReview,
141
161
  gate, files, budgetExempt, fixes,
142
162
  } = input;
143
163
  // Structured criteria (prdCriteria.cjs): createPrd() normalizes once and
@@ -206,6 +226,7 @@ function buildPrdBody(input) {
206
226
  // Precondition command — validated by createPrd() via normalizePreflightField.
207
227
  // JSON-string form, matching prdFrontmatter.cjs's serializer.
208
228
  if (typeof preflight === 'string' && preflight) fmLines.push(`preflight: ${JSON.stringify(preflight)}`);
229
+ if (planReview === 'required') fmLines.push('planReview: required');
209
230
  if (quietMachine === true) fmLines.push('quietMachine: true');
210
231
  // Budget exemption is for a sweep validator that cannot be split further;
211
232
  // every other caller's budgetExempt is ignored.
@@ -1093,7 +1114,7 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
1093
1114
  if (opts.dryRun) {
1094
1115
  return {
1095
1116
  ok: true, dryRun: true, slug, input, gateCommands, filesList,
1096
- inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
1117
+ inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input), ...sandboxWarnings(input), ...mcpReachWarnings(input, mcpReachDeps)],
1097
1118
  };
1098
1119
  }
1099
1120
 
@@ -1185,7 +1206,7 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
1185
1206
  // Advisory only (PRD 1403 sizing warnings + gate-and-files-in-PRD-body
1186
1207
  // absent/none-gate warnings) — never blocks the write. See prdSizing.cjs
1187
1208
  // and prdGateFiles.cjs.
1188
- warnings: [...extraWarnings, ...sizingWarnings(input)],
1209
+ warnings: [...extraWarnings, ...sizingWarnings(input), ...sandboxWarnings(input), ...mcpReachWarnings(input, mcpReachDeps)],
1189
1210
  };
1190
1211
  }
1191
1212
 
@@ -1276,6 +1297,26 @@ async function createPrdBatch(inputs, remote, opts = {}) {
1276
1297
  return fail([{ index: at, slug: cycle[0], error: `dependsOn cycle inside batch: ${cycle.join(' -> ')}` }]);
1277
1298
  }
1278
1299
 
1300
+ // Plan review: stamp planReview: required on each validator whose in-batch
1301
+ // dependsOn closure qualifies (planReviewHold.qualifiesForReview). Batch-only.
1302
+ const stampReview = new Set();
1303
+ if (planReviewEnabled()) {
1304
+ prepared.forEach((p, i) => {
1305
+ if (p.input.agentType !== 'validator') return;
1306
+ const seen = new Set();
1307
+ const stack = [...edges[i]];
1308
+ while (stack.length) {
1309
+ const n = stack.pop();
1310
+ if (seen.has(n)) continue;
1311
+ seen.add(n);
1312
+ stack.push(...edges[n]);
1313
+ }
1314
+ const members = [...seen].filter((n) => prepared[n].input.agentType !== 'validator')
1315
+ .map((n) => ({ slug: slugs[n], dependsOn: edges[n].map((m) => slugs[m]) }));
1316
+ if (qualifiesForReview(members)) stampReview.add(i);
1317
+ });
1318
+ }
1319
+
1279
1320
  // One planId for the whole batch unless an entry inherits one from existing deps.
1280
1321
  const planId = prepared.map((p) => p.inheritedPlanId).find(Boolean) || mintPlanId();
1281
1322
 
@@ -1364,14 +1405,16 @@ async function createPrdBatch(inputs, remote, opts = {}) {
1364
1405
  try {
1365
1406
  nn = nns[i];
1366
1407
  filenameSlug = `${nn}-${p.slug}`;
1367
- const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
1408
+ const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, planReview: stampReview.has(i) ? 'required' : undefined, gate: p.gateCommands, files: p.filesList });
1368
1409
  // A validated preflight must reach the file (PRD 3805 ran unheld when one
1369
1410
  // was lost); a body without the line rolls the whole batch back.
1370
1411
  if (p.input.preflight && !/^preflight: /m.test(body)) throw new Error('preflight was not written to the PRD frontmatter');
1371
1412
  const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
1372
1413
  if (!w?.ok) throw new Error(w?.error ?? 'write failed');
1373
1414
  written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
1374
- results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, preflight: p.input.preflight || null, warnings: [...p.warnings, ...overlapWarnings[i]] });
1415
+ results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, preflight: p.input.preflight || null,
1416
+ ...(stampReview.has(i) ? { planReview: 'required' } : {}),
1417
+ warnings: [...p.warnings, ...overlapWarnings[i], ...(stampReview.has(i) ? ['plan held for plan review before dispatch'] : [])] });
1375
1418
  } catch (e) {
1376
1419
  await rollback();
1377
1420
  return { failed: fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]) };
@@ -1491,6 +1534,7 @@ function registerAdminRoute(adminHttp, remote) {
1491
1534
  }
1492
1535
 
1493
1536
  module.exports = {
1537
+ mcpReachDeps,
1494
1538
  crossEpicFilesOverlapWarnings,
1495
1539
  PRD_CREATE_SLUG_RE,
1496
1540
  STANDARDS_PATH,
@@ -83,8 +83,8 @@ function splitFrontmatter(raw) {
83
83
  * JSON array of { id, statement, check: { kind, spec? } } — see parseCriteria.
84
84
  */
85
85
 
86
- const RECOGNIZED_KEYS = new Set(['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'fixes', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId', 'effort', 'voiceId', 'riskTools', 'preflight', 'criteria']);
87
- const EMIT_ORDER = ['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'fixes', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId', 'effort', 'voiceId', 'riskTools', 'preflight', 'criteria'];
86
+ const RECOGNIZED_KEYS = new Set(['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'fixes', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId', 'effort', 'voiceId', 'riskTools', 'preflight', 'criteria', 'planReview']);
87
+ const EMIT_ORDER = ['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'fixes', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId', 'effort', 'voiceId', 'riskTools', 'preflight', 'criteria', 'planReview'];
88
88
  // Mirrors modelCatalog.cjs CATALOG_FLOOR.effortLevels. A closed set so the
89
89
  // value is always safe as a frontmatter line and as a --effort argv token.
90
90
  const PRD_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
@@ -274,6 +274,9 @@ function applyKey(fm, key, after) {
274
274
  // round-trips the string.
275
275
  fm.agentType = String(v);
276
276
  return;
277
+ case 'planReview':
278
+ if (String(v) === 'required') fm.planReview = 'required';
279
+ return;
277
280
  case 'createdVia':
278
281
  fm.createdVia = String(v);
279
282
  return;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * prdMcpReachWarnings.cjs — advisory rule: a PRD whose persona (declared mcpServers + mcp__<server>__
3
+ * tools) or riskTools name an MCP server a headless job cannot load (undefined for the cwd, or
4
+ * credential-bearing) will park capability_unknown / capability_credentialed. Never blocks a write,
5
+ * never throws (an unreadable persona or resolver yields no warning). readPersonaServers returns null
6
+ * when the persona is missing/unreadable (no warning at all, riskTools included) and an array — [] when
7
+ * a readable persona declares no servers — otherwise.
8
+ */
9
+ 'use strict';
10
+
11
+ const RISK_MCP_RE = /^mcp__([^_](?:[^_]|_(?!_))*)__/;
12
+
13
+ /**
14
+ * @param {any} input createPrd()'s input shape.
15
+ * @param {{ resolve: (o: { cwd?: string }) => { known: Record<string, any>, credentialed: Record<string, string> },
16
+ * readPersonaServers: (input: any) => string[]|null }} deps
17
+ * @returns {string[]}
18
+ */
19
+ function mcpReachWarnings(input, deps) {
20
+ try {
21
+ const personaServers = deps.readPersonaServers(input);
22
+ if (!Array.isArray(personaServers)) return [];
23
+ const { known, credentialed } = deps.resolve({ cwd: input?.cwd });
24
+ const out = [];
25
+ for (const name of personaServers) {
26
+ if (Object.prototype.hasOwnProperty.call(credentialed || {}, name)) {
27
+ out.push(`persona MCP server \`${name}\` is credential-bearing (${credentialed[name]}) — the job will park capability_credentialed. Move the secret to a vault ref (environment profile) or drop the server from the persona.`);
28
+ } else if (!Object.prototype.hasOwnProperty.call(known || {}, name)) {
29
+ out.push(`persona MCP server \`${name}\` is not defined in ~/.claude.json, <cwd>/.mcp.json or the local project scope for this cwd — the job will park capability_unknown. Define the server there or remove it from the persona's tools/mcpServers.`);
30
+ }
31
+ }
32
+ const seen = new Set();
33
+ const risk = Array.isArray(input?.riskTools) ? input.riskTools : [];
34
+ for (const rule of risk) {
35
+ const m = typeof rule === 'string' ? RISK_MCP_RE.exec(rule) : null;
36
+ if (!m || seen.has(m[1]) || personaServers.includes(m[1])) continue;
37
+ seen.add(m[1]);
38
+ out.push(`riskTools clears \`${rule}\` but the persona never loads MCP server \`${m[1]}\` — the tool is cleared yet unreachable. Add it to the persona's tools or mcpServers.`);
39
+ }
40
+ return out;
41
+ } catch {
42
+ return [];
43
+ }
44
+ }
45
+
46
+ module.exports = { mcpReachWarnings };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * prdSandboxWarnings.cjs — pure advisory rule: a PRD that lists a path under `.claude/` in its
3
+ * files AND mentions `git mv` / `git rm` / `rm` in its goal, notes or criteria will park, because
4
+ * job Bash cannot write under `.claude/` in the sandbox (Self PRD 1326). Any path under
5
+ * `.claude/agents/` or `.claude/commands/` warns unconditionally (no verb needed): all writes there
6
+ * are refused, Edit/Write included. Never blocks a write.
7
+ */
8
+ 'use strict';
9
+
10
+ const VERB_RE = /\bgit\s+(mv|rm)\b|(^|[\s`'"(;&|])rm(?=$|[\s.,;:)`'"])/m;
11
+
12
+ /** @param {unknown} p */
13
+ function isClaudePath(p) {
14
+ return typeof p === 'string' && p.split('/').some((seg) => seg === '.claude');
15
+ }
16
+
17
+ /** `.claude` followed by agents, commands, skills, hooks or settings*.json: every write there is refused (Bash, Edit, Write). */
18
+ function isProtectedClaudePath(p) {
19
+ if (typeof p !== 'string') return false;
20
+ const segs = p.split('/');
21
+ return segs.some((seg, i) => seg === '.claude' && (['agents', 'commands', 'skills', 'hooks'].includes(segs[i + 1]) || /^settings[^/]*\.json$/.test(segs[i + 1] ?? '')));
22
+ }
23
+
24
+ /**
25
+ * Returns `[]` or a one-element array holding the warning (spread-compatible with sizingWarnings).
26
+ * @param {any} input createPrd()'s input shape.
27
+ * @returns {string[]}
28
+ */
29
+ function sandboxWarnings(input) {
30
+ const files = Array.isArray(input?.files) ? input.files : [];
31
+ const protectedPaths = files.filter(isProtectedClaudePath);
32
+ if (protectedPaths.length > 0) {
33
+ return [
34
+ `files lists ${protectedPaths.map((p) => `\`${p}\``).join(', ')} under .claude/agents, .claude/commands, .claude/skills, .claude/hooks or .claude/settings*.json — the job sandbox cannot write there (Bash, Edit and Write are all refused), so the job will fail. Remove the path from files; the architect must edit these inline. See PRD_AUTHORING.md#job-sandbox-limits.`,
35
+ ];
36
+ }
37
+ const bad = files.filter(isClaudePath);
38
+ if (bad.length === 0) return [];
39
+ const ac = Array.isArray(input?.acceptanceCriteria) ? input.acceptanceCriteria : [];
40
+ const text = [input?.goal, input?.implementationNotes, ...ac]
41
+ .filter((s) => typeof s === 'string')
42
+ .join('\n');
43
+ if (!VERB_RE.test(text)) return [];
44
+ return [
45
+ `files lists ${bad.map((p) => `\`${p}\``).join(', ')} under .claude/ and the PRD mentions git mv / git rm / rm — Bash writes there are refused by the job sandbox, so the job will park. Remove the verb or the path; the architect edits protected .claude/ paths inline. See PRD_AUTHORING.md#job-sandbox-limits.`,
46
+ ];
47
+ }
48
+
49
+ module.exports = { sandboxWarnings, isProtectedClaudePath };
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * peerChatSession.cjs — given the accepted socket of a loopback HTTP request,
5
+ * find the client process and read SM_CHAT_SESSION_ID / SM_PROJECT_ROOT from
6
+ * its environment (or its nearest ancestor's; up to 6 hops). Lets a press made
7
+ * from an SM chat (agent curl from its Bash tool) record the asking Epic.
8
+ *
9
+ * Read-only, same-uid processes only. Never logs or returns the environment —
10
+ * only the two variables. Never throws or rejects; null on any miss.
11
+ * SECURITY: the resolved chat/Epic is self-asserted by any same-uid process
12
+ * (it can set these variables to anything). It is provenance only and must
13
+ * never be used to authorize anything.
14
+ * Linux: /proc. darwin: lsof + ps (execFile, no shell). Others: null.
15
+ */
16
+
17
+ const nodeFs = require('fs');
18
+ const childProcess = require('child_process');
19
+
20
+ const ID_RE = /^[A-Za-z0-9-]{8,64}$/;
21
+ const MAX_HOPS = 6;
22
+ const DEADLINE_MS = 1500;
23
+
24
+ function pickVars(envMap) {
25
+ const id = envMap.SM_CHAT_SESSION_ID;
26
+ if (typeof id !== 'string' || !ID_RE.test(id)) return null;
27
+ const root = envMap.SM_PROJECT_ROOT;
28
+ return { chatSessionId: id, projectRoot: typeof root === 'string' && root ? root : null };
29
+ }
30
+
31
+ function parseEnviron(buf) {
32
+ const out = {};
33
+ for (const part of String(buf).split('\0')) {
34
+ const i = part.indexOf('=');
35
+ if (i <= 0) continue;
36
+ const k = part.slice(0, i);
37
+ if (k === 'SM_CHAT_SESSION_ID' || k === 'SM_PROJECT_ROOT') out[k] = part.slice(i + 1);
38
+ }
39
+ return out;
40
+ }
41
+
42
+ // ── Linux ──────────────────────────────────────────────────────────────────
43
+
44
+ function findInode(fs, clientLocalPort, serverPort) {
45
+ const lp = clientLocalPort.toString(16).toUpperCase().padStart(4, '0');
46
+ const rp = serverPort.toString(16).toUpperCase().padStart(4, '0');
47
+ for (const f of ['/proc/net/tcp', '/proc/net/tcp6']) {
48
+ let text;
49
+ try { text = fs.readFileSync(f, 'utf8'); } catch { continue; }
50
+ for (const line of String(text).split('\n').slice(1)) {
51
+ const c = line.trim().split(/\s+/);
52
+ if (c.length < 10) continue;
53
+ const l = (c[1] || '').split(':')[1];
54
+ const r = (c[2] || '').split(':')[1];
55
+ if (l && r && l.toUpperCase() === lp && r.toUpperCase() === rp && c[9] && c[9] !== '0') return c[9];
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+
61
+ function findPidByInode(fs, inode, uid, deadline, now) {
62
+ const want = `socket:[${inode}]`;
63
+ let pids;
64
+ try { pids = fs.readdirSync('/proc').filter((n) => /^\d+$/.test(n)); } catch { return null; }
65
+ for (const pid of pids) {
66
+ if (now() > deadline) return null;
67
+ try {
68
+ if (uid != null && fs.statSync(`/proc/${pid}`).uid !== uid) continue;
69
+ for (const fd of fs.readdirSync(`/proc/${pid}/fd`)) {
70
+ try {
71
+ if (fs.readlinkSync(`/proc/${pid}/fd/${fd}`) === want) return Number(pid);
72
+ } catch { /* fd vanished / EACCES */ }
73
+ }
74
+ } catch { /* EACCES / gone */ }
75
+ }
76
+ return null;
77
+ }
78
+
79
+ function linuxResolve(socket, deps, deadline, now) {
80
+ const fs = deps.fs || nodeFs;
81
+ const uid = deps.getuid ? deps.getuid() : (typeof process.getuid === 'function' ? process.getuid() : null);
82
+ const inode = findInode(fs, socket.remotePort, socket.localPort);
83
+ if (!inode) return null;
84
+ let pid = findPidByInode(fs, inode, uid, deadline, now);
85
+ for (let hop = 0; pid && hop <= MAX_HOPS && now() <= deadline; hop++) {
86
+ try {
87
+ const found = pickVars(parseEnviron(fs.readFileSync(`/proc/${pid}/environ`, 'latin1')));
88
+ if (found) return found;
89
+ } catch { /* unreadable */ }
90
+ let ppid = 0;
91
+ try {
92
+ const stat = String(fs.readFileSync(`/proc/${pid}/stat`, 'latin1'));
93
+ ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
94
+ } catch { return null; }
95
+ if (!Number.isInteger(ppid) || ppid <= 1) return null;
96
+ pid = ppid;
97
+ }
98
+ return null;
99
+ }
100
+
101
+ // ── darwin ─────────────────────────────────────────────────────────────────
102
+
103
+ function run(execFile, file, args, timeout) {
104
+ return new Promise((resolve) => {
105
+ try {
106
+ execFile(file, args, { timeout, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => resolve(err ? null : String(stdout)));
107
+ } catch { resolve(null); }
108
+ });
109
+ }
110
+
111
+ async function darwinResolve(socket, deps, deadline, now) {
112
+ const execFile = deps.execFile || childProcess.execFile;
113
+ const left = () => Math.max(100, Math.min(1000, deadline - now()));
114
+ const out = await run(execFile, 'lsof', ['-nP', `-iTCP:${socket.remotePort}`, '-sTCP:ESTABLISHED', '-Fp'], left());
115
+ if (!out) return null;
116
+ const self = process.pid;
117
+ const pids = out.split('\n').filter((l) => /^p\d+$/.test(l)).map((l) => Number(l.slice(1))).filter((p) => p !== self);
118
+ for (let pid of pids.slice(0, 4)) {
119
+ for (let hop = 0; hop <= MAX_HOPS && now() < deadline; hop++) {
120
+ const cmd = await run(execFile, 'ps', ['-E', '-ww', '-o', 'command=', '-p', String(pid)], left());
121
+ if (cmd) {
122
+ const env = {};
123
+ // ps -E prints argv then the environment: the LAST match is the env's.
124
+ const id = [...cmd.matchAll(/ SM_CHAT_SESSION_ID=(\S+)/g)].pop();
125
+ const root = [...cmd.matchAll(/ SM_PROJECT_ROOT=(\S+)/g)].pop();
126
+ if (id) env.SM_CHAT_SESSION_ID = id[1];
127
+ if (root) env.SM_PROJECT_ROOT = root[1];
128
+ const found = pickVars(env);
129
+ if (found) return found;
130
+ }
131
+ const pp = await run(execFile, 'ps', ['-o', 'ppid=', '-p', String(pid)], left());
132
+ const ppid = Number(String(pp || '').trim());
133
+ if (!Number.isInteger(ppid) || ppid <= 1) break;
134
+ pid = ppid;
135
+ }
136
+ }
137
+ return null;
138
+ }
139
+
140
+ /**
141
+ * @param {{ remotePort?: number, localPort?: number }} socket
142
+ * @param {{ fs?: any, execFile?: any, getuid?: () => number, platform?: string, now?: () => number }} [deps]
143
+ * @returns {Promise<{ chatSessionId: string, projectRoot: string|null } | null>}
144
+ */
145
+ async function resolvePeerChatSession(socket, deps = {}) {
146
+ try {
147
+ if (!socket || !Number.isInteger(socket.remotePort) || !Number.isInteger(socket.localPort)) return null;
148
+ const now = deps.now || Date.now;
149
+ const deadline = now() + DEADLINE_MS;
150
+ const platform = deps.platform || process.platform;
151
+ if (platform === 'linux') return linuxResolve(socket, deps, deadline, now) || null;
152
+ if (platform === 'darwin') {
153
+ let timer;
154
+ const cap = new Promise((r) => { timer = setTimeout(() => r(null), DEADLINE_MS); });
155
+ try {
156
+ return (await Promise.race([darwinResolve(socket, deps, deadline, now), cap])) || null;
157
+ } finally { clearTimeout(timer); }
158
+ }
159
+ return null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ module.exports = { resolvePeerChatSession };
@@ -179,6 +179,12 @@ function validRun(run) {
179
179
  if (externalRef !== undefined && externalRef !== null && !boundedString(externalRef, 500)) return null;
180
180
  const out = { entryId, epicId, slug, kind, at };
181
181
  if (typeof externalRef === 'string') out.externalRef = externalRef;
182
+ if (run.caller !== undefined) {
183
+ const { CallerSchema } = require('../epic/scriptStartedBy.cjs');
184
+ const c = CallerSchema.safeParse(run.caller);
185
+ if (c.success) out.caller = c.data;
186
+ }
187
+ if (boundedString(run.fromEpicId, 200)) out.fromEpicId = run.fromEpicId;
182
188
  return out;
183
189
  }
184
190
 
@@ -2,7 +2,8 @@
2
2
  * videoScriptRunRoute.cjs — a project's own script presses Demo Video.
3
3
  *
4
4
  * POST /admin/project-home/videos/run (body ≤ 64 KiB)
5
- * { cwd, kind, target?, length?, style?, character?, voiceId?, focus?, reviewFirst?, externalRef? }
5
+ * { cwd, kind, target?, length?, style?, character?, voiceId?, focus?, reviewFirst?, externalRef?,
6
+ * caller?: { pipeline?, runId?, step?, attempt? } }
6
7
  * curl -s -X POST "http://127.0.0.1:$(jq -r .port ~/.claude/session-manager/admin-api.json)/admin/project-home/videos/run" -H "Authorization: Bearer $(jq -r .token ~/.claude/session-manager/admin-api.json)" -H 'Content-Type: application/json' -d '{"cwd":"/abs/project","kind":"blog-post","target":"posts/hello.md","externalRef":"post:hello"}'
7
8
  *
8
9
  * Starts ONE builtin-demo-video job for the cwd through the same renderer
@@ -10,7 +11,10 @@
10
11
  * launchSession run 'job'), so persona, checks, review stage and the single
11
12
  * mint authority are the human press's own. Checks, in order, each refusal
12
13
  * launching nothing:
13
- * 1. 400 — body/cwd (resolveCwd from projectHomeAdminRoutes.cjs);
14
+ * 1. 400 — body/cwd (resolveCwd from projectHomeAdminRoutes.cjs), or a caller
15
+ * failing CallerSchema (epic/scriptStartedBy.cjs). caller names the script;
16
+ * every press sends startedBy (+ the resolved calling chat) so the minted
17
+ * Epic's source says a script started it; ledger + audit record the caller;
14
18
  * 2. 403 scripts_not_allowed — the project's 'Scripts may run Demo Video'
15
19
  * switch is off (videoScriptPress.isVideoScriptSwitchOn);
16
20
  * 3. 400 — the press choices (videoPressLines.parseScriptPress), a voiceId
@@ -43,6 +47,7 @@
43
47
  const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
44
48
  const { normalizeExternalRef } = require('../epic/externalRef.cjs');
45
49
  const { parseScriptPress, pressLines } = require('./videoPressLines.cjs');
50
+ const { CallerSchema } = require('../epic/scriptStartedBy.cjs');
46
51
 
47
52
  const fs = require('node:fs');
48
53
  const path = require('node:path');
@@ -53,7 +58,7 @@ const MAX_RUN_BODY_BYTES = 64 * 1024;
53
58
  const MACRO_ID = 'builtin-demo-video';
54
59
  const ACTIVE = new Set(['pending', 'held', 'running']);
55
60
  const PRESS_KEYS = ['kind', 'target', 'length', 'style', 'character', 'voiceId', 'focus', 'reviewFirst'];
56
- const ALLOWED_KEYS = new Set(['cwd', 'externalRef', ...PRESS_KEYS]);
61
+ const ALLOWED_KEYS = new Set(['cwd', 'externalRef', 'caller', ...PRESS_KEYS]);
57
62
  const SWITCH_REASON = "the 'Scripts may run Demo Video' switch is off for this project; a human turns it on in Project Home > Video";
58
63
 
59
64
  /** cwd -> launch promise; one scripted launch per project at a time. */
@@ -76,7 +81,7 @@ function launchError(result) {
76
81
  * listJobRows?: () => Promise<any[]>, resolveCwd?: (c: unknown) => any, videoScriptPress?: any,
77
82
  * listVoices?: (cwd: string) => { voices: Array<{ id: string }> }, builtinMacros?: any[],
78
83
  * appendAuditEvent?: Function, withExternalRefLock?: Function, now?: () => number,
79
- * readHistoryTail?: (cwd: string) => Promise<string> }} [deps]
84
+ * readHistoryTail?: (cwd: string) => Promise<string>, startedByFromRequest?: Function }} [deps]
80
85
  */
81
86
  function registerAdminRoute(adminHttp, deps = {}) {
82
87
  const resolveCwd = deps.resolveCwd
@@ -112,6 +117,13 @@ function registerAdminRoute(adminHttp, deps = {}) {
112
117
  const unknown = Object.keys(body).find((k) => !ALLOWED_KEYS.has(k));
113
118
  if (unknown) return bad(`unknown field: ${unknown}`);
114
119
 
120
+ let caller;
121
+ if (body.caller !== undefined) {
122
+ const c = CallerSchema.safeParse(body.caller);
123
+ if (!c.success) return bad(`invalid caller: ${c.error.issues.map((i) => `${i.path.join('.') || 'caller'} ${i.message}`).join('; ')}`);
124
+ caller = c.data;
125
+ }
126
+
115
127
  const resolved = resolveCwd(body.cwd);
116
128
  if (!resolved || !resolved.ok) {
117
129
  sendJson(res, resolved?.status || 400, { ok: false, error: oneLine(resolved?.error || 'cwd rejected') });
@@ -180,6 +192,9 @@ function registerAdminRoute(adminHttp, deps = {}) {
180
192
  return;
181
193
  }
182
194
 
195
+ const startedByFn = deps.startedByFromRequest
196
+ || ((/** @type {any} */ a, /** @type {any} */ d) => require('../epic/scriptStartedBy.cjs').startedByFromRequest(a, d));
197
+ const startedBy = await startedByFn({ route: ROUTE_PATH, caller, socket: req.socket }, deps);
183
198
  const payload = {
184
199
  cwd,
185
200
  agentName: macro.agentName,
@@ -188,6 +203,7 @@ function registerAdminRoute(adminHttp, deps = {}) {
188
203
  prompt: `${macro.prompt}\n\nAdditional instructions: ${pressLines(cfg).join('\n')}`,
189
204
  macroId: MACRO_ID,
190
205
  via: 'script',
206
+ startedBy,
191
207
  ...(cfg.review ? { reviewStage: true } : {}),
192
208
  ...(externalRef !== undefined ? { externalRef } : {}),
193
209
  };
@@ -220,6 +236,8 @@ function registerAdminRoute(adminHttp, deps = {}) {
220
236
  kind: cfg.kind,
221
237
  at: new Date(now()).toISOString(),
222
238
  ...(externalRef !== undefined ? { externalRef } : {}),
239
+ ...(caller ? { caller } : {}),
240
+ ...(startedBy.fromEpicId ? { fromEpicId: startedBy.fromEpicId } : {}),
223
241
  });
224
242
  } catch (e) {
225
243
  recorded = false;
@@ -230,6 +248,8 @@ function registerAdminRoute(adminHttp, deps = {}) {
230
248
  route: ROUTE_PATH, cwd, macroId: MACRO_ID, kind: cfg.kind,
231
249
  entryId: result.entryId, epicId: result.epicId, slug, stage,
232
250
  ...(externalRef !== undefined ? { externalRef } : {}),
251
+ ...(caller ? { caller } : {}),
252
+ ...(startedBy.fromEpicId ? { fromEpicId: startedBy.fromEpicId } : {}),
233
253
  });
234
254
  } catch { /* audit is best-effort */ }
235
255
  sendJson(res, 200, {
@@ -52,6 +52,8 @@ const EpicSourceSchema = z.object({
52
52
  // Zod strips undeclared keys on the merge path; a stricter shape could make dropInvalidSessions (ipcSchemas.cjs) drop a whole row holding an older or malformed value.
53
53
  proposal: z.unknown().optional(),
54
54
  autoApprove: z.unknown().optional(),
55
+ // Script-started Epics: { kind: 'script', route, ... }; absent = a person pressed it. Lenient on load; epic/scriptStartedBy.cjs is the entry-point validator.
56
+ startedBy: z.unknown().optional(),
55
57
  // Cross-project thread: replyTo = the asking Epic a reply goes back to
56
58
  // ({ cwd, epicId, claudeSessionId }); replyOf = the Epic a reply answers.
57
59
  replyTo: z.unknown().optional(),
@@ -84,7 +84,32 @@ function failingStep(outcome) {
84
84
  }
85
85
 
86
86
  /**
87
- * decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, env })
87
+ * The file part of a failing-test id: before ' > ' (vitest), '::' (pytest) or
88
+ * ':TS' (tsc); the whole id otherwise.
89
+ * @param {string} id
90
+ * @returns {string}
91
+ */
92
+ function idFilePart(id) {
93
+ for (const sep of [' > ', '::', ':TS']) {
94
+ const i = id.indexOf(sep);
95
+ if (i > 0) return id.slice(0, i).trim();
96
+ }
97
+ return id;
98
+ }
99
+
100
+ /**
101
+ * True when `text` names at least one failing id, or that id's file part.
102
+ * @param {unknown} text
103
+ * @param {string[]} ids
104
+ * @returns {boolean}
105
+ */
106
+ function reasonNamesFailure(text, ids) {
107
+ if (typeof text !== 'string' || text.length === 0) return false;
108
+ return ids.some((id) => text.includes(id) || text.includes(idFilePart(id)));
109
+ }
110
+
111
+ /**
112
+ * decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason, env })
88
113
  * → { complete, reason, preexisting }
89
114
  *
90
115
  * Checks run in a fixed order; the first failed check is the reason.
@@ -97,10 +122,13 @@ function failingStep(outcome) {
97
122
  * @param {boolean} params.ancestorOk - landedCommit is an ancestor of (or equal to) the pre-gate HEAD.
98
123
  * @param {boolean} params.cleanOk - tree clean before and after the gate.
99
124
  * @param {boolean} params.headStable - HEAD unmoved across the gate.
125
+ * @param {string} [params.failReason] - the run's recorded FAIL reason (verdicts sidecar `reason`).
126
+ * Checked LAST: it must name a HEAD failing id or its file part, else 'fail-not-about-gate' —
127
+ * a FAIL on an outside blocker over an already-red suite is not a success.
100
128
  * @param {object} [params.env] - defaults to process.env.
101
129
  * @returns {{complete: boolean, reason: string, preexisting: string[]}}
102
130
  */
103
- function decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, env = process.env } = {}) {
131
+ function decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason, env = process.env } = {}) {
104
132
  const no = (reason) => ({ complete: false, reason, preexisting: [] });
105
133
  if (env?.SM_BASELINE_GATE_AUTHORITY_DISABLE === '1') return no('kill-switch');
106
134
  if (!job || job.status !== 'needs_review' || job.verifierVerdict !== 'sentinel_fail') {
@@ -122,6 +150,7 @@ function decideBaselineAuthority({ job, headOutcome, baseOutcome, evidenceOk, an
122
150
  if (!headIds || !baseIds) return no('unparseable-output');
123
151
  const baseSet = new Set(baseIds);
124
152
  if (headIds.some((id) => !baseSet.has(id))) return no('new-failures');
153
+ if (!reasonNamesFailure(failReason, headIds)) return no('fail-not-about-gate');
125
154
  return { complete: true, reason: 'baseline-identical', preexisting: headIds };
126
155
  }
127
156