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
@@ -25,12 +25,16 @@ const { readArchived, defaultProjectRoots, makeRegisteredRootsCache } = require(
25
25
  const { gatherEpicJobReceipt } = require('./epicJobReceipt.cjs');
26
26
  const { summarizeTranscriptFile } = require('./transcriptUsage.cjs');
27
27
  const { resolveEpicTranscriptPath } = require('./epicTranscriptPath.cjs');
28
+ const { StartedBySchema } = require('./scriptStartedBy.cjs');
28
29
  const { isSafeEpicId } = require('../prd/prdLocations.cjs');
29
30
  const fs = require('node:fs');
30
31
  const { opsPath } = require('../opsOwnership.cjs');
31
32
  const { readJsonOrSync } = require('../util/atomicFs.cjs');
32
33
  const { parseValidatorVerdict } = require('../scheduler/validatorVerdictSchema.cjs');
33
34
  const { bareSlug } = require('../prd/depSlugResolve.cjs');
35
+ const { readPlanReviewFiles } = require('../scheduler/planReviewStore.cjs');
36
+ const { splitFrontmatter, parseFixes } = require('../prd/prdFrontmatter.cjs');
37
+ const { planReviewStats } = require('../scheduler/planReviewStats.cjs');
34
38
 
35
39
  const DEFAULT_LIMIT = 50;
36
40
  const MAX_LIMIT = 200;
@@ -207,10 +211,75 @@ function readVerdictFiles(cwd, epicId) {
207
211
  }
208
212
  }
209
213
 
214
+ /** Re-sanitize a stored startedBy; anything invalid or absent reads as null (a person pressed it). */
215
+ function startedByOf(raw) {
216
+ if (raw == null) return null;
217
+ const r = StartedBySchema.safeParse(raw);
218
+ return r.success ? r.data : null;
219
+ }
220
+
221
+ let MAX_FIX_FILES = 2000;
222
+ let MAX_FIX_CACHE = 5000;
223
+ /** Test seam: override the per-call file cap and the total cache bound. */
224
+ function _setFixesCapsForTests(files, cache) {
225
+ MAX_FIX_FILES = files == null ? 2000 : files;
226
+ MAX_FIX_CACHE = cache == null ? 5000 : cache;
227
+ }
228
+ /** Leading PRD number of a file name; -1 when it has none. */
229
+ function prdNN(name) {
230
+ const m = /^(\d+)/.exec(name);
231
+ return m ? Number(m[1]) : -1;
232
+ }
233
+ /** abs path -> { mtimeMs, size, fixes } — a repeat read re-parses only files whose stat changed. */
234
+ const fixesCache = new Map();
235
+
236
+ /** fixes[] ({ prd, missKind }) from this Epic's PRD files (prds/ and prds-archived/); [] on any failure. At most MAX_FIX_FILES files per call (the newest by name are kept). */
237
+ function readEpicFixes(cwd, epicId) {
238
+ const out = [];
239
+ try {
240
+ if (!isSafeEpicId(epicId)) return out;
241
+ const base = path.join(opsPath(cwd, 'scheduler', 'epics'), epicId);
242
+ let files = [];
243
+ for (const sub of ['prds', 'prds-archived']) {
244
+ let names;
245
+ try { names = fs.readdirSync(path.join(base, sub)); } catch { continue; }
246
+ for (const n of names) if (n.endsWith('.md')) files.push({ n, p: path.join(base, sub, n) });
247
+ }
248
+ files.sort((x, y) => prdNN(x.n) - prdNN(y.n) || (x.n < y.n ? -1 : x.n > y.n ? 1 : x.p < y.p ? -1 : x.p > y.p ? 1 : 0));
249
+ files = files.map((f) => f.p);
250
+ if (files.length > MAX_FIX_FILES) files = files.slice(-MAX_FIX_FILES);
251
+ const seen = new Set(files);
252
+ for (const file of files) {
253
+ try {
254
+ const st = fs.statSync(file);
255
+ let hit = fixesCache.get(file);
256
+ if (!hit || hit.mtimeMs !== st.mtimeMs || hit.size !== st.size) {
257
+ const { fm } = splitFrontmatter(fs.readFileSync(file, 'utf8'));
258
+ const list = typeof fm.fixes === 'string' ? parseFixes(fm.fixes) : null;
259
+ hit = { mtimeMs: st.mtimeMs, size: st.size, fixes: (list || []).map((f) => ({ prd: f.prd, missKind: f.missKind })) };
260
+ fixesCache.set(file, hit);
261
+ } else {
262
+ // LRU: a hit moves the entry to the back so eviction drops the least recently used.
263
+ fixesCache.delete(file);
264
+ fixesCache.set(file, hit);
265
+ }
266
+ while (fixesCache.size > MAX_FIX_CACHE) fixesCache.delete(fixesCache.keys().next().value);
267
+ for (const f of hit.fixes) out.push({ prd: f.prd, missKind: f.missKind });
268
+ } catch { fixesCache.delete(file); /* skip unreadable or deleted PRD */ }
269
+ }
270
+ // Drop deleted/out-of-scope files of this Epic from the cache.
271
+ const prefix = base + path.sep;
272
+ for (const k of fixesCache.keys()) if (k.startsWith(prefix) && !seen.has(k)) fixesCache.delete(k);
273
+ } catch { /* none */ }
274
+ return out;
275
+ }
276
+
210
277
  function buildRecord(cwd, epicId, session, events, jobs, needsInput, chatBusy) {
211
278
  const computed = computeEpicOutsideState({ session: { ...session, id: epicId }, events, jobs, needsInput, chatBusy });
212
279
  const source = isObj(session.source) ? session.source : {};
213
280
  const { title, goal } = splitGoal(session.goalText);
281
+ const verdicts = readVerdictFiles(cwd, epicId);
282
+ const planReviews = readPlanReviewFiles(cwd, epicId);
214
283
  return {
215
284
  epicId,
216
285
  cwd: str(session.cwd) || cwd,
@@ -232,10 +301,13 @@ function buildRecord(cwd, epicId, session, events, jobs, needsInput, chatBusy) {
232
301
  fromCwd: str(source.fromCwd),
233
302
  fromEpicId: str(source.fromEpicId),
234
303
  macroId: str(source.macroId),
304
+ startedBy: startedByOf(source.startedBy),
235
305
  },
236
306
  createdAt: str(session.createdAt),
237
307
  completedAt: str(session.completedAt),
238
- verdicts: readVerdictFiles(cwd, epicId),
308
+ verdicts,
309
+ planReviews,
310
+ planReviewStats: planReviewStats({ planReviews, verdictFiles: verdicts, fixes: readEpicFixes(cwd, epicId) }),
239
311
  };
240
312
  }
