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
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * heldSchedulerTurns.cjs — the one place that decides whether a scheduler-started
5
+ * chat turn (origin 'scheduler': PLAN SETTLED digests, job notices, auto-start
6
+ * follow-ups) may start under the usage hold, and that keeps every held message
7
+ * durably until the hold ends.
8
+ *
9
+ * Store: schedulerPaths.heldSchedulerTurnsPath() — { version: 1, entries: [] }.
10
+ * Each entry: { id, tabId, kind, prompt, sessionId, cwd, heldAt, holdReason, holdDetail, lastAttempt? }.
11
+ *
12
+ * An 'unconfirmed' send that carries a requestId (the renderer ack timed out) stamps
13
+ * its entries with lastAttempt { requestId, at } and drain skips them for
14
+ * LAST_ATTEMPT_GRACE_MS: the renderer may still have run the turn. A late ack
15
+ * (chatRunner → confirmLateDelivery(requestId)) removes them; no ack → resent once
16
+ * after the grace.
17
+ *
18
+ * drain() delivers each tab's held messages ONCE, oldest first, as one coalesced
19
+ * prompt; entries are removed only after the send resolved a disposition that
20
+ * produced (or queued) a run.
21
+ *
22
+ * Must NOT require chatRunner.cjs or scheduler.cjs — both require this module.
23
+ * No audit writes here: callers audit drain()'s return value.
24
+ */
25
+
26
+ const crypto = require('node:crypto');
27
+ const { writeJsonAtomicSync, readJsonOrSync } = require('../util/atomicFs.cjs');
28
+ const { heldSchedulerTurnsPath } = require('./schedulerPaths.cjs');
29
+
30
+ const KINDS = Object.freeze(['settle-digest', 'job-notice', 'auto-start-follow-up', 'scheduler-notice']);
31
+ // 'held': the hold returned between the drain check and the send. The batch is not
32
+ // re-deferred (heldBatch), so the originals must stay or they are lost.
33
+ const NOT_ACCEPTED = new Set(['refused', 'unconfirmed', 'held']);
34
+ const LAST_ATTEMPT_GRACE_MS = 10 * 60 * 1000;
35
+
36
+ /** @type {null | (() => any)} */
37
+ let holdProvider = null;
38
+ /** @type {null | Promise<Array<{ tabId: string, delivered: number, dropped: number }>>} */
39
+ let draining = null;
40
+
41
+ function setHoldProvider(fn) {
42
+ holdProvider = typeof fn === 'function' ? fn : null;
43
+ }
44
+
45
+ /** The current usage hold object, or null (no provider, provider throws, or no hold). */
46
+ function currentHold() {
47
+ if (!holdProvider) return null;
48
+ try {
49
+ const hold = holdProvider();
50
+ return hold && typeof hold === 'object' ? hold : null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ function isEntry(e) {
57
+ return !!e && typeof e === 'object' && typeof e.id === 'string'
58
+ && typeof e.tabId === 'string' && typeof e.prompt === 'string';
59
+ }
60
+
61
+ function readEntries() {
62
+ let file;
63
+ try { file = readJsonOrSync(heldSchedulerTurnsPath(), null); } catch { return []; }
64
+ if (!file || typeof file !== 'object' || !Array.isArray(file.entries)) return [];
65
+ return file.entries.filter(isEntry);
66
+ }
67
+
68
+ function writeEntries(entries) {
69
+ writeJsonAtomicSync(heldSchedulerTurnsPath(), { version: 1, entries });
70
+ }
71
+
72
+ /**
73
+ * Keep one scheduler message for later. The same tabId+kind+prompt already held
74
+ * is not stored twice (the existing entry is returned).
75
+ */
76
+ function defer({ tabId, prompt, kind, sessionId, cwd, hold } = /** @type {any} */ ({})) {
77
+ if (typeof tabId !== 'string' || !tabId) throw new TypeError('defer: tabId required');
78
+ if (typeof prompt !== 'string' || !prompt) throw new TypeError('defer: prompt required');
79
+ const k = KINDS.includes(kind) ? kind : 'scheduler-notice';
80
+ const entries = readEntries();
81
+ const existing = entries.find((e) => e.tabId === tabId && e.kind === k && e.prompt === prompt);
82
+ if (existing) return existing;
83
+ const entry = {
84
+ id: crypto.randomUUID(),
85
+ tabId,
86
+ kind: k,
87
+ prompt,
88
+ sessionId: typeof sessionId === 'string' && sessionId ? sessionId : null,
89
+ cwd: typeof cwd === 'string' && cwd ? cwd : null,
90
+ heldAt: new Date().toISOString(),
91
+ holdReason: hold && typeof hold.reason === 'string' ? hold.reason : null,
92
+ holdDetail: hold && typeof hold.detail === 'string' ? hold.detail : null,
93
+ };
94
+ entries.push(entry);
95
+ writeEntries(entries);
96
+ return entry;
97
+ }
98
+
99
+ const SUMMARY_TAB_LIMIT = 20;
100
+
101
+ /** { count, tabs }: tabs = unique tab ids, oldest-held first, at most SUMMARY_TAB_LIMIT. */
102
+ function summary() {
103
+ const entries = readEntries();
104
+ const tabs = [...new Set([...entries].sort(byHeldAt).map((e) => e.tabId))].slice(0, SUMMARY_TAB_LIMIT);
105
+ return { count: entries.length, tabs };
106
+ }
107
+
108
+ function byHeldAt(a, b) {
109
+ const ta = Date.parse(a.heldAt) || 0;
110
+ const tb = Date.parse(b.heldAt) || 0;
111
+ return ta - tb;
112
+ }
113
+
114
+ function buildCoalescedPrompt(entries) {
115
+ const list = [...entries].sort(byHeldAt);
116
+ const n = list.length;
117
+ const parts = [
118
+ `The usage hold kept ${n} scheduler message(s) for this session while automatic work was paused. They are delivered now, oldest first.`,
119
+ ];
120
+ list.forEach((e, i) => { parts.push(`--- ${i + 1} of ${n} ---\n${e.prompt}`); });
121
+ return parts.join('\n\n');
122
+ }
123
+
124
+ /** True while an entry's last unconfirmed attempt may still be acked late. */
125
+ function inAttemptGrace(e, now) {
126
+ const a = e.lastAttempt;
127
+ if (!a || typeof a !== 'object' || typeof a.requestId !== 'string') return false;
128
+ const at = Date.parse(a.at);
129
+ return Number.isFinite(at) && now - at < LAST_ATTEMPT_GRACE_MS;
130
+ }
131
+
132
+ /** Stamp the given entry ids with lastAttempt (one atomic write). */
133
+ function stampAttempt(ids, requestId) {
134
+ const at = new Date().toISOString();
135
+ const entries = readEntries();
136
+ let changed = false;
137
+ for (const e of entries) {
138
+ if (ids.has(e.id)) { e.lastAttempt = { requestId, at }; changed = true; }
139
+ }
140
+ if (changed) writeEntries(entries);
141
+ }
142
+
143
+ /**
144
+ * The renderer acked a timed-out send late (a run was produced): remove exactly
145
+ * the entries stamped with that requestId, in one atomic write. Returns the count.
146
+ */
147
+ function confirmLateDelivery(requestId) {
148
+ if (typeof requestId !== 'string' || !requestId) return 0;
149
+ const entries = readEntries();
150
+ const left = entries.filter((e) => !(e.lastAttempt && e.lastAttempt.requestId === requestId));
151
+ const removed = entries.length - left.length;
152
+ if (removed > 0) writeEntries(left);
153
+ return removed;
154
+ }
155
+
156
+ async function drainOnce({ send, isStillNeeded }) {
157
+ const now = Date.now();
158
+ const entries = readEntries().filter((e) => !inAttemptGrace(e, now));
159
+ if (entries.length === 0) return [];
160
+ /** @type {Map<string, any[]>} */
161
+ const groups = new Map();
162
+ for (const e of [...entries].sort(byHeldAt)) {
163
+ if (!groups.has(e.tabId)) groups.set(e.tabId, []);
164
+ groups.get(e.tabId).push(e);
165
+ }
166
+ const remove = new Set();
167
+ const results = [];
168
+ for (const [tabId, group] of groups) {
169
+ const keep = [];
170
+ let dropped = 0;
171
+ for (const e of group) {
172
+ let needed = true;
173
+ if (typeof isStillNeeded === 'function') {
174
+ try { needed = (await isStillNeeded(e)) !== false; } catch { needed = true; }
175
+ }
176
+ if (needed) keep.push(e);
177
+ else { dropped += 1; remove.add(e.id); }
178
+ }
179
+ let delivered = 0;
180
+ if (keep.length > 0) {
181
+ const head = keep.find((e) => e.sessionId) ?? keep[0];
182
+ const withCwd = keep.find((e) => e.cwd) ?? keep[0];
183
+ let disposition = 'unconfirmed';
184
+ let requestId = null;
185
+ try {
186
+ const res = await send(tabId, buildCoalescedPrompt(keep), {
187
+ origin: 'scheduler',
188
+ heldBatch: true,
189
+ sessionId: head.sessionId ?? undefined,
190
+ cwd: withCwd.cwd ?? undefined,
191
+ });
192
+ disposition = res && typeof res.disposition === 'string' ? res.disposition : 'unconfirmed';
193
+ requestId = res && typeof res.requestId === 'string' && res.requestId ? res.requestId : null;
194
+ } catch {
195
+ disposition = 'unconfirmed';
196
+ }
197
+ // Stamp right away (synchronously after the send resolved) so a late ack
198
+ // arriving while other tabs are still sending finds its entries.
199
+ if (disposition === 'unconfirmed' && requestId) {
200
+ stampAttempt(new Set(keep.map((e) => e.id)), requestId);
201
+ }
202
+ if (!NOT_ACCEPTED.has(disposition)) {
203
+ delivered = keep.length;
204
+ for (const e of keep) remove.add(e.id);
205
+ }
206
+ }
207
+ results.push({ tabId, delivered, dropped });
208
+ }
209
+ if (remove.size > 0) {
210
+ // Re-read: entries deferred while sends were in flight are kept.
211
+ writeEntries(readEntries().filter((e) => !remove.has(e.id)));
212
+ }
213
+ return results;
214
+ }
215
+
216
+ /**
217
+ * Deliver every tab's held messages once. Single-flight: a call while a drain
218
+ * runs returns that drain's promise.
219
+ * @param {{ send: (tabId: string, prompt: string, extra: object) => Promise<{ disposition: string }>, isStillNeeded?: (entry: any) => boolean | Promise<boolean> }} opts
220
+ */
221
+ function drain(opts) {
222
+ if (draining) return draining;
223
+ if (!opts || typeof opts.send !== 'function') return Promise.resolve([]);
224
+ draining = drainOnce(opts).finally(() => { draining = null; });
225
+ return draining;
226
+ }
227
+
228
+ module.exports = {
229
+ KINDS,
230
+ setHoldProvider,
231
+ currentHold,
232
+ defer,
233
+ summary,
234
+ buildCoalescedPrompt,
235
+ drain,
236
+ confirmLateDelivery,
237
+ LAST_ATTEMPT_GRACE_MS,
238
+ };
@@ -57,6 +57,16 @@ function normalizeSample(s) {
57
57
  return out;
58
58
  }
59
59
 
60
+ /**
61
+ * Re-append identity of a stored sample, independent of its key order (never JSON.stringify).
62
+ * With runId + unit: (runId, unit, at). Without either: every field (agentType, peakMb, at,
63
+ * runId, unit), so a legacy or provenance-less peak never collides with another on `at` alone.
64
+ */
65
+ function sampleKey(x) {
66
+ if (x.runId && x.unit) return `p\0${x.runId}\0${x.unit}\0${x.at}`;
67
+ return `f\0${x.agentType}\0${x.peakMb}\0${x.at}\0${x.runId || ''}\0${x.unit || ''}`;
68
+ }
69
+
60
70
  function defaultStorePath() {
61
71
  return path.join(require('./schedulerPaths.cjs').schedulerHome(), STORE_FILE);
62
72
  }
@@ -269,8 +279,8 @@ function createJobMemoryStats(deps = {}) {
269
279
  liveDuringWrite = null;
270
280
  if (landed.length && samples && samples.length) {
271
281
  const stored = readSamplesUncached(file);
272
- const have = new Set(stored.map((x) => JSON.stringify(x)));
273
- const missing = landed.filter((x) => !have.has(JSON.stringify(x)));
282
+ const have = new Set(stored.map(sampleKey));
283
+ const missing = landed.filter((x) => !have.has(sampleKey(x)));
274
284
  if (missing.length) writeSamples(file, [...stored, ...missing]);
275
285
  }
276
286
  }
@@ -303,6 +313,7 @@ module.exports = {
303
313
  backfillFromRunLogs: defaultInstance.backfillFromRunLogs,
304
314
  createJobMemoryStats,
305
315
  quantile,
316
+ sampleKey,
306
317
  STORE_FILE,
307
318
  MAX_SAMPLES,
308
319
  RECENT_PER_TYPE,
@@ -24,80 +24,240 @@ function errMsg(e) {
24
24
  return e && e.message ? e.message : String(e);
25
25
  }
26
26
 
27
+ const DECLARED_PREFIX = `${OPS_ROOT_DIR}/${NAMESPACE}/`;
28
+ const CROSS_EPIC_EXISTS = 'exists in another Epic folder; not overwritten';
29
+ const SYMLINKED_PARENT = 'symlinked parent refused';
30
+
31
+ /**
32
+ * refusedParent(chain) → { path, reason } | null
33
+ * lstat-checks each source parent in order (outermost first) without ever
34
+ * following a link. A symlink anywhere in the chain is refused; a missing
35
+ * entry ends the check (nothing below it exists to copy); any other lstat
36
+ * error is refused too, so an unreadable parent never lets a pass through.
37
+ * @param {string[]} chain @param {typeof fs} [fsImpl]
38
+ * @returns {{ path: string, reason: string } | null}
39
+ */
40
+ function refusedParent(chain, fsImpl = fs) {
41
+ for (const p of chain) {
42
+ let st;
43
+ try {
44
+ st = fsImpl.lstatSync(p);
45
+ } catch (e) {
46
+ if (e && /** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT') return null;
47
+ return { path: p, reason: `cannot check parent: ${errMsg(e)}` };
48
+ }
49
+ if (st.isSymbolicLink()) return { path: p, reason: SYMLINKED_PARENT };
50
+ }
51
+ return null;
52
+ }
53
+
27
54
  /**
28
- * harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl })
55
+ * destExists(dest) → true when anything (file, folder, symlink — never
56
+ * followed) sits at `dest`. Any lstat error other than ENOENT counts as
57
+ * existing, so an unreadable destination is never overwritten.
58
+ * @param {string} dest @param {typeof fs} [fsImpl]
59
+ */
60
+ function destExists(dest, fsImpl = fs) {
61
+ try {
62
+ fsImpl.lstatSync(dest);
63
+ return true;
64
+ } catch (e) {
65
+ return !(e && /** @type {NodeJS.ErrnoException} */ (e).code === 'ENOENT');
66
+ }
67
+ }
68
+
69
+ /**
70
+ * createExclusive(dest, text, fsImpl) → true when created, false when `dest`
71
+ * already existed (EEXIST). Writes a temp file beside `dest`, then hard-links
72
+ * it into place: link fails with EEXIST rather than overwriting, so create-only
73
+ * is one atomic step with no check-then-write gap. The temp file is always
74
+ * removed. Other errors throw.
75
+ * @param {string} dest @param {string} text @param {any} [fsImpl]
76
+ */
77
+ function createExclusive(dest, text, fsImpl = fs) {
78
+ const link = fsImpl.linkSync || fs.linkSync;
79
+ const unlink = fsImpl.unlinkSync || fs.unlinkSync;
80
+ const mkdir = fsImpl.mkdirSync || fs.mkdirSync;
81
+ const write = fsImpl.writeFileSync || fs.writeFileSync;
82
+ const dir = path.dirname(dest);
83
+ mkdir(dir, { recursive: true });
84
+ const tmp = path.join(dir, `.${path.basename(dest)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
85
+ try {
86
+ write(tmp, text, { encoding: 'utf8', flag: 'wx' });
87
+ try {
88
+ link(tmp, dest);
89
+ } catch (e) {
90
+ if (e && /** @type {NodeJS.ErrnoException} */ (e).code === 'EEXIST') return false;
91
+ throw e;
92
+ }
93
+ return true;
94
+ } finally {
95
+ try { unlink(tmp); } catch { /* already gone */ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * parseDeclaredPath(p) → { folder, name } | { reason }
101
+ * A declared record must be exactly
102
+ * `session-manager-operations/plan-records/<epic-folder>/<name>.md` (posix,
103
+ * repo-relative), with no `..` segment and no NUL byte.
104
+ */
105
+ function parseDeclaredPath(p) {
106
+ if (typeof p !== 'string' || !p) return { reason: 'declared path is not a string' };
107
+ if (p.includes('\0')) return { reason: 'declared path contains a NUL byte' };
108
+ const posix = p.replace(/\\/g, '/');
109
+ if (posix.split('/').includes('..')) return { reason: 'declared path contains ..' };
110
+ if (path.posix.isAbsolute(posix)) return { reason: 'declared path is absolute' };
111
+ const norm = path.posix.normalize(posix);
112
+ if (!norm.startsWith(DECLARED_PREFIX)) return { reason: 'declared path is not under plan-records/' };
113
+ const parts = norm.slice(DECLARED_PREFIX.length).split('/');
114
+ if (parts.length !== 2) return { reason: 'declared path must be plan-records/<epic-folder>/<name>.md' };
115
+ const [folder, name] = parts;
116
+ if (!EPIC_ID_RE.test(folder)) return { reason: 'declared epic folder not allowed' };
117
+ if (!NAME_RE.test(name)) return { reason: 'name not allowed' };
118
+ return { folder, name };
119
+ }
120
+
121
+ /**
122
+ * harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths, fsImpl })
29
123
  * → { copied: string[], skipped: { path, reason }[] }
124
+ * Copies every record in the job's own `plan-records/<epicId>/` folder, plus
125
+ * each well-formed `declaredPaths` entry (the PRD's frontmatter
126
+ * artifactPaths), whose folder may be a different Epic's — create-only there:
127
+ * an existing destination in another Epic's folder is never overwritten.
30
128
  * `copied` holds destination absolute paths.
31
129
  */
32
- function harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl = fs } = {}) {
130
+ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths = [], fsImpl = fs } = {}) {
33
131
  /** @type {string[]} */
34
132
  const copied = [];
35
133
  /** @type {{ path: string, reason: string }[]} */
36
134
  const skipped = [];
37
- try {
38
- if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) {
39
- skipped.push({ path: String(epicId), reason: 'unsafe epicId' });
40
- return { copied, skipped };
41
- }
42
- if (typeof worktreeDir !== 'string' || !path.isAbsolute(worktreeDir)
43
- || typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
44
- skipped.push({ path: String(worktreeDir), reason: 'worktreeDir and projectRoot must be absolute paths' });
45
- return { copied, skipped };
46
- }
47
- if (path.resolve(worktreeDir) === path.resolve(projectRoot)) return { copied, skipped };
135
+ /** @type {Set<string>} source paths already handled */
136
+ const seen = new Set();
48
137
 
49
- const srcDir = path.join(path.resolve(worktreeDir), OPS_ROOT_DIR, NAMESPACE, epicId);
50
- let destDir;
138
+ /**
139
+ * Copy one record `src` to `plan-records/<folder>/<name>` in the main
140
+ * checkout with every safety check. Returns false when `missingReason` is
141
+ * set and the source does not exist (reported with that reason).
142
+ * @param {string} src @param {string} folder @param {string} name
143
+ * @param {string} [missingReason]
144
+ * @param {boolean} [createOnly] another Epic's folder: never overwrite an
145
+ * existing destination (checked with lstat, so a symlink counts as existing)
146
+ */
147
+ function copyOne(src, folder, name, missingReason, createOnly = false) {
148
+ seen.add(src);
51
149
  try {
52
- destDir = path.resolve(opsPath(projectRoot, NAMESPACE, epicId));
53
- } catch (e) {
54
- skipped.push({ path: srcDir, reason: `destination refused: ${errMsg(e)}` });
55
- return { copied, skipped };
56
- }
57
- if (destDir === srcDir) return { copied, skipped };
150
+ if (!NAME_RE.test(name)) { skipped.push({ path: src, reason: 'name not allowed' }); return; }
151
+ let st;
152
+ try {
153
+ st = fsImpl.lstatSync(src);
154
+ } catch (e) {
155
+ if (missingReason && e && e.code === 'ENOENT') { skipped.push({ path: src, reason: missingReason }); return; }
156
+ throw e;
157
+ }
158
+ if (st.isSymbolicLink()) { skipped.push({ path: src, reason: 'symlink' }); return; }
159
+ if (st.isDirectory()) { skipped.push({ path: src, reason: 'directory' }); return; }
160
+ if (!st.isFile()) { skipped.push({ path: src, reason: 'not a regular file' }); return; }
161
+ if (st.size > MAX_BYTES) { skipped.push({ path: src, reason: `oversize (${st.size} > ${MAX_BYTES} bytes)` }); return; }
58
162
 
59
- let srcStat;
60
- try {
61
- srcStat = fsImpl.lstatSync(srcDir);
62
- } catch {
63
- return { copied, skipped }; // no records written by this job
64
- }
65
- if (!srcStat.isDirectory()) {
66
- skipped.push({ path: srcDir, reason: 'source is not a directory' });
67
- return { copied, skipped };
68
- }
163
+ const destDir = path.resolve(opsPath(projectRoot, NAMESPACE, folder));
164
+ const dest = path.resolve(opsPath(projectRoot, NAMESPACE, folder, name));
165
+ if (path.dirname(dest) !== destDir) { skipped.push({ path: src, reason: 'destination escapes plan-records folder' }); return; }
166
+ if (dest === src) return;
167
+ const verdict = checkOpsWrite(dest, WRITER);
168
+ if (!verdict.ok) { skipped.push({ path: src, reason: `write refused: ${verdict.error}` }); return; }
169
+ assertOpsWrite(dest, WRITER);
69
170
 
70
- let names;
71
- try {
72
- names = fsImpl.readdirSync(srcDir).map(String).sort();
171
+ const text = fsImpl.readFileSync(src, 'utf8');
172
+ if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) { skipped.push({ path: src, reason: 'oversize after read' }); return; }
173
+ if (createOnly) {
174
+ if (!createExclusive(dest, text, fsImpl)) { skipped.push({ path: src, reason: CROSS_EPIC_EXISTS }); return; }
175
+ copied.push(dest);
176
+ return;
177
+ }
178
+ writeTextAtomicSync(dest, text);
179
+ copied.push(dest);
73
180
  } catch (e) {
74
- skipped.push({ path: srcDir, reason: `cannot list source: ${errMsg(e)}` });
181
+ skipped.push({ path: src, reason: `copy failed: ${errMsg(e)}` });
182
+ }
183
+ }
184
+
185
+ try {
186
+ // An unsafe epicId only disqualifies pass 1 (the job's own folder); each
187
+ // declared path is validated on its own in pass 2.
188
+ const ownFolderSafe = typeof epicId === 'string' && EPIC_ID_RE.test(epicId);
189
+ if (!ownFolderSafe) skipped.push({ path: String(epicId), reason: 'unsafe epicId' });
190
+ if (typeof worktreeDir !== 'string' || !path.isAbsolute(worktreeDir)
191
+ || typeof projectRoot !== 'string' || !path.isAbsolute(projectRoot)) {
192
+ skipped.push({ path: String(worktreeDir), reason: 'worktreeDir and projectRoot must be absolute paths' });
75
193
  return { copied, skipped };
76
194
  }
195
+ if (path.resolve(worktreeDir) === path.resolve(projectRoot)) return { copied, skipped };
196
+ const wtRoot = path.resolve(worktreeDir);
197
+ const opsSrc = path.join(wtRoot, OPS_ROOT_DIR);
198
+ const recordsSrc = path.join(opsSrc, NAMESPACE);
77
199
 
78
- for (const name of names) {
79
- const src = path.join(srcDir, name);
200
+ // Pass 1: everything in the job's own plan-records/<epicId>/ folder.
201
+ folderPass: {
202
+ if (!ownFolderSafe) break folderPass;
203
+ const srcDir = path.join(recordsSrc, epicId);
204
+ let destDir;
80
205
  try {
81
- if (!NAME_RE.test(name)) { skipped.push({ path: src, reason: 'name not allowed' }); continue; }
82
- const st = fsImpl.lstatSync(src);
83
- if (st.isSymbolicLink()) { skipped.push({ path: src, reason: 'symlink' }); continue; }
84
- if (st.isDirectory()) { skipped.push({ path: src, reason: 'directory' }); continue; }
85
- if (!st.isFile()) { skipped.push({ path: src, reason: 'not a regular file' }); continue; }
86
- if (st.size > MAX_BYTES) { skipped.push({ path: src, reason: `oversize (${st.size} > ${MAX_BYTES} bytes)` }); continue; }
87
-
88
- const dest = path.resolve(opsPath(projectRoot, NAMESPACE, epicId, name));
89
- if (path.dirname(dest) !== destDir) { skipped.push({ path: src, reason: 'destination escapes plan-records folder' }); continue; }
90
- const verdict = checkOpsWrite(dest, WRITER);
91
- if (!verdict.ok) { skipped.push({ path: src, reason: `write refused: ${verdict.error}` }); continue; }
92
- assertOpsWrite(dest, WRITER);
93
-
94
- const text = fsImpl.readFileSync(src, 'utf8');
95
- if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) { skipped.push({ path: src, reason: 'oversize after read' }); continue; }
96
- writeTextAtomicSync(dest, text);
97
- copied.push(dest);
206
+ destDir = path.resolve(opsPath(projectRoot, NAMESPACE, epicId));
98
207
  } catch (e) {
99
- skipped.push({ path: src, reason: `copy failed: ${errMsg(e)}` });
208
+ skipped.push({ path: srcDir, reason: `destination refused: ${errMsg(e)}` });
209
+ break folderPass;
210
+ }
211
+ if (destDir === srcDir) break folderPass;
212
+ // Never read through a symlinked session-manager-operations/,
213
+ // plan-records/ or epic folder: it could point outside the worktree.
214
+ const refused = refusedParent([opsSrc, recordsSrc, srcDir], fsImpl);
215
+ if (refused) { skipped.push(refused); break folderPass; }
216
+ let srcStat;
217
+ try {
218
+ srcStat = fsImpl.lstatSync(srcDir);
219
+ } catch {
220
+ break folderPass; // no records written by this job in its own folder
221
+ }
222
+ if (!srcStat.isDirectory()) {
223
+ skipped.push({ path: srcDir, reason: 'source is not a directory' });
224
+ break folderPass;
225
+ }
226
+ let names;
227
+ try {
228
+ names = fsImpl.readdirSync(srcDir).map(String).sort();
229
+ } catch (e) {
230
+ skipped.push({ path: srcDir, reason: `cannot list source: ${errMsg(e)}` });
231
+ break folderPass;
232
+ }
233
+ for (const name of names) copyOne(path.join(srcDir, name), epicId, name);
234
+ }
235
+
236
+ // Pass 2: records the PRD declared in frontmatter artifactPaths.
237
+ const declared = Array.isArray(declaredPaths) ? declaredPaths : [];
238
+ // The shared parents are checked once; a symlink there refuses the pass.
239
+ const sharedRefused = declared.length ? refusedParent([opsSrc, recordsSrc], fsImpl) : null;
240
+ if (sharedRefused) skipped.push(sharedRefused);
241
+ for (const p of sharedRefused ? [] : declared) {
242
+ const parsed = parseDeclaredPath(p);
243
+ if (!('folder' in parsed)) { skipped.push({ path: String(p), reason: parsed.reason }); continue; }
244
+ const src = path.join(recordsSrc, parsed.folder, parsed.name);
245
+ if (seen.has(src)) continue;
246
+ // Pass 1 refuses a symlinked/non-directory own folder; hold every
247
+ // declared folder to the same rule so a declaration cannot bypass it.
248
+ const folderDir = path.dirname(src);
249
+ const folderRefused = refusedParent([folderDir], fsImpl);
250
+ if (folderRefused) { seen.add(src); skipped.push(folderRefused); continue; }
251
+ let folderStat = null;
252
+ try { folderStat = fsImpl.lstatSync(folderDir); } catch { /* missing: copyOne reports */ }
253
+ if (folderStat && (!folderStat.isDirectory())) {
254
+ seen.add(src);
255
+ skipped.push({ path: src, reason: 'declared epic folder is not a directory' });
256
+ continue;
100
257
  }
258
+ // Another Epic's folder is create-only: a job may add a record there
259
+ // (a validator writing into the Epic it validates) but never overwrite one.
260
+ copyOne(src, parsed.folder, parsed.name, 'declared plan record not found in worktree', parsed.folder !== epicId);
101
261
  }
102
262
  } catch (e) {
103
263
  skipped.push({ path: String(worktreeDir), reason: `harvest failed: ${errMsg(e)}` });
@@ -0,0 +1,110 @@
1
+ /**
2
+ * planReleaseRoute.cjs — POST /admin/scheduler/release-plan: the planner's one
3
+ * call that releases a plan held for independent review.
4
+ *
5
+ * body { cwd, epicId, validateSlug, rejected: [{ finding, reason }],
6
+ * accepted: number, rereview?: boolean }
7
+ *
8
+ * - release: records plan-records/<epic>/<slug>.plan-review.json release
9
+ * { by: 'planner', rejected, accepted }. A second call → 200 alreadyReleased.
10
+ * Every rejected entry needs a non-empty one-line reason (400 otherwise).
11
+ * - rereview: true instead asks for ONE more review after a block. Accepted
12
+ * only when the latest review has a `block` decision and round is 1 and the
13
+ * plan is not released; writes rereviewRequested: true, else 400 + reason.
14
+ * - cwd must be an existing absolute project root outside session-manager-operations/ → else 400 bad_cwd.
15
+ * - unsafe epicId / validateSlug → 400.
16
+ */
17
+ 'use strict';
18
+
19
+ const { z } = require('zod');
20
+ const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
21
+ const { planReviewPath, readPlanReview, recordPlanRelease } = require('./planReviewStore.cjs');
22
+ const fs = require('node:fs');
23
+ const { assertOpsWrite, resolveProjectRoot } = require('../opsOwnership.cjs');
24
+ const { writeJsonAtomic } = require('../util/atomicFs.cjs');
25
+ const { EPIC_ID_RE } = require('./planRecordHarvest.cjs');
26
+
27
+ const MAX_BODY_BYTES = 256 * 1024;
28
+ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
29
+
30
+ const bodySchema = z.object({
31
+ cwd: z.string().min(1),
32
+ epicId: z.string(),
33
+ validateSlug: z.string(),
34
+ rejected: z.array(z.object({ finding: z.string(), reason: z.string() })).optional().default([]),
35
+ accepted: z.number().finite().min(0).optional().default(0),
36
+ rereview: z.boolean().optional(),
37
+ });
38
+
39
+ /** @param {any} record */
40
+ function latestHasBlock(record) {
41
+ const reviews = record && Array.isArray(record.reviews) ? record.reviews : [];
42
+ const last = reviews[reviews.length - 1];
43
+ const prds = last && last.review && Array.isArray(last.review.prds) ? last.review.prds : [];
44
+ return prds.some((/** @type {any} */ p) => p && p.decision === 'block');
45
+ }
46
+
47
+ /** @param {{ registerRoute: Function }} adminHttp */
48
+ function registerPlanReleaseRoute(adminHttp) {
49
+ adminHttp.registerRoute('POST', '/admin/scheduler/release-plan', async (/** @type {any} */ req, /** @type {any} */ res) => {
50
+ const bad = (/** @type {any} */ details) => sendJson(res, 400, { ok: false, error: 'invalid_request', details });
51
+ let raw;
52
+ try { raw = await readBody(req, MAX_BODY_BYTES); } catch (e) {
53
+ bad(e instanceof Error ? e.message : String(e));
54
+ return;
55
+ }
56
+ let json;
57
+ try { json = JSON.parse(raw || '{}'); } catch { bad('body is not valid JSON'); return; }
58
+ const parsed = bodySchema.safeParse(json);
59
+ if (!parsed.success) { bad(parsed.error.issues); return; }
60
+ const { epicId, validateSlug, rejected, accepted, rereview } = parsed.data;
61
+ /** @type {string} */
62
+ let cwd;
63
+ try {
64
+ cwd = resolveProjectRoot(parsed.data.cwd, { opsInternal: 'refuse' });
65
+ if (!fs.statSync(cwd).isDirectory()) throw new Error('not a directory');
66
+ } catch {
67
+ sendJson(res, 400, { ok: false, error: 'bad_cwd' });
68
+ return;
69
+ }
70
+ if (!EPIC_ID_RE.test(epicId) || !SLUG_RE.test(validateSlug) || validateSlug.includes('..')) {
71
+ bad('unsafe epicId or validateSlug');
72
+ return;
73
+ }
74
+ try {
75
+ const prior = readPlanReview(cwd, epicId, validateSlug);
76
+
77
+ if (rereview) {
78
+ let reason = null;
79
+ if (!prior || !Array.isArray(prior.reviews) || prior.reviews.length === 0) reason = 'no review on record for this plan';
80
+ else if (prior.release) reason = 'the plan is already released';
81
+ else if (!latestHasBlock(prior)) reason = 'the latest review has no block decision';
82
+ else if (prior.round !== 1) reason = `a re-review is allowed once per plan; the plan is at round ${prior.round}`;
83
+ else if (prior.rereviewRequested) reason = 're-review was already requested';
84
+ if (reason) { sendJson(res, 400, { ok: false, error: 'rereview_refused', reason }); return; }
85
+ const file = planReviewPath(cwd, epicId, validateSlug);
86
+ assertOpsWrite(file, 'scheduler');
87
+ await writeJsonAtomic(file, { ...prior, rereviewRequested: true });
88
+ sendJson(res, 200, { ok: true, rereviewRequested: true });
89
+ return;
90
+ }
91
+
92
+ const missing = rejected.findIndex((r) => !r.reason.trim());
93
+ if (missing !== -1) {
94
+ sendJson(res, 400, { ok: false, error: 'reason_required', reason: `rejected[${missing}] needs a non-empty one-line reason` });
95
+ return;
96
+ }
97
+ const out = await recordPlanRelease({
98
+ cwd, epicId, validateSlug, by: 'planner',
99
+ rejected: rejected.map((r) => ({ finding: r.finding, reason: r.reason.trim() })),
100
+ accepted,
101
+ });
102
+ if (out && out.alreadyReleased) { sendJson(res, 200, { ok: true, alreadyReleased: true }); return; }
103
+ sendJson(res, 200, { ok: true, released: true, accepted, rejected: rejected.length });
104
+ } catch (e) {
105
+ sendJson(res, 500, { ok: false, error: 'release_failed', details: e instanceof Error ? e.message : String(e) });
106
+ }
107
+ });
108
+ }
109
+
110
+ module.exports = { registerPlanReleaseRoute };