claude-code-session-manager 0.142.0 → 0.144.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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -62,10 +62,10 @@ const KINDS = new Set([KIND_STARTED, KIND_STATUS_CHANGED]);
62
62
  /** Pre-event-log kinds still on disk (≤ tasksDays old) → their current kind. */
63
63
  const LEGACY_KINDS = { start: KIND_STARTED, end: KIND_STATUS_CHANGED, imported: KIND_STATUS_CHANGED };
64
64
 
65
- /** Terminal Task statuses (taskRun.cjs + taskAdminRoutes.cjs + read-side 'interrupted'). */
65
+ /** Terminal Task statuses (taskRun.cjs + taskAdminRoutes.cjs incl. the slot-grant 'usage_held' + read-side 'interrupted'). */
66
66
  const TERMINAL_STATUSES = Object.freeze([
67
67
  'ok', 'error', 'rate_limited', 'timeout', 'spawn_failed', 'caller_gone', 'slot_timeout',
68
- 'too_many_waiting', 'interrupted',
68
+ 'too_many_waiting', 'interrupted', 'usage_held',
69
69
  ]);
70
70
 
71
71
  /**
@@ -74,7 +74,7 @@ function nonEmptyString(v) {
74
74
  * declaredMcpServers?: readonly string[], knownMcpServers?: Record<string, object> }} o
75
75
  * @returns {string[]}
76
76
  */