241
313
 
@@ -421,4 +493,4 @@ async function listOpenEpicRecords(cwd, opts = {}) {
421
493
  }
422
494
  }
423
495
 
424
- module.exports = { readVerdictFiles, listOpenEpicRecords, getEpicRecord, findEpicProject };
496
+ module.exports = { readEpicFixes, _setFixesCapsForTests, _fixesCacheSizeForTests: () => fixesCache.size, get MAX_FIX_FILES() { return MAX_FIX_FILES; }, get MAX_FIX_CACHE() { return MAX_FIX_CACHE; }, readVerdictFiles, listOpenEpicRecords, getEpicRecord, findEpicProject };
@@ -4,7 +4,8 @@
4
4
  * epicSettle.cjs — pure settle evaluator for one Epic.
5
5
  *
6
6
  * Given the Epic's event chain and the scheduler queue rows, says whether the
7
- * Epic has settled (no pending/running PRD) and which finished PRDs no
7
+ * Epic has settled (no running PRD, and no pending PRD other than ones held
8
+ * on a preflight precondition or waiting only on such held rows) and which finished PRDs no
8
9
  * validator has checked yet. No fs; only the pure lib/scheduler/cancelledRow
9
10
  * predicate, never the scheduler itself.
10
11
  */
@@ -35,7 +36,50 @@ function evaluateEpicSettle({ epicId, cwd, events, jobs, now, horizonMs } = {})
35
36
  const epicRows = rows.filter(
36
37
  (r) => r && (r.epicId === epicId || r.sourcePromptId === epicId) && (r.cwd == null || cwd == null || r.cwd === cwd),
37
38
  );
