claude-code-session-manager 0.139.0 → 0.141.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 (154) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
  3. package/dist/assets/History-DJMiuXyK.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
  7. package/dist/assets/Scheduler-cyr61UAC.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
  14. package/dist/assets/index-B2TQz3nd.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  33. package/scripts/README.md +1 -0
  34. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  35. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  36. package/scripts/ops-sweep.cjs +53 -23
  37. package/scripts/scheduler-mcp-server.cjs +205 -18
  38. package/src/main/build-info.json +4 -4
  39. package/src/main/config.cjs +112 -8
  40. package/src/main/docEdit.cjs +6 -1
  41. package/src/main/files.cjs +7 -27
  42. package/src/main/health.cjs +48 -15
  43. package/src/main/historyAggregator.cjs +88 -5
  44. package/src/main/historyDashboard.cjs +69 -4
  45. package/src/main/index.cjs +56 -2
  46. package/src/main/ipcSchemas.cjs +122 -16
  47. package/src/main/lib/AGENTS.md +54 -0
  48. package/src/main/lib/CLAUDE.md +1 -54
  49. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  50. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  51. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  52. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  53. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  54. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  55. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  56. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  57. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  58. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  59. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  60. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  61. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  62. package/src/main/lib/ephemeralCwd.cjs +37 -2
  63. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  64. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  65. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  66. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  67. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  68. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  69. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  70. package/src/main/lib/externalContract.cjs +31 -5
  71. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  72. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  73. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  74. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  75. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  76. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  77. package/src/main/lib/git/branchSweep.cjs +209 -4
  78. package/src/main/lib/git/gitWorktree.cjs +41 -5
  79. package/src/main/lib/guardShims.cjs +1 -1
  80. package/src/main/lib/historyRollup.cjs +26 -0
  81. package/src/main/lib/insideHome.cjs +27 -1
  82. package/src/main/lib/mcpToolCatalog.cjs +132 -13
  83. package/src/main/lib/mdDocCensus.cjs +59 -78
  84. package/src/main/lib/mdDocRefs.cjs +71 -93
  85. package/src/main/lib/mdNetworkScan.cjs +245 -250
  86. package/src/main/lib/mdReviewRecord.cjs +22 -9
  87. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  88. package/src/main/lib/opsOwnership.cjs +18 -2
  89. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  90. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  91. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  92. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  93. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  94. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  95. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  96. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  97. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  98. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  99. package/src/main/lib/prd/prdCreate.cjs +377 -23
  100. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  101. package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
  102. package/src/main/lib/process/loginItem.cjs +171 -0
  103. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  104. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  105. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  106. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  107. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  108. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  109. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  110. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  111. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  112. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  113. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  114. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  115. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  116. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  117. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  118. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  119. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  120. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  121. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  122. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  123. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  124. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  125. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  126. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  127. package/src/main/lib/tasks/taskRun.cjs +313 -0
  128. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  129. package/src/main/loginItemIpc.cjs +35 -0
  130. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  131. package/src/main/projectPages.cjs +6 -15
  132. package/src/main/promptSessionEvents.cjs +9 -1
  133. package/src/main/queueOps.cjs +260 -3
  134. package/src/main/runVerify.cjs +53 -25
  135. package/src/main/scheduler/AGENTS.md +26 -0
  136. package/src/main/scheduler/CLAUDE.md +1 -26
  137. package/src/main/scheduler/budget.cjs +239 -9
  138. package/src/main/scheduler/cancelDependents.cjs +154 -0
  139. package/src/main/scheduler/prdParser.cjs +19 -1
  140. package/src/main/scheduler/reviewLadder.cjs +36 -3
  141. package/src/main/scheduler/starvation.cjs +89 -18
  142. package/src/main/scheduler.cjs +1080 -89
  143. package/src/main/supervisor.cjs +5 -1
  144. package/src/main/templates/PRD_AUTHORING.md +14 -1
  145. package/src/main/validationQualityHandlers.cjs +199 -0
  146. package/src/main/webRemote.cjs +10 -2
  147. package/src/preload/api.d.ts +364 -21
  148. package/src/preload/apiSurface.json +89 -10
  149. package/src/preload/index.cjs +23 -2
  150. package/src/seed/agents/validator.md +19 -8
  151. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  152. package/dist/assets/History-DDnqaLyw.js +0 -2
  153. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  154. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -0,0 +1,268 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * videoReview.cjs — the one writer of a video entry's human review step:
5
+ * session-manager-operations/project-pages/videos/<id>/review/ (namespace
6
+ * 'project-pages', owner 'project-home' in lib/opsOwnership.cjs).
7
+ *
8
+ * dispatch.json — written by the app when a review-tool run is queued
9
+ * material.json — + image-1.<ext> .. image-N.<ext>, written by the
10
+ * agent-facing review write tool (writeMaterial)
11
+ * decision.json — written ONLY by the human decision IPC (writeDecision)
12
+ *
13
+ * reviewStatus() derives the state from those three records, purely.
14
+ * Plain Node: no Electron import. Paths come from opsPath; every write goes
15
+ * through assertOpsWrite + util/atomicFs.cjs (tmp+rename).
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const fsp = require('node:fs/promises');
20
+ const path = require('node:path');
21
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
22
+ const { writeJsonAtomic, writeTextAtomic, readJsonOr } = require('../util/atomicFs.cjs');
23
+ const { ENTRY_ID_RE } = require('../../ipcSchemas.cjs');
24
+
25
+ const WRITER = 'project-home';
26
+ const REVIEW_MATERIAL_REL = 'session-manager-operations/project-pages/videos/{id}/review/material.json';
27
+ const REVIEW_TEXT_MAX = 32000;
28
+ const REVIEW_IMAGES_MAX = 6;
29
+ const REVIEW_IMAGE_BYTES_MAX = 2 * 1024 * 1024;
30
+ const NOTE_MAX = 2000;
31
+ const AT_MAX = 40;
32
+ const STAGE_MAX = 40;
33
+ const DECISIONS = Object.freeze(['approve', 'changes']);
34
+ const IMAGE_NAME_RE = /^image-\d+\.(png|jpg|webp)$/;
35
+
36
+ /** Strictly increasing ISO stamps, so records written in the same ms still order. */
37
+ let lastStampMs = 0;
38
+ function nowIso() {
39
+ let ms = Date.now();
40
+ if (ms <= lastStampMs) ms = lastStampMs + 1;
41
+ lastStampMs = ms;
42
+ return new Date(ms).toISOString();
43
+ }
44
+
45
+ function reviewDir(cwd, entryId) {
46
+ return opsPath(cwd, 'project-pages', 'videos', entryId, 'review');
47
+ }
48
+
49
+ function validEntryId(entryId) {
50
+ return typeof entryId === 'string' && ENTRY_ID_RE.test(entryId);
51
+ }
52
+
53
+ async function writeJson(abs, obj) {
54
+ assertOpsWrite(abs, WRITER);
55
+ await writeJsonAtomic(abs, obj);
56
+ }
57
+
58
+ /** -> 'png' | 'jpg' | 'webp' | null, by magic bytes only. */
59
+ function imageExt(buf) {
60
+ if (!Buffer.isBuffer(buf)) return null;
61
+ if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
62
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpg';
63
+ if (buf.length >= 12 && buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') return 'webp';
64
+ return null;
65
+ }
66
+
67
+ async function readRecords(dir) {
68
+ const [dispatch, material, decision] = await Promise.all([
69
+ readJsonOr(path.join(dir, 'dispatch.json'), null),
70
+ readJsonOr(path.join(dir, 'material.json'), null),
71
+ readJsonOr(path.join(dir, 'decision.json'), null),
72
+ ]);
73
+ return { dispatch, material, decision };
74
+ }
75
+
76
+ const ms = (iso) => {
77
+ const t = Date.parse(iso);
78
+ return Number.isFinite(t) ? t : -Infinity;
79
+ };
80
+
81
+ /**
82
+ * reviewStatus({ dispatch, material, decision }) -> 'building' | 'waiting' |
83
+ * 'approved' | 'changes-requested' | null. Pure. The newest record wins; ties
84
+ * go to the later lifecycle step. A 'final' dispatch never outranks a decision.
85
+ */
86
+ function reviewStatus(records) {
87
+ const { dispatch = null, material = null, decision = null } = records || {};
88
+ const candidates = [];
89
+ if (dispatch && !(dispatch.stage === 'final' && decision)) {
90
+ candidates.push({ t: ms(dispatch.dispatchedAt), rank: 0, status: 'building' });
91
+ }
92
+ if (material) candidates.push({ t: ms(material.savedAt), rank: 1, status: 'waiting' });
93
+ if (decision) {
94
+ candidates.push({
95
+ t: ms(decision.decidedAt),
96
+ rank: 2,
97
+ status: decision.decision === 'approve' ? 'approved' : 'changes-requested',
98
+ });
99
+ }
100
+ if (!candidates.length) return null;
101
+ candidates.sort((a, b) => (b.t - a.t) || (b.rank - a.rank));
102
+ return candidates[0].status;
103
+ }
104
+
105
+ /**
106
+ * recordDispatch(cwd, entryId, { macroId, epicId, slug, stage, inputValues, extraInstructions })
107
+ * -> { ok: true, path, dispatch } | { ok: false, error }
108
+ */
109
+ async function recordDispatch(cwd, entryId, input = {}) {
110
+ if (!validEntryId(entryId)) return { ok: false, error: 'invalid entryId' };
111
+ const { macroId, epicId = null, slug = '', stage, inputValues = {}, extraInstructions = '' } = input || {};
112
+ if (typeof macroId !== 'string' || !macroId) return { ok: false, error: 'macroId required' };
113
+ if (epicId !== null && typeof epicId !== 'string') return { ok: false, error: 'epicId must be a string or null' };
114
+ if (typeof slug !== 'string') return { ok: false, error: 'slug must be a string' };
115
+ if (typeof stage !== 'string' || !stage || stage.length > STAGE_MAX) return { ok: false, error: 'stage required (1-40 chars)' };
116
+ if (!inputValues || typeof inputValues !== 'object' || Array.isArray(inputValues)) {
117
+ return { ok: false, error: 'inputValues must be an object' };
118
+ }
119
+ if (typeof extraInstructions !== 'string') return { ok: false, error: 'extraInstructions must be a string' };
120
+ const dispatch = { entryId, macroId, epicId, slug, stage, inputValues, extraInstructions, dispatchedAt: nowIso() };
121
+ const abs = path.join(reviewDir(cwd, entryId), 'dispatch.json');
122
+ await writeJson(abs, dispatch);
123
+ return { ok: true, path: abs, dispatch };
124
+ }
125
+
126
+ /**
127
+ * writeMaterial(cwd, entryId, { text, images: [{ bytes: Buffer }] })
128
+ * -> { ok: true, path, material } | { ok: false, error }
129
+ * Replaces the previous material and images. Refused without dispatch.json.
130
+ */
131
+ async function writeMaterial(cwd, entryId, input = {}) {
132
+ if (!validEntryId(entryId)) return { ok: false, error: 'invalid entryId' };
133
+ const { text, images } = input || {};
134
+ if (typeof text !== 'string' || text.length < 1 || text.length > REVIEW_TEXT_MAX) {
135
+ return { ok: false, error: `text must be 1-${REVIEW_TEXT_MAX} chars` };
136
+ }
137
+ if (!Array.isArray(images) || images.length < 1 || images.length > REVIEW_IMAGES_MAX) {
138
+ return { ok: false, error: `images must be 1-${REVIEW_IMAGES_MAX} items` };
139
+ }
140
+ const exts = [];
141
+ for (let i = 0; i < images.length; i++) {
142
+ const bytes = images[i] && images[i].bytes;
143
+ if (!Buffer.isBuffer(bytes)) return { ok: false, error: `image ${i + 1}: bytes must be a Buffer` };
144
+ if (bytes.length > REVIEW_IMAGE_BYTES_MAX) return { ok: false, error: `image ${i + 1}: larger than 2 MiB` };
145
+ const ext = imageExt(bytes);
146
+ if (!ext) return { ok: false, error: `image ${i + 1}: not a PNG, JPEG or WebP` };
147
+ exts.push(ext);
148
+ }
149
+ const dir = reviewDir(cwd, entryId);
150
+ const dispatch = await readJsonOr(path.join(dir, 'dispatch.json'), null);
151
+ if (!dispatch) return { ok: false, error: 'no dispatch for this entry' };
152
+
153
+ const names = exts.map((ext, i) => `image-${i + 1}.${ext}`);
154
+ for (let i = 0; i < names.length; i++) {
155
+ const abs = path.join(dir, names[i]);
156
+ assertOpsWrite(abs, WRITER);
157
+ // atomicFs.writeTextAtomic writes a Buffer verbatim (encoding is ignored for Buffers).
158
+ await writeTextAtomic(abs, images[i].bytes);
159
+ }
160
+ let existing = [];
161
+ try { existing = await fsp.readdir(dir); } catch { /* dir was just created */ }
162
+ for (const name of existing) {
163
+ if (IMAGE_NAME_RE.test(name) && !names.includes(name)) {
164
+ const abs = path.join(dir, name);
165
+ assertOpsWrite(abs, WRITER);
166
+ await fsp.unlink(abs);
167
+ }
168
+ }
169
+ const material = { entryId, text, images: names.map((name) => ({ name })), savedAt: nowIso() };
170
+ const abs = path.join(dir, 'material.json');
171
+ await writeJson(abs, material);
172
+ return { ok: true, path: abs, material };
173
+ }
174
+
175
+ /**
176
+ * writeDecision(cwd, entryId, { decision, note, at }) — the human decision.
177
+ * -> { ok: true, path, decision } | { ok: false, error }
178
+ */
179
+ async function writeDecision(cwd, entryId, input = {}) {
180
+ if (!validEntryId(entryId)) return { ok: false, error: 'invalid entryId' };
181
+ const { decision, note, at } = input || {};
182
+ if (!DECISIONS.includes(decision)) return { ok: false, error: "decision must be 'approve' or 'changes'" };
183
+ const record = { entryId, decision };
184
+ if (decision === 'changes') {
185
+ const n = typeof note === 'string' ? note.replace(/\s*[\r\n]+\s*/g, ' ').trim() : '';
186
+ if (n.length < 1 || n.length > NOTE_MAX) return { ok: false, error: `note must be 1-${NOTE_MAX} chars` };
187
+ record.note = n;
188
+ } else {
189
+ if (typeof at !== 'string' || at.length < 1 || at.length > AT_MAX || /[\r\n]/.test(at)) {
190
+ return { ok: false, error: `at must be a 1-${AT_MAX} char single line` };
191
+ }
192
+ record.at = at;
193
+ }
194
+ const dir = reviewDir(cwd, entryId);
195
+ const { material, decision: prior } = await readRecords(dir);
196
+ if (!material) return { ok: false, error: 'no material to decide on' };
197
+ if (prior && ms(prior.decidedAt) >= ms(material.savedAt)) return { ok: false, error: 'already decided' };
198
+ record.decidedAt = nowIso();
199
+ const abs = path.join(dir, 'decision.json');
200
+ await writeJson(abs, record);
201
+ return { ok: true, path: abs, decision: record };
202
+ }
203
+
204
+ /** readReview(cwd, entryId) -> { entryId, dispatch, material, decision, status } | null */
205
+ async function readReview(cwd, entryId) {
206
+ if (!validEntryId(entryId)) return null;
207
+ const dir = reviewDir(cwd, entryId);
208
+ if (!fs.existsSync(dir)) return null;
209
+ const records = await readRecords(dir);
210
+ let material = records.material;
211
+ if (material) {
212
+ const images = Array.isArray(material.images) ? material.images : [];
213
+ material = {
214
+ ...material,
215
+ images: images
216
+ .filter((img) => img && typeof img.name === 'string' && IMAGE_NAME_RE.test(img.name))
217
+ .map((img) => ({ name: img.name, path: path.join(dir, img.name) })),
218
+ };
219
+ }
220
+ return {
221
+ entryId,
222
+ dispatch: records.dispatch,
223
+ material,
224
+ decision: records.decision,
225
+ status: reviewStatus(records),
226
+ };
227
+ }
228
+
229
+ function newestStamp(r) {
230
+ return Math.max(
231
+ r.dispatch ? ms(r.dispatch.dispatchedAt) : -Infinity,
232
+ r.material ? ms(r.material.savedAt) : -Infinity,
233
+ r.decision ? ms(r.decision.decidedAt) : -Infinity,
234
+ );
235
+ }
236
+
237
+ /** listReviews(cwd) -> every entry with a review folder, newest record first. */
238
+ async function listReviews(cwd) {
239
+ const videosDir = opsPath(cwd, 'project-pages', 'videos');
240
+ let names;
241
+ try {
242
+ names = await fsp.readdir(videosDir);
243
+ } catch (e) {
244
+ if (e && e.code === 'ENOENT') return [];
245
+ throw e;
246
+ }
247
+ const out = [];
248
+ for (const name of names) {
249
+ if (!validEntryId(name)) continue;
250
+ const r = await readReview(cwd, name);
251
+ if (r) out.push(r);
252
+ }
253
+ out.sort((a, b) => newestStamp(b) - newestStamp(a));
254
+ return out;
255
+ }
256
+
257
+ module.exports = {
258
+ REVIEW_MATERIAL_REL,
259
+ REVIEW_TEXT_MAX,
260
+ REVIEW_IMAGES_MAX,
261
+ REVIEW_IMAGE_BYTES_MAX,
262
+ recordDispatch,
263
+ writeMaterial,
264
+ writeDecision,
265
+ readReview,
266
+ listReviews,
267
+ reviewStatus,
268
+ };
@@ -0,0 +1,229 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * videoReviewIpc.cjs — IPC handlers `project-videos:review-list`,
5
+ * `project-videos:review-decide` and `project-videos:review-retry`: the human
6
+ * review step of a project Video
7
+ * tool entry. Renderer IPC only — no admin route or MCP tool reaches a
8
+ * decision, and nothing here mints an Epic.
9
+ *
10
+ * approve — starts the tool's final run in the Epic that built the entry
11
+ * (runToolJob, review { decision: 'approved', at }), then writes
12
+ * decision.json with that same `at`.
13
+ * changes — re-runs the review stage with the owner's note, then writes
14
+ * decision.json with the note.
15
+ *
16
+ * retry — an approved entry whose final run failed: re-dispatches the
17
+ * final stage with the recorded approval `at` and inputs; writes
18
+ * no decision; archives the old failed slug (best effort).
19
+ *
20
+ * A decision is written only after an ok dispatch. One decide/retry per entry
21
+ * at a time (module-level in-flight set), so a double click dispatches one run.
22
+ * review-list adds each entry's `job` (jobStatusesBySlug for dispatch.slug, or
23
+ * null) and `canRetry` (retryable()).
24
+ *
25
+ * deps: the same deps registerMacroJobIpc gets ({ schemas, validatePath,
26
+ * readActiveIndex, createPrd, loadJobs, archivePrd, ... }), plus
27
+ * optional readHistoryTail, and videoReview / runToolJob /
28
+ * jobStatusesBySlug / now overrides for tests.
29
+ */
30
+
31
+ const NOT_RETRYABLE_ERROR = 'only an approved entry whose final run failed can be retried';
32
+ const IN_FLIGHT_ERROR = 'a decision or retry for this entry is already in progress';
33
+ const INACTIVE_ERROR = 'the session that built this entry is no longer active — press the tool again';
34
+
35
+ /** In-flight decides and retries (they share one slot per entry), keyed `${cwd}\0${entryId}`. */
36
+ const inFlight = new Set();
37
+
38
+ function defaultVideoReview() {
39
+ return require('./videoReview.cjs');
40
+ }
41
+
42
+ function defaultJobStatusesBySlug() {
43
+ return require('../persona-macro/macroJobStatus.cjs').jobStatusesBySlug;
44
+ }
45
+
46
+ /**
47
+ * retryable(review, job) -> boolean. Pure. True only for an approved entry
48
+ * (decision 'approve' with a non-empty at) whose recorded final-stage run's
49
+ * job ended failed. No job row counts as not failed.
50
+ */
51
+ function retryable(review, job) {
52
+ if (!review || review.status !== 'approved') return false;
53
+ const d = review.decision;
54
+ if (!d || d.decision !== 'approve' || typeof d.at !== 'string' || !d.at.trim()) return false;
55
+ if (!review.dispatch || review.dispatch.stage !== 'final') return false;
56
+ return !!job && job.state === 'failed';
57
+ }
58
+
59
+ /** { [slug]: job | null } for the given reviews' dispatch slugs. */
60
+ async function jobsFor(deps, cwd, reviews) {
61
+ const bySlug = deps.jobStatusesBySlug || defaultJobStatusesBySlug();
62
+ const slugs = reviews.map((r) => r && r.dispatch && r.dispatch.slug).filter((s) => typeof s === 'string' && s);
63
+ if (!slugs.length) return {};
64
+ const io = { loadJobs: deps.loadJobs };
65
+ if (typeof deps.readHistoryTail === 'function') io.readHistoryTail = deps.readHistoryTail;
66
+ try {
67
+ return (await bySlug({ cwd, slugs }, io)) || {};
68
+ } catch {
69
+ return {};
70
+ }
71
+ }
72
+
73
+ function jobOf(jobs, review) {
74
+ const slug = review && review.dispatch && review.dispatch.slug;
75
+ return (typeof slug === 'string' && slug && jobs[slug]) || null;
76
+ }
77
+
78
+ function defaultRunToolJob() {
79
+ return require('../persona-macro/macroJobIpc.cjs').runToolJob;
80
+ }
81
+
82
+ /** '2026-11-22 13:05 PST' — the machine's local zone, 24-hour clock. */
83
+ function formatLocalAt(date = new Date()) {
84
+ const parts = new Intl.DateTimeFormat('en-US', {
85
+ year: 'numeric', month: '2-digit', day: '2-digit',
86
+ hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
87
+ timeZoneName: 'short',
88
+ }).formatToParts(date);
89
+ const get = (type) => (parts.find((p) => p.type === type) || {}).value || '';
90
+ return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')} ${get('timeZoneName')}`.trim();
91
+ }
92
+
93
+ /** Drop every 'Replace entry:' line, then name this entry. */
94
+ function replaceEntryInstructions(extra, entryId) {
95
+ const kept = (typeof extra === 'string' ? extra : '')
96
+ .split(/\r?\n/)
97
+ .filter((l) => !/^\s*replace entry:/i.test(l))
98
+ .join('\n')
99
+ .trim();
100
+ return [kept, `Replace entry: ${entryId}`].filter(Boolean).join('\n');
101
+ }
102
+
103
+ function epicIsActive(readActiveIndex, cwd, epicId) {
104
+ if (typeof epicId !== 'string' || !epicId) return false;
105
+ const index = readActiveIndex(cwd);
106
+ const sessions = index && index.sessions ? index.sessions : {};
107
+ if (!Object.prototype.hasOwnProperty.call(sessions, epicId)) return false;
108
+ const entry = sessions[epicId];
109
+ return !!entry && entry.status === 'active';
110
+ }
111
+
112
+ /** decide(deps, { cwd, entryId, decision, note }) — `cwd` already validated. */
113
+ async function decide(deps, { cwd, entryId, decision, note }) {
114
+ const videoReview = deps.videoReview || defaultVideoReview();
115
+ const runToolJob = deps.runToolJob || defaultRunToolJob();
116
+ const key = `${cwd}\0${entryId}`;
117
+ if (inFlight.has(key)) return { ok: false, error: IN_FLIGHT_ERROR };
118
+ inFlight.add(key);
119
+ try {
120
+ const trimmedNote = typeof note === 'string' ? note.trim() : '';
121
+ if (decision === 'changes' && !trimmedNote) return { ok: false, error: 'a note is required to ask for changes' };
122
+
123
+ const rev = await videoReview.readReview(cwd, entryId);
124
+ if (!rev || rev.status !== 'waiting') {
125
+ return { ok: false, error: `entry ${entryId} is not waiting for review (${rev ? rev.status : 'no review'})` };
126
+ }
127
+ const dispatch = rev.dispatch;
128
+ if (!dispatch || typeof dispatch.macroId !== 'string' || !dispatch.macroId) {
129
+ return { ok: false, error: `entry ${entryId} has no recorded tool run` };
130
+ }
131
+ if (!epicIsActive(deps.readActiveIndex, cwd, dispatch.epicId)) return { ok: false, error: INACTIVE_ERROR };
132
+
133
+ const at = decision === 'approve' ? formatLocalAt(deps.now ? deps.now() : new Date()) : null;
134
+ const review = decision === 'approve'
135
+ ? { decision: 'approved', at }
136
+ : { decision: 'changes', note: trimmedNote };
137
+
138
+ const result = await runToolJob(deps, {
139
+ cwd,
140
+ macroId: dispatch.macroId,
141
+ epicId: dispatch.epicId,
142
+ inputValues: dispatch.inputValues && typeof dispatch.inputValues === 'object' ? dispatch.inputValues : {},
143
+ extraInstructions: replaceEntryInstructions(dispatch.extraInstructions, entryId),
144
+ review,
145
+ });
146
+ if (!result || result.ok !== true) {
147
+ return { ok: false, error: (result && result.error) || 'dispatch failed' };
148
+ }
149
+
150
+ const written = await videoReview.writeDecision(cwd, entryId, decision === 'approve'
151
+ ? { decision: 'approve', at }
152
+ : { decision: 'changes', note: trimmedNote });
153
+ if (!written || written.ok !== true) {
154
+ return { ok: false, error: `run queued (${result.slug}) but the decision was not recorded: ${(written && written.error) || 'unknown error'}` };
155
+ }
156
+ return { ok: true, slug: result.slug, stage: result.stage, decision: written.decision };
157
+ } finally {
158
+ inFlight.delete(key);
159
+ }
160
+ }
161
+
162
+ /** retry(deps, { cwd, entryId }) — `cwd` already validated. Writes no decision. */
163
+ async function retry(deps, { cwd, entryId }) {
164
+ const videoReview = deps.videoReview || defaultVideoReview();
165
+ const runToolJob = deps.runToolJob || defaultRunToolJob();
166
+ const key = `${cwd}\0${entryId}`;
167
+ if (inFlight.has(key)) return { ok: false, error: IN_FLIGHT_ERROR };
168
+ inFlight.add(key);
169
+ try {
170
+ const rev = await videoReview.readReview(cwd, entryId);
171
+ const job = rev ? jobOf(await jobsFor(deps, cwd, [rev]), rev) : null;
172
+ if (!retryable(rev, job)) return { ok: false, error: NOT_RETRYABLE_ERROR };
173
+ const dispatch = rev.dispatch;
174
+ if (typeof dispatch.macroId !== 'string' || !dispatch.macroId) return { ok: false, error: NOT_RETRYABLE_ERROR };
175
+ const oldSlug = dispatch.slug;
176
+
177
+ const result = await runToolJob(deps, {
178
+ cwd,
179
+ macroId: dispatch.macroId,
180
+ epicId: dispatch.epicId,
181
+ inputValues: dispatch.inputValues && typeof dispatch.inputValues === 'object' ? dispatch.inputValues : {},
182
+ extraInstructions: replaceEntryInstructions(dispatch.extraInstructions, entryId),
183
+ review: { decision: 'approved', at: rev.decision.at },
184
+ });
185
+ if (result && result.ok === true && typeof deps.archivePrd === 'function' && oldSlug && oldSlug !== result.slug) {
186
+ try { await deps.archivePrd(oldSlug, cwd); } catch { /* best effort */ }
187
+ }
188
+ return result;
189
+ } finally {
190
+ inFlight.delete(key);
191
+ }
192
+ }
193
+
194
+ function registerVideoReviewIpc(ipcMain, deps = {}) {
195
+ ipcMain.handle('project-videos:review-list', async (_event, rawPayload) => {
196
+ const payload = deps.schemas.projectVideosReviewList.parse(rawPayload);
197
+ const cwd = deps.validatePath(payload.cwd);
198
+ const videoReview = deps.videoReview || defaultVideoReview();
199
+ const reviews = await videoReview.listReviews(cwd);
200
+ const list = Array.isArray(reviews) ? reviews : [];
201
+ const jobs = await jobsFor(deps, cwd, list);
202
+ return list.map((r) => {
203
+ const job = jobOf(jobs, r);
204
+ return { ...r, job, canRetry: retryable(r, job) };
205
+ });
206
+ });
207
+
208
+ ipcMain.handle('project-videos:review-decide', async (_event, rawPayload) => {
209
+ const payload = deps.schemas.projectVideosReviewDecide.parse(rawPayload);
210
+ const cwd = deps.validatePath(payload.cwd);
211
+ return decide(deps, {
212
+ cwd,
213
+ entryId: payload.entryId,
214
+ decision: payload.decision,
215
+ note: payload.note,
216
+ });
217
+ });
218
+
219
+ ipcMain.handle('project-videos:review-retry', async (_event, rawPayload) => {
220
+ const payload = deps.schemas.projectVideosReviewRetry.parse(rawPayload);
221
+ const cwd = deps.validatePath(payload.cwd);
222
+ return retry(deps, { cwd, entryId: payload.entryId });
223
+ });
224
+ }
225
+
226
+ module.exports = {
227
+ registerVideoReviewIpc, formatLocalAt, replaceEntryInstructions, retryable,
228
+ INACTIVE_ERROR, NOT_RETRYABLE_ERROR,
229
+ };
@@ -7,7 +7,17 @@
7
7
  * it can read high on a mostly idle machine (2026-11-01, 14 CPUs: 25 D-state
8
8
  * tasks gave loadavg1 22.39 while the CPU was only 24% busy over 75 s). This