77
- function buildTaskArgs({ model, effort, runtime, projectCwd, declaredMcpServers = [], knownMcpServers = {} } = /** @type {any} */ ({})) {
77
+ function buildTaskArgs({ model, effort, runtime, projectCwd, declaredMcpServers = [], knownMcpServers = {}, skillDeny = [] } = /** @type {any} */ ({})) {
78
78
  if (!nonEmptyString(model)) throw new Error('buildTaskArgs: model is required');
79
79
  if (!nonEmptyString(effort)) throw new Error('buildTaskArgs: effort is required');
80
80
  const rt = runtime && typeof runtime === 'object' ? runtime : {};
@@ -119,6 +119,8 @@ function buildTaskArgs({ model, effort, runtime, projectCwd, declaredMcpServers
119
119
  if (Array.isArray(rt.disallowedTools) && rt.disallowedTools.length) {
120
120
  for (const rule of rt.disallowedTools) args.push('--disallowedTools=' + String(rule));
121
121
  }
122
+ // Skills ride only inside the persona's packs (already '--disallowedTools=Skill(<name>)').
123
+ if (Array.isArray(skillDeny)) args.push(...skillDeny.filter((a) => typeof a === 'string' && a.startsWith('--disallowedTools=Skill(')));
122
124
 
123
125
  if (rt.outputFormat === 'stream-json') args.push('--output-format', 'stream-json', '--verbose');
124
126
  else args.push('--output-format', 'json');
@@ -0,0 +1,178 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * weeklyConsolidationInputs.cjs — what the weekly memory + docs consolidation
5
+ * pass may read: this project's own session transcripts and the Lessons blocks
6
+ * headless PRD jobs handed over, both inside a half-open window [since, until).
7
+ *
8
+ * Pure + dependency-injected (deps.*); the defaults lazy-require the real
9
+ * readers. Read-only: never writes a transcript or a job record.
10
+ */
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+ const os = require('node:os');
15
+ const { encodeCwd } = require('../util/encodeCwd.cjs');
16
+
17
+ const MAX_TRANSCRIPTS = 200;
18
+ const MAX_LESSON_LINES = 3;
19
+ const MAX_LESSON_CHARS = 200;
20
+ const HEAD_BYTES = 64 * 1024;
21
+
22
+ function toMs(v) {
23
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
24
+ if (typeof v === 'string' && v) { const t = Date.parse(v); return Number.isFinite(t) ? t : null; }
25
+ return null;
26
+ }
27
+
28
+ /** Half-open window test: since <= t < until. */
29
+ function inWindow(t, sinceMs, untilMs) {
30
+ return typeof t === 'number' && Number.isFinite(t) && t >= sinceMs && t < untilMs;
31
+ }
32
+
33
+ function defaultDeps() {
34
+ return {
35
+ projectsDir: path.join(os.homedir(), '.claude', 'projects'),
36
+ readdir: (d) => { try { return fs.readdirSync(d); } catch { return []; } },
37
+ stat: (p) => { try { return fs.statSync(p); } catch { return null; } },
38
+ // First lines only — never the whole file.
39
+ readFirstCwd: (file) => {
40
+ let fd;
41
+ try {
42
+ fd = fs.openSync(file, 'r');
43
+ const buf = Buffer.alloc(HEAD_BYTES);
44
+ const n = fs.readSync(fd, buf, 0, HEAD_BYTES, 0);
45
+ for (const line of buf.toString('utf8', 0, n).split('\n').slice(0, 20)) {
46
+ if (!line.includes('"cwd"')) continue;
47
+ try { const o = JSON.parse(line); if (o && typeof o.cwd === 'string') return o.cwd; } catch { /* torn line */ }
48
+ }
49
+ } catch { /* unreadable */ } finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* ignore */ } }
50
+ return null;
51
+ },
52
+ mainRootOf: (cwd) => require('../cwdClassify.cjs').worktreeMainRootOf(cwd),
53
+ readJobs: () => require('../scheduler/queueStore.cjs').readMergedSync().jobs,
54
+ readResultText: (logPath) => require('../../scheduler.cjs').extractResultTextFromLog(logPath),
55
+ readStructured: (logPath) => require('../../scheduler.cjs').extractStructuredOutputFromLog(logPath),
56
+ };
57
+ }
58
+
59
+ function withDefaults(deps) {
60
+ return { ...defaultDeps(), ...(deps || {}) };
61
+ }
62
+
63
+ /** True when `sessionCwd` is the project root or one of its worktrees. */
64
+ function belongsToProject(sessionCwd, root, d) {
65
+ if (typeof sessionCwd !== 'string' || !sessionCwd) return false;
66
+ const norm = (p) => path.resolve(p);
67
+ if (norm(sessionCwd) === norm(root)) return true;
68
+ let main = null;
69
+ try { main = d.mainRootOf(sessionCwd); } catch { main = null; }
70
+ return !!main && norm(main) === norm(root);
71
+ }
72
+
73
+ /**
74
+ * listProjectTranscripts({ cwd, sinceMs, untilMs, deps }) →
75
+ * { transcripts: [{ path, sessionId, mtimeMs, cwd }], truncated, total, range: { since, until } }
76
+ */
77
+ function listProjectTranscripts({ cwd, sinceMs, untilMs, deps } = {}) {
78
+ const d = withDefaults(deps);
79
+ const range = { since: sinceMs, until: untilMs };
80
+ const found = [];
81
+ if (!cwd || typeof cwd !== 'string') return { transcripts: [], truncated: 0, total: 0, range };
82
+ const enc = encodeCwd(cwd);
83
+ for (const folder of d.readdir(d.projectsDir) || []) {
84
+ // Cheap name filter first: the project's own folder (or a sibling sharing its
85
+ // prefix, rejected below by the real cwd) and managed worktree folders.
86
+ if (!folder.startsWith(enc) && !folder.includes('worktrees')) continue;
87
+ const dir = path.join(d.projectsDir, folder);
88
+ const inWin = [];
89
+ for (const name of d.readdir(dir) || []) {
90
+ if (!name.endsWith('.jsonl')) continue; // also skips subagents/ directories
91
+ const file = path.join(dir, name);
92
+ const st = d.stat(file);
93
+ if (!st || !inWindow(st.mtimeMs, sinceMs, untilMs)) continue;
94
+ inWin.push({ file, name, mtimeMs: st.mtimeMs });
95
+ }
96
+ if (!inWin.length) continue;
97
+ // A folder is one cwd; read it once, from the newest in-window file.
98
+ inWin.sort((a, b) => b.mtimeMs - a.mtimeMs);
99
+ let sessionCwd = null;
100
+ for (const f of inWin) { sessionCwd = d.readFirstCwd(f.file); if (sessionCwd) break; }
101
+ if (!belongsToProject(sessionCwd, cwd, d)) continue;
102
+ for (const f of inWin) found.push({ path: f.file, sessionId: f.name.slice(0, -'.jsonl'.length), mtimeMs: f.mtimeMs, cwd: sessionCwd });
103
+ }
104
+ found.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.path < b.path ? -1 : 1));
105
+ const transcripts = found.slice(0, MAX_TRANSCRIPTS);
106
+ return { transcripts, truncated: found.length - transcripts.length, total: found.length, range };
107
+ }
108
+
109
+ function clip(s) {
110
+ const t = String(s).replace(/\s+/g, ' ').trim();
111
+ return t.length > MAX_LESSON_CHARS ? t.slice(0, MAX_LESSON_CHARS) : t;
112
+ }
113
+
114
+ /** Trailing 'Lessons' block of a result text → up to 3 lines, or []. Lenient. */
115
+ function parseLessonsBlock(text) {
116
+ if (typeof text !== 'string' || !text) return [];
117
+ const lines = text.split('\n');
118
+ let at = -1;
119
+ for (let i = lines.length - 1; i >= 0; i--) {
120
+ if (/^\s*(?:#{1,6}\s*)?(?:\*\*|__)?\s*lessons\s*:?\s*(?:\*\*|__)?\s*:?\s*$/i.test(lines[i])) { at = i; break; }
121
+ }
122
+ if (at < 0) return [];
123
+ const out = [];
124
+ for (let i = at + 1; i < lines.length && out.length < MAX_LESSON_LINES; i++) {
125
+ const m = /^\s*[-*]\s+(.*\S)\s*$/.exec(lines[i]);
126
+ if (!m) { if (!lines[i].trim()) continue; break; }
127
+ out.push(clip(m[1]));
128
+ }
129
+ return out;
130
+ }
131
+
132
+ function lessonsFromField(v) {
133
+ if (typeof v === 'string') return v.split('\n').map((l) => clip(l.replace(/^\s*[-*]\s+/, ''))).filter(Boolean).slice(0, MAX_LESSON_LINES);
134
+ if (Array.isArray(v)) return v.filter((x) => typeof x === 'string').map(clip).filter(Boolean).slice(0, MAX_LESSON_LINES);
135
+ return [];
136
+ }
137
+
138
+ /**
139
+ * collectLessons({ cwd, sinceMs, untilMs, deps }) →
140
+ * { lessons: [{ slug, jobId, source, lines }], range: { since, until } }
141
+ */
142
+ function collectLessons({ cwd, sinceMs, untilMs, deps } = {}) {
143
+ const d = withDefaults(deps);
144
+ const range = { since: sinceMs, until: untilMs };
145
+ const lessons = [];
146
+ if (!cwd || typeof cwd !== 'string') return { lessons, range };
147
+ let jobs = [];
148
+ try { jobs = d.readJobs(cwd) || []; } catch { jobs = []; }
149
+ for (const job of jobs) {
150
+ if (!job || typeof job !== 'object' || !job.finishedAt) continue;
151
+ if (!belongsToProject(job.cwd, cwd, d)) continue;
152
+ if (!inWindow(toMs(job.finishedAt), sinceMs, untilMs)) continue;
153
+ const jobId = job.id ?? job.runId ?? null;
154
+ const slug = job.slug ?? null;
155
+ if (job.agentType === 'validator') {
156
+ let so = null;
157
+ try { so = d.readStructured(job.logPath); } catch { so = null; }
158
+ if (!so || typeof so !== 'object') continue;
159
+ const top = lessonsFromField(so.lessons);
160
+ if (top.length) lessons.push({ slug, jobId, source: 'validator', lines: top });
161
+ for (const v of Array.isArray(so.verdicts) ? so.verdicts : []) {
162
+ const lines = lessonsFromField(v && v.lessons);
163
+ if (lines.length) lessons.push({ slug: (v && v.prd) || slug, jobId, source: 'validator', lines });
164
+ }
165
+ } else {
166
+ let text = null;
167
+ try { text = d.readResultText(job.logPath); } catch { text = null; }
168
+ const lines = parseLessonsBlock(text);
169
+ if (lines.length) lessons.push({ slug, jobId, source: 'dev-lead', lines });
170
+ }
171
+ }
172
+ return { lessons, range };
173
+ }
174
+
175
+ module.exports = {
176
+ listProjectTranscripts, collectLessons, parseLessonsBlock, inWindow,
177
+ MAX_TRANSCRIPTS, MAX_LESSON_LINES, MAX_LESSON_CHARS,
178
+ };
@@ -22,12 +22,13 @@
22
22
  * stamps `now` at append time). Rows that fail to parse or lack a string `at` are skipped.
23
23
  *
24
24
  * epic_state_changed is read from the per-Epic event logs, not from audit rows:
25
- * every `epic.status_changed` event (written by epicTransitions.transitionEpic at
26
- * the transition, lib/epic/epicEventLog.cjs) of every registered project becomes
27
- * one row { at, kind: 'epic_state_changed', cwd, epicId, from, to, externalRef? }
28
- * (epicStateRowOf), merged into the audit rows by `at` (ties: audit rows first,
29
- * then cwd, epicId, seq) so one cursor covers both. Status values map to the
30
- * outside-state words of lib/epic/epicOutsideState.cjs (STATUS_TO_OUTSIDE).
25
+ * every `epic.state_changed` event (written by lib/epic/epicStateEmitter.cjs with
26
+ * the fine-grained outside state, lib/epic/epicEventLog.cjs) of every registered
27
+ * project becomes one row
28
+ * { at, kind: 'epic_state_changed', cwd, epicId, from, to, blockedKind?, externalRef? }
29
+ * (epicStateRowOf; blockedKind only on a `to: 'blocked'` row), merged into the
30
+ * audit rows by `at` (ties: audit rows first, then cwd, epicId, seq) so one cursor
31
+ * covers both. Lifecycle-only `epic.status_changed` events yield no row.
31
32
  * Legacy epic_state_changed audit rows already in the log stay readable.
32
33
  * Projects come from the `projectRoots` option, else — only when `target` is not
33
34
  * given — promptSessionsIpc's registered projects (cached EPIC_ROOTS_TTL_MS).
@@ -136,9 +137,7 @@ const cursorOf = (at, n) => `${at}~${n}`;
136
137
  // ── epic_state_changed from the per-Epic event logs ──
137
138
 
138
139
  const EPIC_STATE_KIND = 'epic_state_changed';
139
- const EPIC_STATUS_EVENT = 'epic.status_changed';
140
- /** Lifecycle status → the outside-state word epicOutsideState.cjs gives an Epic in that status. */
141
- const STATUS_TO_OUTSIDE = Object.freeze({ proposed: 'awaiting_approval', active: 'open', completed: 'closed' });
140
+ const EPIC_STATE_EVENT = 'epic.state_changed';
142
141
  const EPIC_ROOTS_TTL_MS = 10000;
143
142
  const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
144
143
 
@@ -146,26 +145,24 @@ const EPIC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
146
145
  const nonEmpty = (v) => (typeof v === 'string' && v !== '' ? v : null);
147
146
  /** @param {unknown} v @returns {v is Record<string, any>} */
148
147
  const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
149
- /** @param {unknown} status */
150
- const outsideOf = (status) => {
151
- const s = nonEmpty(status);
152
- if (s === null) return null;
153
- return Object.prototype.hasOwnProperty.call(STATUS_TO_OUTSIDE, s) ? STATUS_TO_OUTSIDE[/** @type {'proposed'} */ (s)] : s;
154
- };
155
148
 
156
149
  /**
157
- * One epic.status_changed event → its outside epic_state_changed row, or null.
150
+ * One epic.state_changed event → its outside epic_state_changed row, or null
151
+ * (any other kind, epic.status_changed included).
158
152
  * @param {string} cwd project root the event log belongs to
159
153
  * @param {Record<string, any>} ev a parsed event-log record
160
- * @param {string|null} [externalRef]
154
+ * @param {string|null} [externalRef] fallback ref (active index) when the event carries none
161
155
  */
162
156
  function epicStateRowOf(cwd, ev, externalRef = null) {
163
- if (!isObj(ev) || ev.kind !== EPIC_STATUS_EVENT) return null;
157
+ if (!isObj(ev) || ev.kind !== EPIC_STATE_EVENT) return null;
164
158
  const at = nonEmpty(ev.time);
165
159
  const epicId = nonEmpty(ev.epicId);
166
- if (!at || !epicId) return null;
160
+ const to = nonEmpty(ev.to);
161
+ if (!at || !epicId || !to) return null;
167
162
  /** @type {Record<string, any>} */
168
- const row = { at, kind: EPIC_STATE_KIND, cwd, epicId, from: outsideOf(ev.from), to: outsideOf(ev.to) };
163
+ const row = { at, kind: EPIC_STATE_KIND, cwd, epicId, from: ev.from ?? null, to };
164
+ const blockedKind = to === 'blocked' ? nonEmpty(ev.blockedKind) : null;
165
+ if (blockedKind) row.blockedKind = blockedKind;
169
166
  const ref = nonEmpty(ev.externalRef) || nonEmpty(externalRef);
170
167
  if (ref) row.externalRef = ref;
171
168
  return row;
@@ -179,7 +176,7 @@ const indexCache = new Map();
179
176
  const knownRefs = new Map();
180
177
  let rootsCache = { at: 0, roots: /** @type {string[]} */ ([]) };
181
178
 
182
- /** Status-change events of one event-log file, re-reading only bytes appended since the last call. */
179
+ /** epic.state_changed events of one event-log file, re-reading only bytes appended since the last call. */
183
180
  function statusEventsOf(file) {
184
181
  let size;
185
182
  try { size = fs.statSync(file).size; } catch { logCache.delete(file); return []; }
@@ -199,10 +196,10 @@ function statusEventsOf(file) {
199
196
  if (end >= 0) {
200
197
  const events = c.events.slice();
201
198
  for (const line of text.slice(0, end).split('\n')) {
202
- if (!line.includes(EPIC_STATUS_EVENT)) continue;
199
+ if (!line.includes(EPIC_STATE_EVENT)) continue;
203
200
  try {
204
201
  const r = JSON.parse(line);
205
- if (isObj(r) && r.kind === EPIC_STATUS_EVENT) events.push(r);
202
+ if (isObj(r) && r.kind === EPIC_STATE_EVENT) events.push(r);
206
203
  } catch { /* torn line */ }
207
204
  }
208
205
  c = { size, offset: c.offset + Buffer.byteLength(text.slice(0, end + 1), 'utf8'), events };
@@ -373,5 +370,5 @@ function readEventsAfter({ after, kinds, limit, target, initialWindow, maxArchiv
373
370
 
374
371
  module.exports = {
375
372
  OUTSIDE_EVENT_KINDS, readEventsAfter, CURSOR_FORM, INVALID_AUDIT_CURSOR, MAX_ARCHIVE_GZ_BYTES,
376
- STATUS_TO_OUTSIDE, epicStateRowOf, _resetEpicStateCacheForTests,
373
+ epicStateRowOf, _resetEpicStateCacheForTests,
377
374
  };
@@ -128,16 +128,20 @@ function rotateIfNeeded(target, now, maxBytes) {
128
128
  /**
129
129
  * appendAuditEvent(kind, fields, opts?) — append one JSONL record. `kind` is a short
130
130
  * label ('epic_mint' | 'prd_create' | ...); `fields` is event-specific detail
131
- * (cwd, epicId, status, title, slug, etc). `opts.now` (Date) / `opts.target` are
131
+ * (cwd, epicId, status, title, slug, etc); a `fields.kind` never overrides `kind`
132
+ * and is stored as `fieldKind`. `opts.now` (Date) / `opts.target` are
132
133
  * test seams. Never throws; a rotation failure never drops the append.
133
134
  */
134
135
  function appendAuditEvent(kind, fields = {}, opts = {}) {
135
136
  try {
136
137
  const now = opts.now ?? new Date();
138
+ // The first-argument kind always wins; a caller field named `kind` is kept as `fieldKind`.
139
+ const { kind: fieldKind, ...rest } = fields ?? {};
137
140
  const record = {
138
141
  at: now.toISOString(),
139
142
  kind,
140
- ...fields,
143
+ ...rest,
144
+ ...(fieldKind !== undefined ? { fieldKind } : {}),
141
145
  caller: callerContext(),
142
146
  };
143
147
  const target = opts.target ?? auditLogPath();
@@ -95,9 +95,9 @@ async function readJsonOr(file, fallback) {
95
95
  }
96
96
  }
97
97
 
98
- function readJsonOrSync(file, fallback) {
98
+ function readJsonOrSync(file, fallback, fsImpl = fs) {
99
99
  try {
100
- const raw = fs.readFileSync(file, 'utf8');
100
+ const raw = fsImpl.readFileSync(file, 'utf8');
101
101
  if (raw.trim() === '') return fallback;
102
102
  return JSON.parse(raw);
103
103
  } catch {
@@ -1,16 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * projectPages.cjs — read-only backend for Project Home. Project Home has two
5
- * self-contained generated artifacts under
6
- * `session-manager-operations/project-pages/`: `home.html` (written by the
7
- * `project_home_write` admin route) and `demo-video/index.html` (written by
8
- * the `project_demo_video_write` admin route) — both in
9
- * lib/feedback-remote/projectHomeAdminRoutes.cjs. This module only reads them: get() returns
10
- * home.html's content plus the demo video's { path, mtimeMs }, and a
11
- * refcounted per-cwd watcher pushes `project-pages:changed` for either. It
12
- * never writes content (watch()'s mkdir creates an empty directory only).
13
- * mdNetwork() maps the project's markdown link network on demand
4
+ * projectPages.cjs — main-process backend for Project Home. Its content is a
5
+ * library under `session-manager-operations/project-pages/`: one folder per
6
+ * entry in `knowledge/<id>/` and `videos/<id>/` (index.html + meta.json),
7
+ * listed by lib/project-pages/pagesLibrary.cjs listLibrary(). get() first runs
8
+ * migrateLegacy(), which moves the two legacy files (`home.html`,
9
+ * `demo-video/index.html`) into the library once, then returns { knowledge,
10
+ * videos, html, mtimeMs, demoVideo } (+ persona/outcomes when present); html
11
+ * is the `overview` page and demoVideo the newest video, kept for the phone
12
+ * remote. watchOutput()/unwatchOutput() run a refcounted per-cwd watcher that
13
+ * pushes get()'s result as `project-pages:changed` on library (and legacy or
14
+ * matrix.json) changes. renameEntry() rewrites one entry's meta.json title and
15
+ * deleteEntry() removes one entry folder (writer 'project-home'). mdNetwork()
16
+ * maps the project's markdown link network on demand
14
17
  * (lib/mdNetworkScan.cjs) for the Tools pane. matrix() reads the saved
15
18
  * Competitor matrix (lib/project-pages/competitiveMatrix.cjs readMatrix).
16
19
  * mdReview() reads the newest Review MD network record plus each review
@@ -159,13 +162,18 @@ function isLibraryPath(rel) {
159
162
  //
160
163
  // project-pages:get is a one-shot pull; this adds a per-cwd chokidar watcher
161
164
  // on the project-pages dir that recomputes get() and pushes it to the
162
- // renderer when home.html is added/changed/removed. Map<realCwd, { watcher,
163
- // refCount }> — refcounted so several mounted components watching the same
164
- // cwd share one chokidar instance.
165
+ // renderer whenever a path isLibraryPath accepts is added, changed or removed:
166
+ // knowledge/<id>/ and videos/<id>/ index.html or meta.json, the two legacy
167
+ // files home.html and demo-video/index.html, and matrix/matrix.json.
168
+ // Map<realCwd, { watcher, refCount }> — refcounted so several mounted
169
+ // components watching the same cwd share one chokidar instance.
165
170
  const outputWatchers = new Map();
166
171
 
167
172
  /**
168
- * Watch `cwd`'s home.html. Resolves `{ ok: true }` once watching is live (or
173
+ * Watch `cwd`'s project-pages dir: recomputes get() and pushes it whenever a
174
+ * path isLibraryPath accepts is added, changed or removed (knowledge/<id>/ and
175
+ * videos/<id>/ index.html or meta.json, the legacy home.html and
176
+ * demo-video/index.html, and matrix/matrix.json). Resolves `{ ok: true }` once watching is live (or
169
177
  * already watching), or `{ ok: false, reason: 'ephemeral' | 'invalid-cwd' }`
170
178
  * when there is nothing safe to watch — not an error, just "no live updates
171
179
  * for this cwd". Waits for chokidar's 'ready' so a write landing right after
@@ -76,7 +76,7 @@ function mintEventId() {
76
76
  * id, title }` of a macro build's saved entry), and `reply` (`{ fromCwd,
77
77
  * fromEpicId, outcome, referencePaths }` — a cross-project reply's origin, plus
78
78
  * a receipt's optional `hash`/`delivery`/`toEpicId`/`fallbackEpicId`/`reason`/
79
- * `reused`). All
79
+ * `reused`/`release`). All
80
80
  * keys are added to the event object only when present in `meta`, never as
81
81
  * `undefined`-valued keys, so events appended without them serialize
82
82
  * identically to before.
@@ -129,10 +129,25 @@ async function appendResponseEventWithReason(cwd, sourcePromptId, text, meta = {
129
129
  if (typeof meta.reply[k] === 'string' && meta.reply[k]) event.reply[k] = meta.reply[k];
130
130
  }
131
131
  if (meta.reply.reused === true) event.reply.reused = true;
132
+ // A verified release claim (crossProjectReply.cjs): { version, commits }.
133
+ const rel = meta.reply.release;
134
+ if (rel && typeof rel === 'object' && typeof rel.version === 'string'
135
+ && Array.isArray(rel.commits) && rel.commits.every((c) => typeof c === 'string')) {
136
+ event.reply.release = { version: rel.version, commits: rel.commits.slice() };
137
+ }
132
138
  }
133
139
  data.events[sourcePromptId] = [...events, event];
134
140
  await config.writeJson(path, data, { writer: 'scheduler' });
135
141
  broadcast(EVENT_APPENDED_CHANNEL, { cwd, promptSessionId: sourcePromptId, event });
142
+ // Outside-state poke (lib/epic/epicStateEmitter.cjs): a verdict or PRD
143
+ // check-in on this chain writes no event-log kind the emitter listens
144
+ // for, so poke it here. Only after a successful write; never changes
145
+ // the result.
146
+ try {
147
+ require('./lib/epic/epicStateEmitter.cjs').pokeEpicState(cwd, sourcePromptId);
148
+ } catch (e) {
149
+ console.error('[promptSessionEvents] pokeEpicState failed', cwd, sourcePromptId, e);
150
+ }
136
151
  return { ok: true };
137
152
  });
138
153
  } catch (e) {
package/src/main/pty.cjs CHANGED
@@ -25,8 +25,10 @@ const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
25
25
  const opsErrorLog = require('./lib/telemetry/opsErrorLog.cjs');
26
26
  const { planEpicSpawn } = require('./lib/epic/epicSpawnPlan.cjs');
27
27
  const { resolveEpicSpawnCwd } = require('./lib/epic/epicSpawnCwd.cjs');
28
+ const epicDepsSync = require('./lib/epic/epicDepsSync.cjs');
28
29
  const telemetryCounters = require('./lib/telemetry/telemetryCounters.cjs');
29
30
  const artifactStore = require('./lib/epic/artifactStore.cjs');
31
+ const artifactNotice = require('./lib/epic/artifactNotice.cjs');
30
32
  const { findEpicByClaudeSessionId } = require('./lib/claude/agentModelResolve.cjs');
31
33
 
32
34
  // Absolute path to the installed package root (src/main/ -> ../../), shown in
@@ -58,8 +60,9 @@ const ARTIFACT_MIN_AGE_MS = 10_000;
58
60
  * Sweep an Epic Terminal's artifact staging folder (runId = tabId) into the
59
61
  * Artifacts store every ARTIFACT_INGEST_MS. Returns stop(), which clears the
60
62
  * interval and runs one final sweep with no age floor (after any in-flight
61
- * sweep). Notices are not posted here — artifact-ready-notice owns them.
62
- * Errors are logged, never thrown.
63
+ * sweep). Each sweep (interval or exit) that published one or more files posts
64
+ * ONE 'artifact-ready' notice to the Epic chat, as the chat turn-end ingest
65
+ * does; an empty sweep posts nothing. Errors are logged, never thrown.
63
66
  */
64
67
  function startArtifactIngest({ cwd, epicId, tabId }) {
65
68
  let running = Promise.resolve();
@@ -75,6 +78,13 @@ function startArtifactIngest({ cwd, epicId, tabId }) {
75
78
  for (const s of res?.skipped || []) {
76
79
  if (s.reason !== 'still being written') console.error('[pty] artifact not ingested', s.path, s.reason);
77
80
  }
81
+ if (res && Array.isArray(res.published) && res.published.length > 0) {
82
+ try {
83
+ await artifactNotice.postArtifactReadyNotice({ cwd, epicId, entries: res.published });
84
+ } catch (err) {
85
+ console.error('[pty] artifact-ready notice failed', tabId, err?.message ?? err);
86
+ }
87
+ }
78
88
  } catch (err) {
79
89
  console.error('[pty] artifact ingest failed', tabId, err?.message ?? err);
80
90
  }
@@ -329,6 +339,8 @@ class PtyManager {
329
339
  }
330
340
  if (spawnCwd !== cwd) {
331
341
  console.log(`[pty] tabId=${tabId} isolated in worktree ${spawnCwd}`);
342
+ // Refresh the worktree's node_modules links (fire-and-forget, throttled).
343
+ epicDepsSync.syncEpicWorktreeDeps({ projectCwd: cwd, worktreeCwd: spawnCwd });
332
344
  }
333
345
  let proc;
334
346
  try {
@@ -388,7 +388,7 @@ async function archiveMany(slugs, cwd, { retire = true, jobs } = {}) {
388
388
  for (const slug of slugs) {
389
389
  if (!cancelled.has(slug)) { toArchive.push(slug); continue; }
390
390
  const warning = `"${slug}" is a cancelled job — archiving it would make it satisfy dependsOn. `
391
- + `Dismiss it instead (${DISMISS_ROUTE}); not archived.`;
391
+ + `Dismiss it instead (scheduler_dismiss_cancelled, or ${DISMISS_ROUTE}); not archived.`;
392
392
  warnings.push(warning);
393
393
  refused.push({ ok: false, slug, cancelled: true, warning, error: warning });
394
394
  }
@@ -341,8 +341,9 @@ function scanHaltLine(text) {
341
341
  }
342
342
 
343
343
  /**
344
- * One-line reason after `SCHEDULER_VERDICT: FAIL` (same two-source scan order
345
- * as scanSentinel). Trimmed, capped at 300 chars; '' when absent.
344
+ * One-line reason after `SCHEDULER_VERDICT: FAIL` or `NEEDS_HUMAN` (same
345
+ * two-source scan order as scanSentinel), so it also returns NEEDS_HUMAN
346
+ * reasons. Trimmed, capped at 300 chars; '' when absent.
346
347
  */
347
348
  function scanSentinelReason(resultEvent, events) {
348
349
  const RE = /^SCHEDULER_VERDICT:\s*(?:FAIL|NEEDS_HUMAN)\b[ \t]*([^\n]*)/m;
@@ -653,7 +654,7 @@ function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
653
654
  */
654
655
  function captureArtifactEvidence({ prdPath, roots, startedAt, fsImpl = fs } = {}) {
655
656
  try {
656
- const text = fs.readFileSync(prdPath, 'utf8');
657
+ const text = fsImpl.readFileSync(prdPath, 'utf8');
657
658
  const fm = parsePrdFile(text).frontmatter;
658
659
  if (!isArtifactOnlyDeclaration(fm)) return null;
659
660
  const check = artifactsCheck({ cwd: roots, paths: fm.artifactPaths, startedAt, finishedAt: null, fsImpl });
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * planReviewHold.cjs — pure rule deciding which plans need an independent plan
5
+ * review, which pending rows are held 'held: plan-review' until it lands, and
6
+ * which holds have timed out. Shaped like computePreflightHolds so the tick can
7
+ * merge `held` into heldSlugs. No fs: the caller passes queue rows and the
8
+ * stored review records ({ [bareValidateSlug]: record }).
9
+ *
10
+ * Record fields read (all optional): `release` (non-null object, as planReviewStore.recordPlanRelease writes it = released),
11
+ * `firstReviewAt` / `reviews[0].at` (hold start when a review exists).
12
+ */
13
+
14
+ const { bareSlug } = require('../lib/prd/depSlugResolve.cjs');
15
+
16
+ const DEFAULT_HOLD_MINUTES = 240;
17
+ const REVIEWER_AGENT = 'plan-reviewer';
18
+
19
+ function holdMsFromEnv(env = process.env) {
20
+ const n = Number(env.SM_PLAN_REVIEW_HOLD_MINUTES);
21
+ const minutes = Number.isFinite(n) && n > 0 ? n : DEFAULT_HOLD_MINUTES;
22
+ return minutes * 60 * 1000;
23
+ }
24
+
25
+ function planReviewEnabled(env = process.env) {
26
+ return String(env.SM_PLAN_REVIEW ?? '') !== '0';
27
+ }
28
+
29
+ /**
30
+ * Transitive dependsOn walk from a validator row. Same-cwd only (a row with no
31
+ * cwd is kept), bare-slug matching. Excludes the validator and reviewer rows.
32
+ * @param {any} validateRow
33
+ * @param {any[]} rows
34
+ * @returns {any[]}
35
+ */
36
+ function planMembers(validateRow, rows) {
37
+ if (!validateRow || !Array.isArray(rows)) return [];
38
+ const scoped = rows.filter((r) => r && (!validateRow.cwd || r.cwd == null || r.cwd === validateRow.cwd));
39
+ const byBare = new Map();
40
+ for (const r of scoped) {
41
+ const b = bareSlug(r.slug);
42
+ if (!byBare.has(b)) byBare.set(b, []);
43
+ byBare.get(b).push(r);
44
+ }
45
+ const members = [];
46
+ const seen = new Set();
47
+ const visited = new Set();
48
+ const queue = Array.isArray(validateRow.dependsOn) ? [...validateRow.dependsOn] : [];
49
+ while (queue.length) {
50
+ const dep = bareSlug(queue.shift());
51
+ if (visited.has(dep)) continue;
52
+ visited.add(dep);
53
+ for (const row of byBare.get(dep) ?? []) {
54
+ if (row === validateRow || row.slug === validateRow.slug) continue;
55
+ if (row.agentType === REVIEWER_AGENT || row.agentType === 'validator') continue;
56
+ if (!seen.has(row.slug)) {
57
+ seen.add(row.slug);
58
+ members.push(row);
59
+ }
60
+ for (const d of row.dependsOn ?? []) if (!visited.has(bareSlug(d))) queue.push(d);
61
+ }
62
+ }
63
+ return members;
64
+ }
65
+
66
+ /** True when >= 3 members, or any member depends on another member. */
67
+ function qualifiesForReview(members) {
68
+ if (!Array.isArray(members)) return false;
69
+ if (members.length >= 3) return true;
70
+ const bares = new Set(members.map((m) => bareSlug(m.slug)));
71
+ return members.some((m) => (m.dependsOn ?? []).some(
72
+ (d) => bares.has(bareSlug(d)) && bareSlug(d) !== bareSlug(m.slug),
73
+ ));
74
+ }
75
+
76
+ function isReleased(record) {
77
+ return !!record && record.release != null && typeof record.release === 'object';
78
+ }
79
+
80
+ function holdStartMs(validateRow, record) {
81
+ const first = record?.firstReviewAt ?? record?.reviews?.[0]?.at;
82
+ const t = Date.parse(first ?? '');
83
+ if (Number.isFinite(t)) return t;
84
+ const c = Date.parse(validateRow.createdAt ?? '');
85
+ return Number.isFinite(c) ? c : null;
86
+ }
87
+
88
+ /**
89
+ * @param {any[]} rows
90
+ * @param {Record<string, any>} reviewsByValidateSlug keyed by bare validate slug
91
+ * @param {{ now?: number, holdMs?: number }} [opts]
92
+ * @returns {{ held: Map<string, string>, needsReview: string[], expired: string[] }}
93
+ */
94
+ function computePlanReviewHolds(rows, reviewsByValidateSlug, opts = {}) {
95
+ const now = opts.now ?? Date.now();
96
+ const holdMs = opts.holdMs ?? holdMsFromEnv();
97
+ const held = new Map();
98
+ const needsReview = [];
99
+ const expired = [];
100
+ const reviews = reviewsByValidateSlug || {};
101
+ for (const v of rows || []) {
102
+ if (!v || v.status !== 'pending' || v.agentType !== 'validator' || v.planReview !== 'required') continue;
103
+ const members = planMembers(v, rows);
104
+ if (!qualifiesForReview(members)) continue;
105
+ const record = reviews[bareSlug(v.slug)];
106
+ if (isReleased(record)) continue;
107
+ const hasReview = !!record && (record.firstReviewAt || (Array.isArray(record.reviews) && record.reviews.length > 0));
108
+ if (!hasReview) needsReview.push(v.slug);
109
+ const start = holdStartMs(v, record);
110
+ if (start != null && now - start > holdMs) expired.push(v.slug);
111
+ const reason = `held: plan-review — waiting on independent review of plan ${bareSlug(v.slug)}`;
112
+ for (const m of members) {
113
+ if (m.status === 'pending') held.set(m.slug, reason);
114
+ }
115
+ }
116
+ return { held, needsReview, expired };
117
+ }
118
+
119
+ const MODEL_FAMILIES = ['opus', 'sonnet', 'haiku', 'fable'];
120
+ function familyOf(model) {
121
+ const m = String(model ?? '').toLowerCase();
122
+ return MODEL_FAMILIES.find((f) => m.includes(f)) || null;
123
+ }
124
+
125
+ /**
126
+ * The reviewer must not share the planner's model family: personaModel is kept
127
+ * unless it matches plannerModel's family, then 'opus' (persona sonnet) else 'sonnet'.
128
+ */
129
+ function reviewerModelFor(personaModel, plannerModel) {
130
+ const persona = String(personaModel ?? '').trim();
131
+ const pf = familyOf(persona);
132
+ const lf = familyOf(plannerModel);
133
+ if (persona && !(pf && lf && pf === lf)) return persona;
134
+ return pf === 'sonnet' ? 'opus' : 'sonnet';
135
+ }
136
+
137
+ module.exports = {
138
+ reviewerModelFor,
139
+ planMembers, qualifiesForReview, computePlanReviewHolds, holdMsFromEnv, planReviewEnabled,
140
+ };