claude-code-session-manager 0.141.0 → 0.143.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 (223) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +76 -153
  3. package/bin/cli.cjs +11 -0
  4. package/dist/assets/AppSettings-BO4jDVGO.js +2 -0
  5. package/dist/assets/{History-DJMiuXyK.js → History-DTttbvPb.js} +1 -1
  6. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +3 -0
  7. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-B_D4Bg7L.js} +1 -1
  8. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-DPnDJKcr.js} +7 -7
  9. package/dist/assets/Scheduler-CNLjn90m.js +16 -0
  10. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  11. package/dist/assets/{Skills-C1v91GEO.js → Skills-cfV7sgk6.js} +5 -5
  12. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-DVXtEIVy.js} +1 -1
  13. package/dist/assets/Toggle-CYajnSdx.js +1 -0
  14. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-DJ4gGRuE.js} +1 -1
  15. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-D3MoHY2U.js} +1 -1
  16. package/dist/assets/index-CdTppjKR.js +3133 -0
  17. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  18. package/dist/index.html +2 -2
  19. package/dist-web/app.css +1 -1
  20. package/dist-web/app.js +496 -484
  21. package/package.json +6 -4
  22. package/plugins/AGENTS.md +4 -3
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  25. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  26. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  27. package/plugins/session-manager-dev/skills/develop/SKILL.md +58 -18
  28. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  29. package/scripts/README.md +2 -0
  30. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  31. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  32. package/scripts/scheduler-mcp-server.cjs +1032 -112
  33. package/src/main/adminRouteRegistry.cjs +69 -0
  34. package/src/main/agentLibrary.cjs +72 -4
  35. package/src/main/agentsIpc.cjs +3 -2
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/chatRunner.cjs +336 -23
  38. package/src/main/config.cjs +35 -1
  39. package/src/main/docEdit.cjs +4 -2
  40. package/src/main/health.cjs +129 -2
  41. package/src/main/index.cjs +110 -52
  42. package/src/main/ipcSchemas.cjs +172 -8
  43. package/src/main/lib/AGENTS.md +1 -1
  44. package/src/main/lib/chatBootRecovery.cjs +2 -0
  45. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  46. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  47. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  48. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  49. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  50. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  51. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  52. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  53. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  54. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  55. package/src/main/lib/demo-video-kit/cast.md +52 -0
  56. package/src/main/lib/demo-video-kit/character.cjs +778 -30
  57. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  58. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  59. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  60. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  61. package/src/main/lib/demo-video-kit/kind-tiktok.md +103 -0
  62. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  63. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  64. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  65. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  66. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  67. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  68. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  69. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  70. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  71. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  72. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  73. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  74. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  75. package/src/main/lib/epic/artifactRetention.cjs +356 -0
  76. package/src/main/lib/epic/artifactStore.cjs +435 -0
  77. package/src/main/lib/epic/delegationReadiness.cjs +83 -2
  78. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  79. package/src/main/lib/epic/epicEventLog.cjs +258 -0
  80. package/src/main/lib/epic/epicMint.cjs +43 -1
  81. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  82. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  83. package/src/main/lib/epic/epicPurge.cjs +347 -0
  84. package/src/main/lib/epic/epicReopen.cjs +5 -2
  85. package/src/main/lib/epic/epicSettle.cjs +4 -13
  86. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  87. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  88. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  89. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  90. package/src/main/lib/epic/epicValidationHook.cjs +94 -4
  91. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  92. package/src/main/lib/externalContract.cjs +48 -4
  93. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  94. package/src/main/lib/feedback-remote/crossProjectReply.cjs +478 -127
  95. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  96. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  97. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  98. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  99. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  100. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  101. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  102. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  103. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  104. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  105. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  106. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +32 -1
  107. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  108. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  109. package/src/main/lib/feedback-remote/pendingReplies.cjs +207 -0
  110. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +282 -14
  111. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  112. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  113. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  114. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  115. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  116. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  117. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  118. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  119. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  120. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  121. package/src/main/lib/git/gitWorktree.cjs +8 -0
  122. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  123. package/src/main/lib/git/worktreeDeps.cjs +182 -4
  124. package/src/main/lib/mcpToolCatalog.cjs +399 -29
  125. package/src/main/lib/opsOwnership.cjs +141 -28
  126. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  127. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  128. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  129. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  130. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  131. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  132. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  133. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +309 -0
  134. package/src/main/lib/phaseProjection.cjs +103 -0
  135. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  136. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  137. package/src/main/lib/prd/prdCreate.cjs +387 -228
  138. package/src/main/lib/prd/prdCriteria.cjs +228 -0
  139. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  140. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  141. package/src/main/lib/prd/prdSizing.cjs +3 -1
  142. package/src/main/lib/process/cleanEnv.cjs +52 -1
  143. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  144. package/src/main/lib/process/memoryScope.cjs +31 -3
  145. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  146. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  147. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  148. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  149. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  150. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  151. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  152. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  153. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  154. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  155. package/src/main/lib/promptSessionSchema.cjs +6 -0
  156. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  157. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  158. package/src/main/lib/scheduler/criteriaChecks.cjs +313 -0
  159. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  160. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  161. package/src/main/lib/scheduler/jobMemoryStats.cjs +324 -0
  162. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  163. package/src/main/lib/scheduler/planRecordHarvest.cjs +152 -54
  164. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +191 -0
  165. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  166. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  167. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  168. package/src/main/lib/scheduler/scheduleJobSchema.cjs +18 -0
  169. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  170. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  171. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -3
  172. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  173. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  174. package/src/main/lib/scheduler/slotsRoute.cjs +251 -0
  175. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  176. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  177. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +152 -11
  178. package/src/main/lib/tasks/memoryConsolidation.cjs +312 -0
  179. package/src/main/lib/tasks/mitigationReview.cjs +314 -0
  180. package/src/main/lib/tasks/taskAdminRoutes.cjs +390 -25
  181. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  182. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  183. package/src/main/lib/tasks/taskRun.cjs +186 -17
  184. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  185. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  186. package/src/main/lib/telemetry/auditEvents.cjs +204 -6
  187. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  188. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  189. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  190. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  191. package/src/main/lib/toolUseClassify.cjs +181 -0
  192. package/src/main/lib/util/atomicFs.cjs +2 -2
  193. package/src/main/lib/util/smfileRange.cjs +77 -0
  194. package/src/main/projectPages.cjs +3 -1
  195. package/src/main/promptSessionEvents.cjs +21 -1
  196. package/src/main/pty.cjs +77 -0
  197. package/src/main/queueOps.cjs +33 -14
  198. package/src/main/runVerify.cjs +74 -9
  199. package/src/main/scheduler/AGENTS.md +1 -0
  200. package/src/main/scheduler/budget.cjs +6 -5
  201. package/src/main/scheduler/prdParser.cjs +46 -13
  202. package/src/main/scheduler/reviewLadder.cjs +9 -25
  203. package/src/main/scheduler/utilizationHold.cjs +191 -0
  204. package/src/main/scheduler.cjs +1932 -213
  205. package/src/main/templates/PRD_AUTHORING.md +11 -3
  206. package/src/main/webRemote.cjs +463 -6
  207. package/src/preload/api.d.ts +576 -39
  208. package/src/preload/apiSurface.json +223 -7
  209. package/src/preload/index.cjs +48 -1
  210. package/src/seed/agents/architect.md +6 -1
  211. package/src/seed/agents/blender-artist.md +2 -1
  212. package/src/seed/agents/competitive-analyst.md +3 -1
  213. package/src/seed/agents/competitive-researcher.md +2 -1
  214. package/src/seed/agents/demo-video-builder.md +98 -87
  215. package/src/seed/agents/dev-lead.md +3 -3
  216. package/src/seed/agents/project-home-builder.md +9 -31
  217. package/src/seed/agents/validator.md +23 -23
  218. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  219. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  220. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  221. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  222. package/dist/assets/index-B2TQz3nd.js +0 -3121
  223. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,324 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * jobMemoryStats.cjs — recorded per-job memory peaks → per-agentType reservation