38
- const settled = !epicRows.some((r) => r.status === 'pending' || r.status === 'running');
39
+ // A pending row is held when its preflight parked it, or when every one of its
40
+ // unfinished dependencies is itself held. Held rows run on their own later, so
41
+ // they do not hold back the settle digest; the digest names them instead.
42
+ const byBare = new Map();
43
+ for (const r of epicRows) if (r && r.slug != null) byBare.set(bareSlug(String(r.slug)), r);
44
+ const isFinished = (r) => r.status === 'completed' || r.status === 'skipped';
45
+ const heldMemo = new Map(); // row -> reason string | null
46
+ /** @returns {string|null} the held reason, or null when the row is not held */
47
+ const heldReasonOf = (row, seen) => {
48
+ if (!row || row.status !== 'pending') return null;
49
+ if (heldMemo.has(row)) return heldMemo.get(row);
50
+ if (row.preflightHold || (typeof row.heldReason === 'string' && row.heldReason.startsWith('held: plan-review'))) {
51
+ const reason = typeof row.heldReason === 'string' && row.heldReason ? row.heldReason : 'waiting on precondition';
52
+ heldMemo.set(row, reason);
53
+ return reason;
54
+ }
55
+ if (seen.has(row)) return null;
56
+ seen.add(row);
57
+ const deps = Array.isArray(row.dependsOn) ? row.dependsOn : [];
58
+ let firstHeld = null;
59
+ let result = null;
60
+ let anyUnfinished = false;
61
+ let allHeld = true;
62
+ for (const d of deps) {
63
+ const dep = byBare.get(bareSlug(String(d)));
64
+ if (!dep || isFinished(dep)) continue;
65
+ anyUnfinished = true;
66
+ if (heldReasonOf(dep, seen) == null) { allHeld = false; break; }
67
+ if (firstHeld == null) firstHeld = String(dep.slug);
68
+ }
69
+ if (anyUnfinished && allHeld) result = `waiting on ${firstHeld}`;
70
+ seen.delete(row);
71
+ heldMemo.set(row, result);
72
+ return result;
73
+ };
74
+ const held = epicRows
75
+ .filter((r) => r.status === 'pending')
76
+ .map((r) => ({ slug: String(r.slug), reason: heldReasonOf(r, new Set()) }))
77
+ .filter((h) => h.reason != null)
78
+ .sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
79
+ const heldSet = new Set(held.map((h) => h.slug));
80
+ const settled = !epicRows.some(
81
+ (r) => r.status === 'running' || (r.status === 'pending' && !heldSet.has(String(r.slug))),
82
+ );
39
83
  const cancelled = epicRows
40
84
  .filter(isCancelledRow)
41
85
  .map((r) => String(r.slug))
@@ -101,12 +145,12 @@ function evaluateEpicSettle({ epicId, cwd, events, jobs, now, horizonMs } = {})
101
145
  failed.sort();
102
146
 
103
147
  const digestKey = createHash('sha1')
104
- .update(JSON.stringify({ verified, refuted, failed, parked, cancelled, uncovered: uncovered.map((u) => u.slug) }))
148
+ .update(JSON.stringify({ verified, refuted, failed, parked, cancelled, uncovered: uncovered.map((u) => u.slug), held: held.map((h) => h.slug) }))
105
149
  .digest('hex')
106
150
  .slice(0, 16);
107
151
  const hasContent = [uncovered, verified, refuted, failed, parked, cancelled].some((l) => l.length > 0);
108
152
 
109
- return { settled, uncovered, verified, refuted, failed, parked, cancelled, digestKey, hasContent };
153
+ return { settled, held, uncovered, verified, refuted, failed, parked, cancelled, digestKey, hasContent };
110
154
  }
111
155
 
112
156
  module.exports = { evaluateEpicSettle, DEFAULT_SETTLE_HORIZON_MS };
@@ -47,7 +47,7 @@ const { isNonClaudeAgentCli } = require('../agent-cli/agentCliEvents.cjs');
47
47
 