9
9
  * helper derives busy/total from cumulative counters over a window of about a
10
- * minute instead. Pure and injectable (`read`, `now`).
10
+ * minute instead. Pure and injectable (`read`, `readOwn`, `now`).
11
+ *
12
+ * Own-process exclusion (PRD 3495): 2026-11-22 the gate held launches at
13
+ * loadavg ratios 2.21 … 1.01 on 14 cores while this app's own renderer averaged
14
+ * ~81% CPU and main ~45%. The app must not gate on its own load, so the sampler
15
+ * also tracks the app's own process tree (main + Electron `--type=` helpers:
16
+ * zygote, renderer, GPU, utility) from /proc/<pid>/stat and reports busy both
17
+ * raw and net of it. Spawned jobs (claude -p and their children) are NOT own
18
+ * processes — they carry no `--type=` flag — so they stay in the net figure.
19
+ * /proc/stat and /proc/<pid>/stat are both in USER_HZ clock ticks, so the
20
+ * deltas subtract directly. Off Linux the own reading is null and net = raw.
11
21
  */
12
22
 
13
23
  const fs = require('node:fs');
@@ -81,18 +91,128 @@ function readCpuTimes({
81
91
  }
82
92
 
83
93
  /**
84
- * @param {{ read?: () => ({busy:number,iowait?:number,total:number}|null), now?: () => number,
94
+ * Parse one /proc/<pid>/stat line → { pid, ppid, ticks: utime+stime }.
95
+ * comm (field 2) may contain spaces and parens, so split after the LAST ')'.
96
+ * @param {string} text
97
+ * @returns {{ pid: number, ppid: number, ticks: number } | null}
98
+ */
99
+ function parsePidStat(text) {
100
+ if (typeof text !== 'string' || !text) return null;
101
+ const close = text.lastIndexOf(')');
102
+ const open = text.indexOf('(');
103
+ if (close < 0 || open < 0) return null;
104
+ const pid = Number(text.slice(0, open).trim());
105
+ // After ')': state(3) ppid(4) ... utime(14) stime(15) → indices 0,1,...,11,12.
106
+ const rest = text.slice(close + 1).trim().split(/\s+/);
107
+ const ppid = Number(rest[1]);
108
+ const utime = Number(rest[11]);
109
+ const stime = Number(rest[12]);
110
+ if (![pid, ppid, utime, stime].every(Number.isFinite)) return null;
111
+ return { pid, ppid, ticks: utime + stime };
112
+ }
113
+
114
+ /**
115
+ * True when a /proc/<pid>/cmdline names an Electron/Chromium helper: `--type=`
116
+ * among the first two arguments. Chromium helpers rewrite their argv into one
117
+ * space-joined string (setproctitle), so split on NUL and space.
118
+ * @param {string} cmd
119
+ */
120
+ function isElectronHelperCmdline(cmd) {
121
+ if (typeof cmd !== 'string') return false;
122
+ return cmd.split(/[\0 ]+/).slice(1, 3).some((a) => a.startsWith('--type='));
123
+ }
124
+
125
+ /**
126
+ * The app's own process tree as Map<pid, cumulative utime+stime ticks>: the
127
+ * root (Electron main) plus every descendant reached only through processes
128
+ * whose cmdline carries an Electron `--type=` flag. Linux only; null elsewhere
129
+ * or when /proc cannot be listed. Never throws.
130
+ * A helper must also run the same executable as the root (when /proc/<pid>/exe
131
+ * is readable), so a job whose prompt text happens to contain "--type=" never
132
+ * counts as own.
133
+ * @param {{ rootPid?: number, platform?: string, readdir?: (p: string) => string[],
134
+ * readFile?: (p: string) => string, readlink?: (p: string) => string }} [deps]
135
+ * @returns {Map<number, number> | null}
136
+ */
137
+ function readOwnProcessTicks({
138
+ rootPid = process.pid,
139
+ platform = process.platform,
140
+ readdir = (p) => fs.readdirSync(p),
141
+ readFile = (p) => fs.readFileSync(p, 'utf8'),
142
+ readlink = (p) => fs.readlinkSync(p),
143
+ } = {}) {
144
+ if (platform !== 'linux') return null;
145
+ try {
146
+ /** @type {Map<number, { ppid: number, ticks: number }>} */
147
+ const procs = new Map();
148
+ /** @type {Map<number, number[]>} */
149
+ const children = new Map();
150
+ for (const name of readdir('/proc')) {
151
+ if (!/^\d+$/.test(name)) continue;
152
+ let st;
153
+ try { st = parsePidStat(readFile(`/proc/${name}/stat`)); } catch { continue; }
154
+ if (!st) continue;
155
+ procs.set(st.pid, { ppid: st.ppid, ticks: st.ticks });
156
+ const list = children.get(st.ppid);
157
+ if (list) list.push(st.pid); else children.set(st.ppid, [st.pid]);
158
+ }
159
+ const root = procs.get(rootPid);
160
+ if (!root) return null;
161
+ const exeOf = (/** @type {number} */ pid) => { try { return readlink(`/proc/${pid}/exe`); } catch { return null; } };
162
+ const rootExe = exeOf(rootPid);
163
+ /** @type {Map<number, number>} */
164
+ const own = new Map([[rootPid, root.ticks]]);
165
+ const queue = [rootPid];
166
+ while (queue.length) {
167
+ const parent = /** @type {number} */ (queue.shift());
168
+ for (const child of children.get(parent) || []) {
169
+ let cmd = '';
170
+ try { cmd = readFile(`/proc/${child}/cmdline`); } catch { continue; }
171
+ if (!isElectronHelperCmdline(cmd)) continue;
172
+ if (rootExe !== null && exeOf(child) !== rootExe) continue;
173
+ own.set(child, /** @type {{ticks:number}} */ (procs.get(child)).ticks);
174
+ queue.push(child);
175
+ }
176
+ }
177
+ return own;
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Own-process ticks consumed between two readings. A pid only in `before`
185
+ * exited (its last ticks are lost, count 0); a pid only in `after` started in
186
+ * the window, so all its ticks count.
187
+ * @param {Map<number, number> | null} before
188
+ * @param {Map<number, number> | null} after
189
+ * @returns {number | null}
190
+ */
191
+ function ownTicksDelta(before, after) {
192
+ if (!before || !after) return null;
193
+ let d = 0;
194
+ for (const [pid, ticks] of after) {
195
+ const prev = before.get(pid);
196
+ d += prev === undefined ? ticks : Math.max(0, ticks - prev);
197
+ }
198
+ return d;
199
+ }
200
+
201
+ /**
202
+ * @param {{ read?: () => ({busy:number,iowait?:number,total:number}|null),
203
+ * readOwn?: () => (Map<number, number>|null), now?: () => number,
85
204
  * windowMs?: number, minWindowMs?: number, maxWindowMs?: number, minSpacingMs?: number }} [opts]
86
205
  */
87
206
  function createCpuSampler({
88
207
  read = readCpuTimes,
208
+ readOwn = () => readOwnProcessTicks(),
89
209
  now = () => Date.now(),
90
210
  windowMs = DEFAULT_WINDOW_MS,
91
211
  minWindowMs = MIN_WINDOW_MS,
92
212
  maxWindowMs = MAX_WINDOW_MS,
93
213
  minSpacingMs = MIN_SPACING_MS,
94
214
  } = {}) {
95
- /** @type {{ at: number, busy: number, iowait: number, total: number }[]} */
215
+ /** @type {{ at: number, busy: number, iowait: number, total: number, own: Map<number, number> | null }[]} */
96
216
  let entries = [];
97
217
 
98
218
  function observe() {
@@ -101,7 +221,7 @@ function createCpuSampler({
101
221
  if (!r) return;
102
222
  const newest = entries[entries.length - 1];
103
223
  if (newest && t - newest.at < minSpacingMs) return;
104
- entries.push({ at: t, busy: r.busy, iowait: r.iowait ?? 0, total: r.total });
224
+ entries.push({ at: t, busy: r.busy, iowait: r.iowait ?? 0, total: r.total, own: readOwn() });
105
225
  entries = entries.filter((e) => t - e.at <= maxWindowMs);
106
226
  }
107
227
 
@@ -126,8 +246,12 @@ function createCpuSampler({
126
246
  const dIowait = (r.iowait ?? 0) - best.iowait;
127
247
  // Per-CPU idle and iowait counters can step backwards.
128
248
  if (dTotal <= 0 || dBusy < 0) return null;
249
+ const dOwnRaw = ownTicksDelta(best.own, readOwn());
250
+ const dOwn = dOwnRaw === null ? null : Math.min(dBusy, dOwnRaw);
129
251
  return {
130
252
  busyFraction: Math.min(1, dBusy / dTotal),
253
+ ownFraction: dOwn === null ? null : dOwn / dTotal,
254
+ netBusyFraction: Math.min(1, (dBusy - (dOwn ?? 0)) / dTotal),
131
255
  iowaitFraction: Math.min(1, Math.max(0, dIowait / dTotal)),
132
256
  windowMs: t - best.at,
133
257
  };
@@ -138,6 +262,9 @@ function createCpuSampler({
138
262
 
139
263
  module.exports = {
140
264
  parseProcStat,
265
+ parsePidStat,
266
+ readOwnProcessTicks,
267
+ ownTicksDelta,
141
268
  readCpuTimes,
142
269
  createCpuSampler,
143
270
  DEFAULT_WINDOW_MS,