5
+ * and one shared spike buffer, so the memory gate can reserve what jobs really use
6
+ * instead of a flat 2,500 MB (≈p93 of 2,457 measured scopes: p50 670, p75 1,269,
7
+ * p90 1,994, p95 2,663, max 9,142 MB).
8
+ *
9
+ * Store: `<schedulerHome>/job-memory-peaks.jsonl`, one `{agentType, peakMb, at}`
10
+ * per line, trimmed to the newest MAX_SAMPLES, rewritten via util/atomicFs.cjs.
11
+ * Reads are cached CACHE_MS. Quantiles are nearest-rank. Pure Node, no Electron.
12
+ *
13
+ * The default instance's functions are the module exports; createJobMemoryStats()
14
+ * builds one with injected { fs, now, storePath, writeTextAtomicSync, writeTextAtomic } for tests
15
+ * (writeTextAtomicSync: recordPeak's write; writeTextAtomic: the backfill's async write).
16
+ */
17
+
18
+ const nodeFs = require('node:fs');
19
+ const path = require('node:path');
20
+ const atomicFs = require('../util/atomicFs.cjs');
21
+
22
+ const STORE_FILE = 'job-memory-peaks.jsonl';
23
+ const MAX_SAMPLES = 2000;
24
+ const RECENT_PER_TYPE = 200;
25
+ const MIN_SAMPLES = 30;
26
+ const CACHE_MS = 60_000;
27
+ const DEFAULT_RESERVATION_MB = 2500;
28
+ const DEFAULT_TYPICAL_MB = 1000;
29
+ const DEFAULT_SPIKE_BUFFER_MB = 1500;
30
+ const RESERVATION_CLAMP = [800, 4000];
31
+ const TYPICAL_CLAMP = [300, 2500];
32
+ const SPIKE_CLAMP = [500, 3000];
33
+ const DEFAULT_MAX_FILES = 2000;
34
+ const BACKFILL_BATCH = 50; // run-log files read concurrently per batch
35
+ const PEAK_LINE_RE = /\[scheduler\] memory scope (\S+): peak=(\d+)MB/g;
36
+
37
+ function clamp(v, [lo, hi]) { return Math.min(hi, Math.max(lo, v)); }
38
+
39
+ /** Nearest-rank quantile: the ceil(q*n)-th smallest value (1-based). `values` need not be sorted. */
40
+ function quantile(values, q) {
41
+ if (!values.length) return NaN;
42
+ const sorted = [...values].sort((a, b) => a - b);
43
+ const rank = Math.max(1, Math.ceil(q * sorted.length));
44
+ return sorted[Math.min(sorted.length, rank) - 1];
45
+ }
46
+
47
+ function normalizeSample(s) {
48
+ if (!s || typeof s !== 'object') return null;
49
+ const peakMb = Number(s.peakMb);
50
+ if (!Number.isFinite(peakMb) || peakMb < 0) return null;
51
+ const agentType = typeof s.agentType === 'string' && s.agentType ? s.agentType : 'unknown';
52
+ const at = Number.isFinite(Number(s.at)) ? Number(s.at) : 0;
53
+ const out = { agentType, peakMb: Math.round(peakMb), at };
54
+ // Optional provenance: the run folder + scope unit, so the boot backfill never re-adds a peak.
55
+ if (typeof s.runId === 'string' && s.runId) out.runId = s.runId;
56
+ if (typeof s.unit === 'string' && s.unit) out.unit = s.unit;
57
+ return out;
58
+ }
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
+
70
+ function defaultStorePath() {
71
+ return path.join(require('./schedulerPaths.cjs').schedulerHome(), STORE_FILE);
72
+ }
73
+
74
+ function createJobMemoryStats(deps = {}) {
75
+ const fs = deps.fs || nodeFs;
76
+ const now = deps.now || Date.now;
77
+ const writeText = deps.writeTextAtomicSync || atomicFs.writeTextAtomicSync;
78
+ const writeTextAsync = deps.writeTextAtomic || atomicFs.writeTextAtomic;
79
+ const resolveStorePath = () => (typeof deps.storePath === 'function' ? deps.storePath() : deps.storePath) || defaultStorePath();
80
+ let cache = null; // { at, file, samples }
81
+ let liveDuringWrite = null; // live recordPeak samples landing while the backfill's async write is in flight
82
+
83
+ function parseSamples(text) {
84
+ const out = [];
85
+ for (const line of String(text).split('\n')) {
86
+ if (!line.trim()) continue;
87
+ try {
88
+ const s = normalizeSample(JSON.parse(line));
89
+ if (s) out.push(s);
90
+ } catch { /* skip a torn line */ }
91
+ }
92
+ return out;
93
+ }
94
+
95
+ function readSamplesUncached(file) {
96
+ let text;
97
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
98
+ return parseSamples(text);
99
+ }
100
+
101
+ async function readSamplesAsync(file) {
102
+ let text;
103
+ try { text = await fs.promises.readFile(file, 'utf8'); } catch { return []; }
104
+ return parseSamples(text);
105
+ }
106
+
107
+ const serialize = (kept) => kept.map((x) => JSON.stringify(x)).join('\n') + (kept.length ? '\n' : '');
108
+
109
+ /** All stored samples, oldest first (file order). Cached CACHE_MS per store path. */
110
+ function loadSamples() {
111
+ const file = resolveStorePath();
112
+ const t = now();
113
+ if (cache && cache.file === file && t - cache.at < CACHE_MS) return cache.samples;
114
+ const samples = readSamplesUncached(file);
115
+ cache = { at: t, file, samples };
116
+ return samples;
117
+ }
118
+
119
+ function writeSamples(file, samples) {
120
+ const kept = samples.slice(-MAX_SAMPLES);
121
+ writeText(file, serialize(kept));
122
+ cache = { at: now(), file, samples: kept };
123
+ return kept;
124
+ }
125
+
126
+ async function writeSamplesAsync(file, samples) {
127
+ const kept = samples.slice(-MAX_SAMPLES);
128
+ await writeTextAsync(file, serialize(kept));
129
+ cache = { at: now(), file, samples: kept };
130
+ return kept;
131
+ }
132
+
133
+ function appendSamples(newSamples) {
134
+ const file = resolveStorePath();
135
+ const existing = readSamplesUncached(file);
136
+ return writeSamples(file, [...existing, ...newSamples]);
137
+ }
138
+
139
+ /** Records one job's peak. Returns the stored sample, or null when the input is unusable. */
140
+ function recordPeak({ agentType, peakMb, at, runId, unit } = {}) {
141
+ const s = normalizeSample({ agentType, peakMb, at: at === undefined ? now() : at, runId, unit });
142
+ if (!s) return null;
143
+ appendSamples([s]);
144
+ if (liveDuringWrite) liveDuringWrite.push(s);
145
+ return s;
146
+ }
147
+
148
+ /** Peaks to take quantiles of: agentType's newest 200 when it has ≥30, else all when ≥30, else null. */
149
+ function basisFor(agentType) {
150
+ const all = loadSamples();
151
+ const own = all.filter((s) => s.agentType === agentType);
152
+ if (own.length >= MIN_SAMPLES) return own.slice(-RECENT_PER_TYPE).map((s) => s.peakMb);
153
+ if (all.length >= MIN_SAMPLES) return all.map((s) => s.peakMb);
154
+ return null;
155
+ }
156
+
157
+ /** p75 peak for agentType (MB), clamped 800-4000; 2500 with too few samples. */
158
+ function reservationMb(agentType) {
159
+ const basis = basisFor(agentType);
160
+ if (!basis) return DEFAULT_RESERVATION_MB;
161
+ return clamp(quantile(basis, 0.75), RESERVATION_CLAMP);
162
+ }
163
+
164
+ /** p50 peak for agentType (MB), clamped 300-2500; 1000 with too few samples. */
165
+ function typicalPeakMb(agentType) {
166
+ const basis = basisFor(agentType);
167
+ if (!basis) return DEFAULT_TYPICAL_MB;
168
+ return clamp(quantile(basis, 0.5), TYPICAL_CLAMP);
169
+ }
170
+
171
+ /** p95 − p75 of all samples (one job at its p95 while the rest sit near p75), clamped 500-3000; 1500 with too few. */
172
+ function spikeBufferMb() {
173
+ const all = loadSamples().map((s) => s.peakMb);
174
+ if (all.length < MIN_SAMPLES) return DEFAULT_SPIKE_BUFFER_MB;
175
+ return clamp(quantile(all, 0.95) - quantile(all, 0.75), SPIKE_CLAMP);
176
+ }
177
+
178
+ /** True once the store holds ≥ MIN_SAMPLES peaks, i.e. the quantiles above are measured, not fallbacks. */
179
+ function isMeasured() {
180
+ return loadSamples().length >= MIN_SAMPLES;
181
+ }
182
+
183
+ /** Directory entries under dir (async), or [] when unreadable. */
184
+ async function listDir(dir) {
185
+ try { return await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return []; }
186
+ }
187
+
188
+ /** Yields the event loop once (between read batches). */
189
+ const yieldTurn = () => new Promise((resolve) => setImmediate(resolve));
190
+
191
+ /**
192
+ * Seeds the store from run logs' 'memory scope <unit>: peak=<N>MB' lines
193
+ * (agentType 'unknown', at = log mtime) while it holds fewer than MIN_SAMPLES.
194
+ * `runsDir` is the scheduler runs folder (<runId>/<slug>.log). Only the newest
195
+ * maxFiles × 2 run folders (by name — names are timestamps) are listed, whether
196
+ * or not they hold logs, so a sparse runs folder never costs a listing per run;
197
+ * among them the walk stops once maxFiles logs are picked, and only picked logs
198
+ * are read and stat'd. A peak is deduped by run folder + scope unit (a stored
199
+ * sample without a runId — a peak recorded before live peaks carried one — can
200
+ * only match by unit).
201
+ *
202
+ * I/O: the store reads, run-log listings/reads/stats and the final store write
203
+ * (util/atomicFs writeTextAtomic) are all fs.promises, run-log reads in batches
204
+ * of at most BACKFILL_BATCH with an event-loop yield between batches. Nothing
205
+ * runs synchronously except one case: when a live recordPeak lands while that
206
+ * async write is in flight (our rename may have replaced its line), the store
207
+ * is re-read and the missing live peak re-appended with the same synchronous
208
+ * writer recordPeak itself uses. Never rejects. Resolves to the number added.
209
+ */
210
+ async function backfillFromRunLogs(runsDir, { maxFiles = DEFAULT_MAX_FILES } = {}) {
211
+ try {
212
+ if (typeof runsDir !== 'string' || !runsDir) return 0;
213
+ const file = resolveStorePath();
214
+ const existing = await readSamplesAsync(file);
215
+ if (existing.length >= MIN_SAMPLES) return 0;
216
+ const budget = Math.max(0, Math.floor(Number(maxFiles) || 0));
217
+ if (!budget) return 0;
218
+ const keyOf = (runId, unit) => `${runId}\0${unit}`;
219
+ const seen = new Set();
220
+ const legacyUnits = new Set(); // stored peaks with no run folder
221
+ const noteStored = (samples) => {
222
+ for (const x of samples) {
223
+ if (!x.unit) continue;
224
+ if (x.runId) seen.add(keyOf(x.runId, x.unit));
225
+ else legacyUnits.add(x.unit);
226
+ }
227
+ };
228
+ noteStored(existing);
229
+ const isStored = (runId, unit) => seen.has(keyOf(runId, unit)) || legacyUnits.has(unit);
230
+ const runIds = (await listDir(runsDir)).filter((e) => e.isDirectory()).map((e) => e.name)
231
+ .sort().reverse().slice(0, budget * 2);
232
+ // Pick the newest `budget` logs: [{ runId, p }], newest run first.
233
+ const picked = [];
234
+ for (const runId of runIds) {
235
+ if (picked.length >= budget) break;
236
+ const dir = path.join(runsDir, runId);
237
+ const logs = (await listDir(dir)).filter((e) => e.isFile() && e.name.endsWith('.log')).map((e) => e.name).sort();
238
+ for (const name of logs) {
239
+ if (picked.length >= budget) break;
240
+ picked.push({ runId, p: path.join(dir, name) });
241
+ }
242
+ }
243
+ const readOne = async ({ runId, p }) => {
244
+ let text;
245
+ try { text = await fs.promises.readFile(p, 'utf8'); } catch { return null; }
246
+ let mtimeMs = 0;
247
+ try { mtimeMs = (await fs.promises.stat(p)).mtimeMs; } catch { /* keep 0 */ }
248
+ return { runId, text: String(text), mtimeMs };
249
+ };
250
+ const perRun = new Map(); // runId → samples, insertion order = newest run first
251
+ for (let i = 0; i < picked.length; i += BACKFILL_BATCH) {
252
+ if (i > 0) await yieldTurn();
253
+ const results = await Promise.all(picked.slice(i, i + BACKFILL_BATCH).map(readOne));
254
+ for (const r of results) {
255
+ if (!r) continue;
256
+ if (!perRun.has(r.runId)) perRun.set(r.runId, []);
257
+ const found = perRun.get(r.runId);
258
+ for (const m of r.text.matchAll(PEAK_LINE_RE)) {
259
+ const unit = m[1];
260
+ if (isStored(r.runId, unit)) continue;
261
+ seen.add(keyOf(r.runId, unit));
262
+ found.push({ agentType: 'unknown', peakMb: Number(m[2]), at: Math.round(r.mtimeMs), runId: r.runId, unit });
263
+ }
264
+ }
265
+ }
266
+ // Re-read the store: a live recordPeak may have landed while the logs were read.
267
+ liveDuringWrite = [];
268
+ let samples;
269
+ try {
270
+ const current = await readSamplesAsync(file);
271
+ seen.clear();
272
+ noteStored(current);
273
+ samples = [...perRun.values()].reverse().flat() // oldest first, like the live store
274
+ .filter((x) => !isStored(x.runId, x.unit));
275
+ if (!samples.length) return 0;
276
+ await writeSamplesAsync(file, [...current, ...samples]);
277
+ } finally {
278
+ const landed = liveDuringWrite;
279
+ liveDuringWrite = null;
280
+ if (landed.length && samples && samples.length) {
281
+ const stored = readSamplesUncached(file);
282
+ const have = new Set(stored.map(sampleKey));
283
+ const missing = landed.filter((x) => !have.has(sampleKey(x)));
284
+ if (missing.length) writeSamples(file, [...stored, ...missing]);
285
+ }
286
+ }
287
+ return Math.min(samples.length, MAX_SAMPLES);
288
+ } catch {
289
+ return 0;
290
+ }
291
+ }
292
+
293
+ return {
294
+ recordPeak,
295
+ reservationMb,
296
+ typicalPeakMb,
297
+ spikeBufferMb,
298
+ isMeasured,
299
+ backfillFromRunLogs,
300
+ loadSamples,
301
+ _resetCache() { cache = null; },
302
+ };
303
+ }
304
+
305
+ const defaultInstance = createJobMemoryStats();
306
+
307
+ module.exports = {
308
+ recordPeak: defaultInstance.recordPeak,
309
+ reservationMb: defaultInstance.reservationMb,
310
+ typicalPeakMb: defaultInstance.typicalPeakMb,
311
+ spikeBufferMb: defaultInstance.spikeBufferMb,
312
+ isMeasured: defaultInstance.isMeasured,
313
+ backfillFromRunLogs: defaultInstance.backfillFromRunLogs,
314
+ createJobMemoryStats,
315
+ quantile,
316
+ sampleKey,
317
+ STORE_FILE,
318
+ MAX_SAMPLES,
319
+ RECENT_PER_TYPE,
320
+ MIN_SAMPLES,
321
+ CACHE_MS,
322
+ DEFAULT_RESERVATION_MB,
323
+ BACKFILL_BATCH,
324
+ };
@@ -3,8 +3,8 @@
3
3
  /**
4
4
  * loadGate.cjs — CPU-load launch gate for the scheduler (PRD 1085).
5
5
  *
6
- * The scheduler already gates launches on free memory (scheduler.cjs's
7
- * memoryLimitedBatchSize) and on a static per-project cap
6
+ * The scheduler already gates launches on free memory (measuredMemoryGate
7
+ * below, PRD 4019) and on a static per-project cap
8
8
  * (schedulerConfig.projectJobCap). Neither sees CPU. Observed 2026-09-01 on
9
9
  * starry-night-ships: 4 concurrent executors each running a Godot test
10
10
  * battery under its own Xvfb, loadavg 12.95 on 14 cores. Under that
@@ -49,7 +49,9 @@ const SATURATED_BUSY = 0.85;
49
49
 
50
50
  // The busy fraction every band above judges is NET of this app's own process
51
51
  // tree (PRD 3495; cpuSample.cjs readOwnProcessTicks) — the app must not gate on
52
- // its own renderer/main load. Raw and own shares are still reported. A sampler
52
+ // its own renderer/main load — and of every process at nice 19 (PRD 4021): those
53
+ // yield to jobs, so they are not load to defend. Raw, own and idle-priority
54
+ // shares are still reported. A sampler
53
55
  // without a net figure (non-Linux, legacy injection) falls back to raw.
54
56
  function busyOf(sample) {
55
57
  if (!sample) return null;
@@ -186,6 +188,7 @@ function createLoadGate({
186
188
  cpuBusyRaw: null,
187
189
  cpuBusyNet: null,
188
190
  cpuOwnBusy: null,
191
+ cpuIdleNice: null,
189
192
  cpuIowait: null,
190
193
  cpuWindowMs: null,
191
194
  standDown: false,
@@ -244,6 +247,7 @@ function createLoadGate({
244
247
  cpuBusyRaw: sample ? round3(sample.busyFraction) : null,
245
248
  cpuBusyNet: round3(busy),
246
249
  cpuOwnBusy: sample && Number.isFinite(sample.ownFraction) ? round3(sample.ownFraction) : null,
250
+ cpuIdleNice: sample && Number.isFinite(sample.idleNiceShare) ? round3(sample.idleNiceShare) : null,
247
251
  cpuIowait: sample ? Number(sample.iowaitFraction.toFixed(3)) : null,
248
252
  cpuWindowMs: sample ? sample.windowMs : null,
249
253
  standDown,
@@ -282,4 +286,78 @@ function createLoadGate({
282
286
  return { evaluate, observe, snapshot, endHold, isSaturated };
283
287
  }
284
288
 
285
- module.exports = { isLoadGated, createLoadGate, topCpuConsumers, AUDIT_INTERVAL_MS, MOSTLY_IDLE_BUSY, SATURATED_BUSY };
289
+ /**
290
+ * Human-readable explanation for a `reason: 'load-deferred'` tick, surfaced
291
+ * to the renderer via lastTick.detail (scheduler.cjs). Names the gate, the
292
+ * measured ratio, the threshold, the net CPU sample, the idle-priority (nice 19)
293
+ * share left out of it when above 0, and how long this gate itself has held a
294
+ * batch that slots and memory admitted (heldMs). Pure.
295
+ */
296
+ function formatLoadGateDetail(load) {
297
+ const heldMinutes = Math.round(load.heldMs / 60_000);
298
+ let cpu = load.cpuBusy == null
299
+ ? 'no CPU sample yet'
300
+ : `CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`;
301
+ if (load.cpuBusy != null && load.cpuIdleNice > 0) {
302
+ cpu += ` (excl. ${Math.round(load.cpuIdleNice * 100)}% at nice 19)`;
303
+ }
304
+ return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, ${cpu}, held ${heldMinutes}m with slots and memory free`;
305
+ }
306
+
307
+ /**
308
+ * measuredMemoryGate({ jobBudgetMb, running, batch, stats }) → decision
309
+ *
310
+ * The memory gate's math (PRD 4019). `jobBudgetMb` is MemAvailable minus the host
311
+ * reserve (scheduler.cjs availableForJobs). Admitting the first k jobs of `batch`
312
+ * needs
313
+ * spikeBufferMb() (one, shared)
314
+ * + Σ running max(0, typicalPeakMb(agentType) − rssMb) (growth still to come)
315
+ * + Σ first k batch jobs reservationMb(agentType) (p75; RSS 0 at launch)
316
+ * Running jobs' resident memory is already out of MemAvailable, so each keeps only
317
+ * its typical growth; its RSS credit is capped at that typical peak.
318
+ *
319
+ * With too few samples (`stats.isMeasured()` false) the typical peak IS the
320
+ * reservation (2,500 MB fallback) and there is no spike buffer — exactly the old
321
+ * flat MIN_FREE_MB_PER_JOB rule. Infinity budget (non-Linux) admits everything.
322
+ *
323
+ * running: [{ agentType, rssMb }]; batch: [{ agentType }]; stats: jobMemoryStats.
324
+ * Returns { allowed, measured, needMb, reservationMb, spikeBufferMb, growthMb,
325
+ * consumedMb } where needMb/reservationMb are for the first job NOT admitted
326
+ * (or the last admitted when the whole batch fits). Pure.
327
+ */
328
+ function measuredMemoryGate({ jobBudgetMb, running = [], batch = [], stats }) {
329
+ const typeOf = (j) => (j && typeof j.agentType === 'string' && j.agentType) || 'dev-lead';
330
+ const measured = Boolean(stats.isMeasured && stats.isMeasured());
331
+ const spikeBufferMb = measured ? stats.spikeBufferMb() : 0;
332
+ let growthMb = 0;
333
+ let consumedMb = 0;
334
+ for (const r of running) {
335
+ const t = typeOf(r);
336
+ const typical = measured ? stats.typicalPeakMb(t) : stats.reservationMb(t);
337
+ const rss = Math.max(0, Number(r && r.rssMb) || 0);
338
+ const credit = Math.min(rss, typical);
339
+ consumedMb += credit;
340
+ growthMb += typical - credit;
341
+ }
342
+ let needMb = spikeBufferMb + growthMb;
343
+ let reservationMb = 0;
344
+ let allowed = 0;
345
+ for (const j of batch) {
346
+ reservationMb = stats.reservationMb(typeOf(j));
347
+ const next = needMb + reservationMb;
348
+ if (jobBudgetMb !== Infinity && !(jobBudgetMb >= next)) { needMb = next; break; }
349
+ needMb = next;
350
+ allowed++;
351
+ }
352
+ return { allowed, measured, needMb, reservationMb, spikeBufferMb, growthMb, consumedMb };
353
+ }
354
+
355
+ /** Human-readable breakdown of a memory-gate decision for the tick detail + heartbeat. Pure. */
356
+ function formatMemoryGateDetail({ availableMb, threshold, reservedHostMb, gate }) {
357
+ const basis = gate.measured ? 'measured' : 'fallback, too few samples';
358
+ return `memory gate: ${availableMb} MB free, need ${threshold} MB = host ${reservedHostMb}` +
359
+ ` + new job ${gate.reservationMb} + spike buffer ${gate.spikeBufferMb}` +
360
+ ` + running growth ${gate.growthMb} (consumed=${gate.consumedMb} MB credited; ${basis})`;
361
+ }
362
+
363
+ module.exports = { measuredMemoryGate, formatMemoryGateDetail, formatLoadGateDetail, isLoadGated, createLoadGate, topCpuConsumers, AUDIT_INTERVAL_MS, MOSTLY_IDLE_BUSY, SATURATED_BUSY };
@@ -12,7 +12,7 @@
12
12
  const fs = require('node:fs');
13
13
  const path = require('node:path');
14
14
  const { OPS_ROOT_DIR, opsPath, checkOpsWrite, assertOpsWrite } = require('../opsOwnership.cjs');
15
- const { writeTextAtomicSync } = require('../util/atomicFs.cjs');
15
+ const { writeTextAtomicSync, writeJsonAtomic } = require('../util/atomicFs.cjs');
16
16
 
17
17
  const NAMESPACE = 'plan-records';
18
18
  const WRITER = 'scheduler';
@@ -24,16 +24,86 @@ 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
+
27
29
  /**
28
- * harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl })
30
+ * parseDeclaredPath(p) → { folder, name } | { reason }
31
+ * A declared record must be exactly
32
+ * `session-manager-operations/plan-records/<epic-folder>/<name>.md` (posix,
33
+ * repo-relative), with no `..` segment and no NUL byte.
34
+ */
35
+ function parseDeclaredPath(p) {
36
+ if (typeof p !== 'string' || !p) return { reason: 'declared path is not a string' };
37
+ if (p.includes('\0')) return { reason: 'declared path contains a NUL byte' };
38
+ const posix = p.replace(/\\/g, '/');
39
+ if (posix.split('/').includes('..')) return { reason: 'declared path contains ..' };
40
+ if (path.posix.isAbsolute(posix)) return { reason: 'declared path is absolute' };
41
+ const norm = path.posix.normalize(posix);
42
+ if (!norm.startsWith(DECLARED_PREFIX)) return { reason: 'declared path is not under plan-records/' };
43
+ const parts = norm.slice(DECLARED_PREFIX.length).split('/');
44
+ if (parts.length !== 2) return { reason: 'declared path must be plan-records/<epic-folder>/<name>.md' };
45
+ const [folder, name] = parts;
46
+ if (!EPIC_ID_RE.test(folder)) return { reason: 'declared epic folder not allowed' };
47
+ if (!NAME_RE.test(name)) return { reason: 'name not allowed' };
48
+ return { folder, name };
49
+ }
50
+
51
+ /**
52
+ * harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths, fsImpl })
29
53
  * → { copied: string[], skipped: { path, reason }[] }
30
- * `copied` holds destination absolute paths.
54
+ * Copies every record in the job's own `plan-records/<epicId>/` folder, plus
55
+ * each well-formed `declaredPaths` entry (the PRD's frontmatter
56
+ * artifactPaths), whose folder may be a different Epic's. `copied` holds
57
+ * destination absolute paths.
31
58
  */
32
- function harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl = fs } = {}) {
59
+ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths = [], fsImpl = fs } = {}) {
33
60
  /** @type {string[]} */
34
61
  const copied = [];
35
62
  /** @type {{ path: string, reason: string }[]} */
36
63
  const skipped = [];
64
+ /** @type {Set<string>} source paths already handled */
65
+ const seen = new Set();
66
+
67
+ /**
68
+ * Copy one record `src` to `plan-records/<folder>/<name>` in the main
69
+ * checkout with every safety check. Returns false when `missingReason` is
70
+ * set and the source does not exist (reported with that reason).
71
+ * @param {string} src @param {string} folder @param {string} name
72
+ * @param {string} [missingReason]
73
+ */
74
+ function copyOne(src, folder, name, missingReason) {
75
+ seen.add(src);
76
+ try {
77
+ if (!NAME_RE.test(name)) { skipped.push({ path: src, reason: 'name not allowed' }); return; }
78
+ let st;
79
+ try {
80
+ st = fsImpl.lstatSync(src);
81
+ } catch (e) {
82
+ if (missingReason && e && e.code === 'ENOENT') { skipped.push({ path: src, reason: missingReason }); return; }
83
+ throw e;
84
+ }
85
+ if (st.isSymbolicLink()) { skipped.push({ path: src, reason: 'symlink' }); return; }
86
+ if (st.isDirectory()) { skipped.push({ path: src, reason: 'directory' }); return; }
87
+ if (!st.isFile()) { skipped.push({ path: src, reason: 'not a regular file' }); return; }
88
+ if (st.size > MAX_BYTES) { skipped.push({ path: src, reason: `oversize (${st.size} > ${MAX_BYTES} bytes)` }); return; }
89
+
90
+ const destDir = path.resolve(opsPath(projectRoot, NAMESPACE, folder));
91
+ const dest = path.resolve(opsPath(projectRoot, NAMESPACE, folder, name));
92
+ if (path.dirname(dest) !== destDir) { skipped.push({ path: src, reason: 'destination escapes plan-records folder' }); return; }
93
+ if (dest === src) return;
94
+ const verdict = checkOpsWrite(dest, WRITER);
95
+ if (!verdict.ok) { skipped.push({ path: src, reason: `write refused: ${verdict.error}` }); return; }
96
+ assertOpsWrite(dest, WRITER);
97
+
98
+ const text = fsImpl.readFileSync(src, 'utf8');
99
+ if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) { skipped.push({ path: src, reason: 'oversize after read' }); return; }
100
+ writeTextAtomicSync(dest, text);
101
+ copied.push(dest);
102
+ } catch (e) {
103
+ skipped.push({ path: src, reason: `copy failed: ${errMsg(e)}` });
104
+ }
105
+ }
106
+
37
107
  try {
38
108
  if (typeof epicId !== 'string' || !EPIC_ID_RE.test(epicId)) {
39
109
  skipped.push({ path: String(epicId), reason: 'unsafe epicId' });
@@ -45,59 +115,57 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl = fs } =
45
115
  return { copied, skipped };
46
116
  }
47
117
  if (path.resolve(worktreeDir) === path.resolve(projectRoot)) return { copied, skipped };
118
+ const wtRoot = path.resolve(worktreeDir);
48
119
 
49
- const srcDir = path.join(path.resolve(worktreeDir), OPS_ROOT_DIR, NAMESPACE, epicId);
50
- let destDir;
51
- 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 };
58
-
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
- }
69
-
70
- let names;
71
- try {
72
- names = fsImpl.readdirSync(srcDir).map(String).sort();
73
- } catch (e) {
74
- skipped.push({ path: srcDir, reason: `cannot list source: ${errMsg(e)}` });
75
- return { copied, skipped };
76
- }
77
-
78
- for (const name of names) {
79
- const src = path.join(srcDir, name);
120
+ // Pass 1: everything in the job's own plan-records/<epicId>/ folder.
121
+ folderPass: {
122
+ const srcDir = path.join(wtRoot, OPS_ROOT_DIR, NAMESPACE, epicId);
123
+ let destDir;
80
124
  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);
125
+ destDir = path.resolve(opsPath(projectRoot, NAMESPACE, epicId));
126
+ } catch (e) {
127
+ skipped.push({ path: srcDir, reason: `destination refused: ${errMsg(e)}` });
128
+ break folderPass;
129
+ }
130
+ if (destDir === srcDir) break folderPass;
131
+ let srcStat;
132
+ try {
133
+ srcStat = fsImpl.lstatSync(srcDir);
134
+ } catch {
135
+ break folderPass; // no records written by this job in its own folder
136
+ }
137
+ if (!srcStat.isDirectory()) {
138
+ skipped.push({ path: srcDir, reason: 'source is not a directory' });
139
+ break folderPass;
140
+ }
141
+ let names;
142
+ try {
143
+ names = fsImpl.readdirSync(srcDir).map(String).sort();
98
144
  } catch (e) {
99
- skipped.push({ path: src, reason: `copy failed: ${errMsg(e)}` });
145
+ skipped.push({ path: srcDir, reason: `cannot list source: ${errMsg(e)}` });
146
+ break folderPass;
147
+ }
148
+ for (const name of names) copyOne(path.join(srcDir, name), epicId, name);
149
+ }
150
+
151
+ // Pass 2: records the PRD declared in frontmatter artifactPaths.
152
+ const declared = Array.isArray(declaredPaths) ? declaredPaths : [];
153
+ for (const p of declared) {
154
+ const parsed = parseDeclaredPath(p);
155
+ if (!('folder' in parsed)) { skipped.push({ path: String(p), reason: parsed.reason }); continue; }
156
+ const src = path.join(wtRoot, OPS_ROOT_DIR, NAMESPACE, parsed.folder, parsed.name);
157
+ if (seen.has(src)) continue;
158
+ // Pass 1 refuses a symlinked/non-directory own folder; hold every
159
+ // declared folder to the same rule so a declaration cannot bypass it.
160
+ const folderDir = path.dirname(src);
161
+ let folderStat = null;
162
+ try { folderStat = fsImpl.lstatSync(folderDir); } catch { /* missing: copyOne reports */ }
163
+ if (folderStat && (folderStat.isSymbolicLink() || !folderStat.isDirectory())) {
164
+ seen.add(src);
165
+ skipped.push({ path: src, reason: 'declared epic folder is not a directory' });
166
+ continue;
100
167
  }
168
+ copyOne(src, parsed.folder, parsed.name, 'declared plan record not found in worktree');
101
169
  }
102
170
  } catch (e) {
103
171
  skipped.push({ path: String(worktreeDir), reason: `harvest failed: ${errMsg(e)}` });
@@ -105,4 +173,34 @@ function harvestPlanRecords({ worktreeDir, projectRoot, epicId, fsImpl = fs } =
105
173
  return { copied, skipped };
106
174
  }
107
175
 
108
- module.exports = { harvestPlanRecords, MAX_BYTES, NAME_RE, EPIC_ID_RE };
176
+ /**
177
+ * saveValidatorVerdicts({ cwd, epicId, validateSlug, record, write, appendEvent })
178
+ * → Promise<string> (the written path)
179
+ * Writes `plan-records/<epicId>/<validateSlug>.verdicts.json` as the namespace
180
+ * owner, then appends one `validator.verdict` { validateSlug, verdicts:
181
+ * [{ prd, verdict }] } event to the Epic's event log. A write failure rejects
182
+ * (the caller logs it); an event-log append failure is logged, never thrown.
183
+ */
184
+ async function saveValidatorVerdicts({
185
+ cwd, epicId, validateSlug, record, write = writeJsonAtomic, appendEvent = null,
186
+ } = {}) {
187
+ const file = opsPath(cwd, NAMESPACE, epicId, `${validateSlug}.verdicts.json`);
188
+ assertOpsWrite(file, WRITER);
189
+ await write(file, record);
190
+ try {
191
+ const append = appendEvent || require('../epic/epicEventLog.cjs').appendEpicEvent;
192
+ const rows = Array.isArray(record && record.verdicts) ? record.verdicts : [];
193
+ await append(cwd, epicId, {
194
+ kind: 'validator.verdict',
195
+ validateSlug,
196
+ verdicts: rows
197
+ .filter((v) => v && typeof v === 'object')
198
+ .map((v) => ({ prd: String(v.prd ?? ''), verdict: String(v.verdict ?? '') })),
199
+ });
200
+ } catch (e) {
201
+ console.error('[planRecordHarvest] validator.verdict event append failed', epicId, validateSlug, errMsg(e));
202
+ }
203
+ return file;
204
+ }
205
+
206
+ module.exports = { harvestPlanRecords, saveValidatorVerdicts, MAX_BYTES, NAME_RE, EPIC_ID_RE };