48
48
  /**
49
49
  * The persona (body + model) this turn runs with — see the header's "Persona pin".
50
- * @returns {{ source: 'snapshot'|'live', agentSnapshotId: string|null, body: string|null, model: string, snapshotMissing?: true } | null}
50
+ * @returns {{ source: 'snapshot'|'live', agentSnapshotId: string|null, body: string|null, model: string, snapshot?: any, snapshotMissing?: true } | null}
51
51
  */
52
52
  function resolveTurnPersona(cwd, claudeSessionId, epic, deps) {
53
53
  if (epic && isNonClaudeAgentCli(epic.agentCli)) return null;
@@ -70,6 +70,8 @@ function resolveTurnPersona(cwd, claudeSessionId, epic, deps) {
70
70
  agentSnapshotId: id,
71
71
  body: typeof snap.body === 'string' && snap.body ? snap.body : null,
72
72
  model: model || modelResolve.FALLBACK_MODEL,
73
+ // The pinned snapshot itself: chatRunner reads gearBindsChat/loadout/tools/mcpServers/packs from it.
74
+ snapshot: snap,
73
75
  };
74
76
  }
75
77
 
@@ -143,8 +143,16 @@ function buildSettledDigest(settle, { epicId, notValidatedReason, cwd, findings
143
143
  const parked = s.parked || [];
144
144
  const cancelled = s.cancelled || [];
145
145
  const notValidated = (s.uncovered || []).map((u) => (typeof u === 'string' ? u : u.slug));
146
+ const held = Array.isArray(s.held) ? s.held : [];
147
+ const head = held.length
148
+ ? [
149
+ `PLAN SETTLED — nothing of this session is running; ${held.length} PRD(s) are held on a precondition and will run on their own:`,
150
+ ...held.map((h) => `- ${h.slug}${h.reason ? ` — ${h.reason}` : ''}`),
151
+ 'This is ONE digest, not a per-PRD request.',
152
+ ]
153
+ : [`PLAN SETTLED — no PRD of this session is pending or running. This is ONE digest, not a per-PRD request.`];
146
154
  const lines = [
147
- `PLAN SETTLED — no PRD of this session is pending or running. This is ONE digest, not a per-PRD request.`,
155
+ ...head,
148
156
  ...recordFolderLines(cwd, epicId),
149
157
  'Do NOT re-verify VERIFIED PRDs — a validator already checked them.',
150
158
  ];
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * planReviewInput.cjs — pure builder for the scheduler_create_prd input of one
5
+ * plan-review job (agentType plan-reviewer), plus a deterministic structural
6
+ * pre-check whose findings go into the job's notes. Pure: no fs, no child_process.
7
+ */
8
+
9
+ const { bareSlug } = require('../prd/depSlugResolve.cjs');
10
+
11
+ const PERSONA_LINE = 'Work as the plan-reviewer persona — the procedure is your system prompt.';
12
+
13
+ /** @param {any} m */
14
+ function isDocMember(m) {
15
+ const goal = typeof m.goal === 'string' ? m.goal.trim().toLowerCase() : '';
16
+ if (goal.startsWith('doc')) return true;
17
+ const files = Array.isArray(m.files) ? m.files : [];
18
+ return files.length > 0 && files.every((f) => typeof f === 'string' && /\.md$/i.test(f));
19
+ }
20
+
21
+ /**
22
+ * @param {Array<any>} members
23
+ * @returns {Array<{ check: string, slug: string, detail: string }>}
24
+ */
25
+ function structuralFindings(members) {
26
+ const list = Array.isArray(members) ? members : [];
27
+ const bySlug = new Map(list.map((m) => [bareSlug(m.slug), m]));
28
+ const findings = [];
29
+
30
+ /** @param {any} start */
31
+ const reachesNonDoc = (start) => {
32
+ const seen = new Set();
33
+ const stack = [...(start.dependsOn || [])];
34
+ while (stack.length) {
35
+ const b = bareSlug(stack.pop());
36
+ if (seen.has(b)) continue;
37
+ seen.add(b);
38
+ const m = bySlug.get(b);
39
+ if (!m) continue;
40
+ if (!isDocMember(m)) return true;
41
+ stack.push(...(m.dependsOn || []));
42
+ }
43
+ return false;
44
+ };
45
+
46
+ for (const m of list) {
47
+ if (isDocMember(m) && !reachesNonDoc(m)) {
48
+ findings.push({
49
+ check: 'doc-after-code',
50
+ slug: m.slug,
51
+ detail: `doc PRD ${m.slug} does not depend (transitively) on any code PRD in the plan`,
52
+ });
53
+ }
54
+ for (const d of m.dependsOn || []) {
55
+ if (!bySlug.has(bareSlug(d))) {
56
+ findings.push({
57
+ check: 'depends-on',
58
+ slug: m.slug,
59
+ detail: `${m.slug} dependsOn ${d}, which is not in the plan`,
60
+ });
61
+ }
62
+ }
63
+ }
64
+ return findings;
65
+ }
66
+
67
+ /**
68
+ * @param {{ epicId: string, cwd: string, epicGoal?: string, validateSlug: string,
69
+ * members: Array<any>, baseSha?: string | null, round?: number }} args
70
+ */
71
+ function buildPlanReviewInput({ epicId, cwd, epicGoal, validateSlug, members, baseSha, round }) {
72
+ const list = Array.isArray(members) ? members : [];
73
+ const bare = bareSlug(validateSlug);
74
+ const slug = `plan-review-${bare}${round && round >= 2 ? `-r${round}` : ''}`;
75
+ const recordPath = `session-manager-operations/plan-records/${epicId}/${validateSlug}.plan-review.md`;
76
+
77
+ const acceptanceCriteria = list.map((m) => `Review ${m.slug}`);
78
+ acceptanceCriteria.push(`Record written at ${recordPath}, relative to the job worktree's repository root (git rev-parse --show-toplevel), never relative to a subdirectory you cd'd into. Do not git add or commit it — the scheduler copies it to the main checkout`);
79
+
80
+ const lines = [
81
+ PERSONA_LINE,
82
+ `Epic goal: ${epicGoal || 'unknown'}`,
83
+ baseSha ? `Base: ${baseSha}` : 'Base: unknown',
84
+ '',
85
+ 'Plan members:',
86
+ ];
87
+ for (const m of list) {
88
+ lines.push(
89
+ `- ${m.slug}${m.title ? ` — ${m.title}` : ''}`,
90
+ ` PRD file: ${m.prdPath}`,
91
+ ` Goal: ${m.goal || ''}`,
92
+ ' Acceptance criteria:',
93
+ ...(m.acceptanceCriteria || []).map((c) => ` - ${c}`),
94
+ ` Files: ${(m.files || []).join(', ') || '(none)'}`,
95
+ ` Gate: ${(m.gate || []).join(' ; ') || '(none)'}`,
96
+ ` dependsOn: ${(m.dependsOn || []).join(', ') || '(none)'}`,
97
+ );
98
+ }
99
+ const findings = structuralFindings(list);
100
+ lines.push('', 'Structural pre-check:');
101
+ if (findings.length === 0) lines.push('- no findings');
102
+ for (const f of findings) lines.push(`- [${f.check}] ${f.detail}`);
103
+ lines.push('', 'Created automatically by the scheduler; no human or planner wrote this PRD.');
104
+
105
+ return {
106
+ title: `Plan review: ${bare}${round && round >= 2 ? ` (round ${round})` : ''}`,
107
+ slug,
108
+ goal: `review. Independent review of this Epic's plan before its PRDs dispatch: ${list.map((m) => m.slug).join(', ')}.`,
109
+ acceptanceCriteria,
110
+ implementationNotes: lines.join('\n'),
111
+ outOfScope: ['Editing product code', 'Queuing fix PRDs'],
112
+ gate: ['none'],
113
+ files: [recordPath],
114
+ deliverable: 'artifact',
115
+ artifactPaths: [recordPath],
116
+ agentType: 'plan-reviewer',
117
+ tag: 'build',
118
+ sourcePromptId: epicId,
119
+ // The plan's own PRDs are incomplete; without a disposition prdCreate refuses.
120
+ disposition: 'new-head',
121
+ cwd,
122
+ };
123
+ }
124
+
125
+ module.exports = { buildPlanReviewInput, structuralFindings };
@@ -975,5 +975,6 @@ module.exports = {
975
975
  listRestorableSessions,
976
976
  listRecentRestorableSessions,
977
977
  checkRestorableSessionSync,
978
+ showId,
978
979
  __resetCacheForTests,
979
980
  };
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * scriptStartedBy.cjs — how a script-started Epic records who started it.
5
+ * EpicSource.startedBy = { kind: 'script', route, caller?, fromCwd?, fromEpicId? }
6
+ * | { kind: 'service', serviceId, name } (a paired service under an owner grant);
7
+ * absent for every human press. 'new-epic-ui' stays the mint authority
8
+ * (epicMint.cjs); startedBy sits next to it. The stored shape is lenient
9
+ * (promptSessionSchema.cjs); this is the strict entry-point validator.
10
+ */
11
+
12
+ const { z } = require('zod');
13
+
14
+ const CallerSchema = z.object({
15
+ pipeline: z.string().max(200).optional(),
16
+ runId: z.string().max(200).optional(),
17
+ step: z.string().max(200).optional(),
18
+ attempt: z.number().int().min(0).optional(),
19
+ }).strict();
20
+
21
+ const ScriptStartedBySchema = z.object({
22
+ kind: z.literal('script'),
23
+ route: z.string().min(1).max(200),
24
+ caller: CallerSchema.optional(),
25
+ fromCwd: z.string().max(4096).optional(),
26
+ fromEpicId: z.string().max(200).optional(),
27
+ }).strict();
28
+
29
+ /** A paired service started it under an owner startWork grant. */
30
+ const ServiceStartedBySchema = z.object({
31
+ kind: z.literal('service'),
32
+ serviceId: z.string().min(1).max(200),
33
+ name: z.string().min(1).max(200),
34
+ }).strict();
35
+
36
+ const StartedBySchema = z.discriminatedUnion('kind', [ScriptStartedBySchema, ServiceStartedBySchema]);
37
+
38
+ /** @param {{ serviceId: string, name: string }} args */
39
+ function buildServiceStartedBy({ serviceId, name }) {
40
+ return ServiceStartedBySchema.parse({ kind: 'service', serviceId, name });
41
+ }
42
+
43
+ /**
44
+ * Build a StartedBySchema-valid object, omitting absent/empty keys.
45
+ * @param {{ route: string, caller?: object, fromCwd?: string, fromEpicId?: string }} args
46
+ */
47
+ function buildStartedBy({ route, caller, fromCwd, fromEpicId } = {}) {
48
+ const out = { kind: 'script', route };
49
+ if (caller && typeof caller === 'object') {
50
+ const c = {};
51
+ for (const [k, v] of Object.entries(caller)) {
52
+ if (v !== undefined && v !== null && v !== '') c[k] = v;
53
+ }
54
+ if (Object.keys(c).length) out.caller = c;
55
+ }
56
+ if (typeof fromCwd === 'string' && fromCwd) out.fromCwd = fromCwd;
57
+ if (typeof fromEpicId === 'string' && fromEpicId) out.fromEpicId = fromEpicId;
58
+ return ScriptStartedBySchema.parse(out);
59
+ }
60
+
61
+ /**
62
+ * startedBy for a request: validated body caller + the chat that made the
63
+ * loopback call (resolved from the socket), mapped to its Epic when found.
64
+ * @param {{ route: string, caller?: object, socket?: object }} args
65
+ * @param {{ resolvePeerChatSession?: Function, findEpicByClaudeSessionId?: Function }} [deps]
66
+ */
67
+ async function startedByFromRequest({ route, caller, socket } = {}, deps = {}) {
68
+ let fromCwd;
69
+ let fromEpicId;
70
+ try {
71
+ const resolve = deps.resolvePeerChatSession || require('../process/peerChatSession.cjs').resolvePeerChatSession;
72
+ const peer = await resolve(socket);
73
+ if (peer && peer.chatSessionId && peer.projectRoot) {
74
+ const find = deps.findEpicByClaudeSessionId || require('../claude/agentModelResolve.cjs').findEpicByClaudeSessionId;
75
+ const epic = find(peer.projectRoot, peer.chatSessionId);
76
+ if (epic) {
77
+ fromCwd = peer.projectRoot;
78
+ fromEpicId = epic.id || epic.epicId || undefined;
79
+ if (!fromEpicId) fromCwd = undefined;
80
+ }
81
+ }
82
+ } catch { /* resolution is best-effort */ }
83
+ return buildStartedBy({ route, caller, fromCwd, fromEpicId });
84
+ }
85
+
86
+ module.exports = { CallerSchema, StartedBySchema, ScriptStartedBySchema, ServiceStartedBySchema, buildStartedBy, buildServiceStartedBy, startedByFromRequest };
@@ -60,6 +60,9 @@ const CONTRACT = deepFreeze({
60
60
  { method: 'GET', path: '/__admin/health' },
61
61
  { method: 'POST', path: '/admin/feedback/open-session' },
62
62
  { method: 'POST', path: '/admin/macros/run' },
63
+ { method: 'POST', path: '/admin/projects/create' },
64
+ { method: 'POST', path: '/admin/services/pair-local' },
65
+ { method: 'POST', path: '/admin/services/pair-local/confirm' },
63
66
  { method: 'GET', path: '/admin/epics' },
64
67
  { method: 'GET', path: '/admin/epic' },
65
68
  // GET /admin/events: no epicId → audit-log rows { events, next, more, gap } (eventKinds below);
@@ -91,6 +94,7 @@ const CONTRACT = deepFreeze({
91
94
  epicRecordFields: [
92
95
  'epicId', 'cwd', 'title', 'goal', 'tag', 'agentType', 'status', 'state', 'phase', 'blocked', 'prds',
93
96
  'verified', 'refuted', 'unvalidated', 'externalRef', 'source', 'createdAt', 'completedAt', 'verdicts',
97
+ 'planReviews', 'planReviewStats',
94
98
  ],
95
99
  receiptFields: ['jobs', 'chat'],
96
100
  epicStateChangedFields: ['at', 'kind', 'cwd', 'epicId', 'from', 'to', 'blockedKind', 'externalRef'],
@@ -165,6 +169,10 @@ const CONTRACT_FINGERPRINTS = Object.freeze({
165
169
  // back to the v1 shape 0.141.0 served; 0.142.0 served lifecycle words only, after C6 909f6e47 narrowed it).
166
170
  // then GET /admin/usage-hold (scheduler/usageHoldRoute.cjs): the 'pause above' hold POST /admin/tasks refuses on.
167
171
  // then usage_hold_get: the MCP tool over GET /admin/usage-hold (scheduler-mcp-server.cjs).
172
+ // then POST /admin/projects/create (feedback-remote/projectCreate.cjs); no tool entry, mirroring macro_run.
173
+ // then POST /admin/services/pair-local + /confirm (feedback-remote/servicePairLocalRoutes.cjs).
174
+ // then 'planReviews' on epicRecordFields (stored plan-review records + release from plan-records/*.plan-review.json).
175
+ // then 'planReviewStats' on epicRecordFields (planReviewStats.cjs: reviewed vs unreviewed plan comparison).
168
176
  1: Object.freeze([
169
177
  '5a56abbb70184ff4a34346a5c6da4c5e6edbd756b54573c199b812d3f5a04101',
170
178
  '7383ff32c80561b1b2c505a78a1e8313ae2851bdc6e8fce6c6a88e1ab119bf5a',
@@ -175,6 +183,10 @@ const CONTRACT_FINGERPRINTS = Object.freeze({
175
183
  '4f4ee647977bb670c71db57c6fdfa8dc5db89ce789a1f05dbf23f9468dcff30b',
176
184
  '2c87717d95b8b7dceb8a2138affcd3fc990f762072691de7a433b2874fe89d4d',
177
185
  '9490d3b89b9468f20666553747b3d4be3558e78ffcb5b79d63397cfa4ddd5235',
186
+ '799f062f9dd858b81afa20cf2153357e8fc7a3be2c748573d0f4c12b430d6683',
187
+ 'feaad10fabd300203314318c5484a8aed9b1cef496d2fbfb48464b06ff64628a',
188
+ 'e0ee3a1a0970e44c52b336d935ac59d05c4bfba3b4f3c602222292fbb5c77174',
189
+ '6fa520f745b48c393733123633029537aa54109040081bed320fa976888f1e77',
178
190
  ]),
179
191
  });
180
192