claude-code-session-manager 0.141.0 → 0.142.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 (200) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History-DJMiuXyK.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-Bf1Cf8UL.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BWPpypf9.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Ba4TkX2C.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-C1v91GEO.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-BrcWVpiW.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-qivnDV6K.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-CMCPTKqC.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +52 -18
  25. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  26. package/scripts/README.md +1 -0
  27. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  28. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  29. package/scripts/scheduler-mcp-server.cjs +732 -110
  30. package/src/main/adminRouteRegistry.cjs +59 -0
  31. package/src/main/agentLibrary.cjs +72 -4
  32. package/src/main/agentsIpc.cjs +3 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/chatRunner.cjs +231 -16
  35. package/src/main/config.cjs +30 -0
  36. package/src/main/docEdit.cjs +4 -2
  37. package/src/main/health.cjs +91 -0
  38. package/src/main/index.cjs +98 -48
  39. package/src/main/ipcSchemas.cjs +161 -8
  40. package/src/main/lib/AGENTS.md +1 -1
  41. package/src/main/lib/chatBootRecovery.cjs +2 -0
  42. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  43. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  44. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  45. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  46. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  47. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  48. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  49. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  50. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  51. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  52. package/src/main/lib/demo-video-kit/cast.md +43 -0
  53. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  54. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  55. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  56. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  57. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  58. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  59. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  60. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  61. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  62. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  63. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  64. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  65. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  66. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  67. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  68. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  69. package/src/main/lib/epic/artifactStore.cjs +392 -0
  70. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  71. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  72. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  73. package/src/main/lib/epic/epicMint.cjs +43 -1
  74. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  75. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  76. package/src/main/lib/epic/epicPurge.cjs +347 -0
  77. package/src/main/lib/epic/epicReopen.cjs +5 -2
  78. package/src/main/lib/epic/epicSettle.cjs +4 -13
  79. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  80. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  81. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  82. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  83. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  84. package/src/main/lib/externalContract.cjs +37 -4
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  90. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  91. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  92. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  93. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  94. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  95. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  96. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  97. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  98. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  99. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  100. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  101. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  102. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  103. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  104. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  105. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  106. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  107. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  111. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  112. package/src/main/lib/mcpToolCatalog.cjs +304 -28
  113. package/src/main/lib/opsOwnership.cjs +29 -1
  114. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  115. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  116. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  117. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  118. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  119. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  120. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  121. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  122. package/src/main/lib/phaseProjection.cjs +103 -0
  123. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  124. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  125. package/src/main/lib/prd/prdCreate.cjs +41 -5
  126. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  127. package/src/main/lib/prd/prdFrontmatter.cjs +43 -3
  128. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  129. package/src/main/lib/prd/prdSizing.cjs +3 -1
  130. package/src/main/lib/process/cleanEnv.cjs +52 -1
  131. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  132. package/src/main/lib/process/memoryScope.cjs +31 -3
  133. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  134. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  135. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  136. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  137. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  138. package/src/main/lib/promptSessionSchema.cjs +6 -0
  139. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  140. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  141. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  142. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  143. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  144. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  145. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  146. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  147. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  148. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  149. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  150. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  151. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  152. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  153. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  154. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  155. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  156. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  157. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  158. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  159. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  160. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  161. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  162. package/src/main/lib/tasks/taskRun.cjs +186 -17
  163. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  164. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  165. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  166. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  167. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  168. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  169. package/src/main/lib/toolUseClassify.cjs +181 -0
  170. package/src/main/lib/util/smfileRange.cjs +77 -0
  171. package/src/main/projectPages.cjs +3 -1
  172. package/src/main/promptSessionEvents.cjs +5 -0
  173. package/src/main/pty.cjs +68 -0
  174. package/src/main/queueOps.cjs +32 -13
  175. package/src/main/runVerify.cjs +74 -9
  176. package/src/main/scheduler/AGENTS.md +1 -0
  177. package/src/main/scheduler/budget.cjs +6 -5
  178. package/src/main/scheduler/prdParser.cjs +46 -13
  179. package/src/main/scheduler/reviewLadder.cjs +9 -25
  180. package/src/main/scheduler/utilizationHold.cjs +101 -0
  181. package/src/main/scheduler.cjs +1414 -189
  182. package/src/main/templates/PRD_AUTHORING.md +5 -2
  183. package/src/main/webRemote.cjs +463 -6
  184. package/src/preload/api.d.ts +529 -38
  185. package/src/preload/apiSurface.json +209 -7
  186. package/src/preload/index.cjs +46 -1
  187. package/src/seed/agents/architect.md +6 -1
  188. package/src/seed/agents/blender-artist.md +2 -1
  189. package/src/seed/agents/competitive-analyst.md +3 -1
  190. package/src/seed/agents/competitive-researcher.md +2 -1
  191. package/src/seed/agents/demo-video-builder.md +87 -83
  192. package/src/seed/agents/dev-lead.md +3 -3
  193. package/src/seed/agents/project-home-builder.md +9 -31
  194. package/src/seed/agents/validator.md +9 -10
  195. package/dist/assets/AppSettings-DExeJhqQ.js +0 -2
  196. package/dist/assets/HomeClaudeConfig-CTp2tkZ4.js +0 -3
  197. package/dist/assets/Scheduler-cyr61UAC.js +0 -16
  198. package/dist/assets/ViewTabs-DXhOWFG0.js +0 -1
  199. package/dist/assets/index-B2TQz3nd.js +0 -3121
  200. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * smfileRange.cjs — HTTP Range (RFC 9110 §14) streaming for smfile:// media.
5
+ *
6
+ * Audio/video elements seek by issuing `Range: bytes=…` requests; a whole-file
7
+ * buffered read cannot serve a large rendered reel. These helpers stream just
8
+ * the requested slice with fs.createReadStream. Home containment is the
9
+ * caller's job (assertInsideHome runs before buildMediaResponse).
10
+ */
11
+
12
+ const fs = require('node:fs');
13
+ const { Readable } = require('node:stream');
14
+ const { smfileResponseHeaders } = require('../smfileHeaders.cjs');
15
+
16
+ const RANGE_RE = /^bytes=(\d*)-(\d*)$/;
17
+
18
+ /**
19
+ * Parse a single-range `Range` header against a file size.
20
+ * Absent or malformed (incl. multi-range) headers return null: per RFC 9110 a
21
+ * server ignores a Range it cannot parse and sends the full 200 body.
22
+ * @param {string|null|undefined} header
23
+ * @param {number} size
24
+ * @returns {null | {start:number,end:number} | {unsatisfiable:true}}
25
+ */
26
+ function parseRange(header, size) {
27
+ if (typeof header !== 'string' || header === '') return null;
28
+ const m = RANGE_RE.exec(header);
29
+ if (!m) return null;
30
+ const [, a, b] = m;
31
+ if (a === '' && b === '') return null;
32
+ if (a === '') {
33
+ // suffix range: last n bytes
34
+ const n = Number(b);
35
+ if (n === 0 || size === 0) return { unsatisfiable: true };
36
+ return { start: Math.max(0, size - n), end: size - 1 };
37
+ }
38
+ const start = Number(a);
39
+ let end = b === '' ? size - 1 : Number(b);
40
+ if (b !== '' && end < start) return null;
41
+ if (start >= size) return { unsatisfiable: true };
42
+ if (end > size - 1) end = size - 1;
43
+ return { start, end };
44
+ }
45
+
46
+ /**
47
+ * Build a streaming Response (200 / 206 / 416) for a media file.
48
+ * @param {string} realPath already containment-checked real path
49
+ * @param {import('node:fs').Stats} stat
50
+ * @param {string|null|undefined} rangeHeader
51
+ * @param {string} type content type
52
+ * @returns {Response}
53
+ */
54
+ function buildMediaResponse(realPath, stat, rangeHeader, type) {
55
+ const size = stat.size;
56
+ const base = { ...smfileResponseHeaders(realPath, type), 'accept-ranges': 'bytes' };
57
+ const range = parseRange(rangeHeader, size);
58
+ if (range && 'unsatisfiable' in range) {
59
+ return new Response(null, { status: 416, headers: { ...base, 'content-range': `bytes */${size}` } });
60
+ }
61
+ if (!range) {
62
+ const body = size === 0 ? null : Readable.toWeb(fs.createReadStream(realPath));
63
+ return new Response(body, { status: 200, headers: { ...base, 'content-length': String(size) } });
64
+ }
65
+ const { start, end } = range;
66
+ const body = Readable.toWeb(fs.createReadStream(realPath, { start, end }));
67
+ return new Response(body, {
68
+ status: 206,
69
+ headers: {
70
+ ...base,
71
+ 'content-range': `bytes ${start}-${end}/${size}`,
72
+ 'content-length': String(end - start + 1),
73
+ },
74
+ });
75
+ }
76
+
77
+ module.exports = { parseRange, buildMediaResponse };
@@ -74,7 +74,7 @@ async function get({ cwd }) {
74
74
  const { ephemeral } = tryProjectRoot(realCwd);
75
75
  if (ephemeral) return EMPTY();
76
76
  await migrateLegacy(realCwd);
77
- const { knowledge, videos } = await listLibrary(realCwd);
77
+ const { knowledge, videos, persona, outcomes } = await listLibrary(realCwd);
78
78
  const overview = knowledge.find((k) => k.id === 'overview');
79
79
  let html = null;
80
80
  if (overview) {
@@ -91,6 +91,8 @@ async function get({ cwd }) {
91
91
  html,
92
92
  mtimeMs: html === null ? null : overview.mtimeMs,
93
93
  demoVideo: newest ? { path: newest.path, mtimeMs: newest.mtimeMs } : null,
94
+ ...(persona ? { persona } : {}),
95
+ ...(outcomes.length ? { outcomes } : {}),
94
96
  };
95
97
  }
96
98
 
@@ -113,6 +113,11 @@ async function appendResponseEventWithReason(cwd, sourcePromptId, text, meta = {
113
113
  const { kind, id, title } = meta.buildOutput;
114
114
  event.buildOutput = { kind, id, title };
115
115
  }
116
+ // 'artifact-ready' notice rows (lib/epic/artifactNotice.cjs) — whitelisted keys only.
117
+ if (meta && Array.isArray(meta.artifacts)) {
118
+ event.artifacts = meta.artifacts.map((a) => ({ title: a.title, kind: a.kind, path: a.path, size: a.size }));
119
+ if (Number.isInteger(meta.moreCount) && meta.moreCount > 0) event.moreCount = meta.moreCount;
120
+ }
116
121
  // Cross-project reply provenance (crossProjectReply.cjs) — whitelisted
117
122
  // keys only, so a caller can't smuggle arbitrary fields onto the chain.
118
123
  if (meta && meta.reply && typeof meta.reply === 'object') {
package/src/main/pty.cjs CHANGED
@@ -26,6 +26,8 @@ const opsErrorLog = require('./lib/telemetry/opsErrorLog.cjs');
26
26
  const { planEpicSpawn } = require('./lib/epic/epicSpawnPlan.cjs');
27
27
  const { resolveEpicSpawnCwd } = require('./lib/epic/epicSpawnCwd.cjs');
28
28
  const telemetryCounters = require('./lib/telemetry/telemetryCounters.cjs');
29
+ const artifactStore = require('./lib/epic/artifactStore.cjs');
30
+ const { findEpicByClaudeSessionId } = require('./lib/claude/agentModelResolve.cjs');
29
31
 
30
32
  // Absolute path to the installed package root (src/main/ -> ../../), shown in
31
33
  // the remediation message so the user can cd there and rebuild.
@@ -45,6 +47,53 @@ const PTY_FLUSH_MS = 8;
45
47
  // grow the buffer unbounded while waiting for the timer.
46
48
  const PTY_FLUSH_MAX_BYTES = 64 * 1024;
47
49
 
50
+ // An Epic Terminal's artifact staging folder is swept on this cadence (a
51
+ // Terminal-only Epic never ends a chat turn, which is the other ingest point),
52
+ // taking only files untouched for ARTIFACT_MIN_AGE_MS so a file still being
53
+ // written is never moved. One last sweep with no age floor runs on exit.
54
+ const ARTIFACT_INGEST_MS = 15_000;
55
+ const ARTIFACT_MIN_AGE_MS = 10_000;
56
+
57
+ /**
58
+ * Sweep an Epic Terminal's artifact staging folder (runId = tabId) into the
59
+ * Artifacts store every ARTIFACT_INGEST_MS. Returns stop(), which clears the
60
+ * interval and runs one final sweep with no age floor (after any in-flight
61
+ * sweep). Notices are not posted here — artifact-ready-notice owns them.
62
+ * Errors are logged, never thrown.
63
+ */
64
+ function startArtifactIngest({ cwd, epicId, tabId }) {
65
+ let running = Promise.resolve();
66
+ let busy = false;
67
+ const sweep = (minAgeMs) => {
68
+ busy = true;
69
+ running = running.then(async () => {
70
+ try {
71
+ const srcDir = artifactStore.stagingDirFor({ runId: tabId }); // re-creates it if missing
72
+ const res = await artifactStore.ingestDir({
73
+ projectRoot: cwd, epicId, srcDir, minAgeMs, producer: { epicId, sessionId: tabId },
74
+ });
75
+ for (const s of res?.skipped || []) {
76
+ if (s.reason !== 'still being written') console.error('[pty] artifact not ingested', s.path, s.reason);
77
+ }
78
+ } catch (err) {
79
+ console.error('[pty] artifact ingest failed', tabId, err?.message ?? err);
80
+ }
81
+ }).finally(() => { busy = false; });
82
+ return running;
83
+ };
84
+ const timer = setInterval(() => {
85
+ if (!busy) sweep(ARTIFACT_MIN_AGE_MS);
86
+ }, ARTIFACT_INGEST_MS);
87
+ if (typeof timer?.unref === 'function') timer.unref();
88
+ let stopped = false;
89
+ return () => {
90
+ if (stopped) return;
91
+ stopped = true;
92
+ clearInterval(timer);
93
+ sweep(0);
94
+ };
95
+ }
96
+
48
97
  /**
49
98
  * ANSI-formatted terminal text explaining a native-module / immediate-exit
50
99
  * failure and exactly how to fix it. Written straight into the tab's output so
@@ -230,6 +279,20 @@ class PtyManager {
230
279
  // from a worktree pwd. See projectRootResolve.cjs.
231
280
  SM_PROJECT_ROOT: cwd,
232
281
  });
282
+ // An Epic's Terminal gets the SAME artifact staging folder as its Chat view (runId = the
283
+ // session id; EPIC : CLI session = 1:1), so files written there are ingested at the next
284
+ // chat turn's close. Non-Epic terminals get none. Never fails the spawn.
285
+ delete env.SM_ARTIFACTS_DIR; // never inherit the app's own value
286
+ let artifactEpicId = null;
287
+ try {
288
+ const epic = findEpicByClaudeSessionId(cwd, tabId);
289
+ if (epic) {
290
+ artifactEpicId = typeof epic.id === 'string' && epic.id ? epic.id : tabId;
291
+ env.SM_ARTIFACTS_DIR = artifactStore.stagingDirFor({ runId: tabId });
292
+ }
293
+ } catch (err) {
294
+ console.error('[pty] artifact staging dir unavailable', tabId, err?.message ?? err);
295
+ }
233
296
 
234
297
  const shell = defaultShell({ platform: process.platform, env: process.env, exists: fs.existsSync });
235
298
  console.log('[pty] spawning shell', shell.file);
@@ -320,8 +383,13 @@ class PtyManager {
320
383
  }
321
384
  });
322
385
 
386
+ const stopArtifactIngest = artifactEpicId
387
+ ? startArtifactIngest({ cwd, epicId: artifactEpicId, tabId })
388
+ : () => {};
389
+
323
390
  proc.onExit(({ exitCode, signal }) => {
324
391
  console.log('[pty] exit tabId=', tabId, 'code=', exitCode, 'signal=', signal);
392
+ stopArtifactIngest();
325
393
  // Suppress exit broadcast for explicitly killed sessions — a new PTY
326
394
  // may already be listening on the same channel after a restart.
327
395
  if (this.killed.delete(tabId)) {
@@ -40,6 +40,8 @@ const config = require('./config.cjs');
40
40
  const { expandHome } = require('./lib/util/expandHome.cjs');
41
41
  const { HISTORY_RETENTION_MS } = require('./lib/scheduler/schedulerConfig.cjs');
42
42
  const schedulerPaths = require('./lib/scheduler/schedulerPaths.cjs');
43
+ // The one cancelled-row rule (failed OR needs_review + a cancel marker).
44
+ const { isCancelledRow } = require('./lib/scheduler/cancelledRow.cjs');
43
45
 
44
46
  // Lazy: resolved via lib/scheduler/schedulerPaths.cjs at each use (SM_SCHEDULER_HOME).
45
47
  const prdsArchiveDir = () => path.join(schedulerPaths.scheduledPlansRoot(), 'prds-archived');
@@ -129,7 +131,9 @@ const INTERACTIVE_AC_PATTERNS = [
129
131
  const { splitFrontmatter } = require('./lib/prd/prdFrontmatter.cjs');
130
132
  const {
131
133
  resolvePrdsDirs, resolvePrdWriteDir, listEpicPrdDirs, deriveEpicIdFromPrdPath, deriveProjectCwdFromPrdPath,
134
+ isSafeEpicId,
132
135
  } = require('./lib/prd/prdLocations.cjs');
136
+ const { readJsonOrSync } = require('./lib/util/atomicFs.cjs');
133
137
  const { opsPath, assertOpsWrite } = require('./lib/opsOwnership.cjs');
134
138
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
135
139
  const { readActiveIndex } = require('./lib/epic/epicMint.cjs');
@@ -354,15 +358,6 @@ let retireCompletedSlugsFn = async () => {};
354
358
 
355
359
  const DISMISS_ROUTE = 'POST /admin/scheduler/dismiss-cancelled';
356
360
 
357
- /**
358
- * A cancelled row is a 'failed' row carrying the cancel marker remote.cancelJob
359
- * stamps (`cancelledAt`). JOB_STATUSES is closed, so the marker — not a status —
360
- * is what tells a cancel apart from a real failure.
361
- */
362
- function isCancelledRow(j) {
363
- return !!j && j.status === 'failed' && typeof j.cancelledAt === 'string' && j.cancelledAt.length > 0;
364
- }
365
-
366
361
  function cancelledSlugsIn(jobs, cwd) {
367
362
  const out = new Set();
368
363
  for (const j of Array.isArray(jobs) ? jobs : []) {
@@ -547,6 +542,23 @@ function bindQueueAccess(access) {
547
542
 
548
543
  const CLOSED_EPIC_STATUSES = new Set(['completed', 'archived']);
549
544
 
545
+ /**
546
+ * A completed Epic leaves active-index.json (tombstoned) and lives in
547
+ * prompt-sessions/<id>.json. Returns 'completed' only when that archive reads
548
+ * as closed (non-empty archivedAt + session.status 'completed'); an unsafe id
549
+ * or a missing/corrupt file is not closed.
550
+ */
551
+ function archivedEpicStatus(cwd, epicId) {
552
+ if (!isSafeEpicId(epicId)) return null;
553
+ let file;
554
+ try { file = opsPath(cwd, 'prompt-sessions', `${epicId}.json`); } catch { return null; }
555
+ const data = readJsonOrSync(file, null);
556
+ if (!data || typeof data !== 'object') return null;
557
+ const closed = typeof data.archivedAt === 'string' && data.archivedAt !== ''
558
+ && data.session && typeof data.session === 'object' && data.session.status === 'completed';
559
+ return closed ? 'completed' : null;
560
+ }
561
+
550
562
  function cancelledDirForSource(srcDir, ts) {
551
563
  const parent = path.dirname(srcDir);
552
564
  const epicId = deriveEpicIdFromPrdPath(path.join(srcDir, 'x.md'));
@@ -657,8 +669,10 @@ async function dismissCancelled(slug, cwd, opts = {}) {
657
669
  for (const edit of cascadeEdits) {
658
670
  const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
659
671
  if (!d || d.status !== 'pending') continue;
660
- if (queueAccess.transitionJob && !queueAccess.transitionJob(d, 'failed', { reason: edit.reason, source: 'queueOps:dismissCancelled' })) continue;
661
- if (!queueAccess.transitionJob) d.status = 'failed';
672
+ // Every job status write goes through transitionJob (lint:status-writes); an
673
+ // access binding without its own falls back to the chokepoint module directly.
674
+ const transition = queueAccess.transitionJob || require('./lib/scheduler/scheduleJobTransitions.cjs').transitionJob;
675
+ if (!transition(d, 'failed', { reason: edit.reason, source: 'queueOps:dismissCancelled' })) continue;
662
676
  d.error = edit.reason;
663
677
  d.cancelledAt = cancelledAt;
664
678
  d.finishedAt = cancelledAt;
@@ -696,10 +710,16 @@ async function autoDismissCancelled(state) {
696
710
  const candidates = jobs.filter((j) => isCancelledRow(j) && j.epicId && j.cwd);
697
711
  if (candidates.length === 0) return { dismissed: [] };
698
712
  const indexByCwd = new Map();
713
+ const archiveStatus = new Map();
714
+ // An index entry always wins (a reopened Epic stays open); otherwise the
715
+ // archive file decides, read at most once per (cwd, epicId) per call.
699
716
  const epicStatus = (cwd, epicId) => {
700
717
  if (!indexByCwd.has(cwd)) indexByCwd.set(cwd, readActiveIndex(cwd).sessions);
701
718
  const sessions = indexByCwd.get(cwd);
702
- return Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId]?.status ?? null : null;
719
+ if (Object.prototype.hasOwnProperty.call(sessions, epicId)) return sessions[epicId]?.status ?? null;
720
+ const key = `${cwd}\0${epicId}`;
721
+ if (!archiveStatus.has(key)) archiveStatus.set(key, archivedEpicStatus(cwd, epicId));
722
+ return archiveStatus.get(key);
703
723
  };
704
724
  const ts = newTs();
705
725
  const dismissed = [];
@@ -884,7 +904,6 @@ module.exports = {
884
904
  lintOneAsync,
885
905
  archiveMany,
886
906
  bindQueueAccess,
887
- isCancelledRow,
888
907
  dismissCancelled,
889
908
  autoDismissCancelled,
890
909
  selectAutoArchivable,
@@ -564,7 +564,10 @@ function isGitRepo(cwd) {
564
564
  * `cwd` may be a list of roots; a path is accepted if it verifies under any —
565
565
  * except a `session-manager-operations/plan-records/` path, which verifies only
566
566
  * under the first root (the main checkout).
567
- * Complexity O(paths).
567
+ * A path that resolves to a DIRECTORY (e.g. a trailing-`/` plan-records folder)
568
+ * verifies when at least one DIRECT child (not recursive) is a non-empty regular
569
+ * file inside the same run window; a trailing-slash path that is a file fails.
570
+ * Complexity O(paths × direct children).
568
571
  */
569
572
  function artifactsVerifiedOnDisk({ cwd, paths, startedAt, finishedAt, fsImpl = fs } = {}) {
570
573
  return artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl }).ok;
@@ -601,6 +604,29 @@ function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
601
604
  if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) continue;
602
605
  let st;
603
606
  try { st = fsImpl.statSync(abs); } catch { continue; }
607
+ if (st.isDirectory()) {
608
+ // Directory artifact: newest fresh, non-empty regular DIRECT child.
609
+ let best = null;
610
+ try {
611
+ for (const name of fsImpl.readdirSync(abs)) {
612
+ let cs;
613
+ try { cs = fsImpl.statSync(path.join(abs, name)); } catch { continue; }
614
+ if (!cs.isFile() || cs.size <= 0) continue;
615
+ if (cs.mtimeMs < lo || cs.mtimeMs > hi) continue;
616
+ if (!best || cs.mtimeMs > best.st.mtimeMs) best = { name, st: cs };
617
+ }
618
+ } catch { continue; }
619
+ if (!best) continue;
620
+ hit = {
621
+ path: p,
622
+ size: best.st.size,
623
+ mtime: new Date(best.st.mtimeMs).toISOString(),
624
+ file: path.posix.join(p.replace(/\\/g, '/').replace(/\/+$/, ''), best.name),
625
+ };
626
+ break;
627
+ }
628
+ // A trailing-slash declaration must name a directory.
629
+ if (/[\\/]$/.test(p)) continue;
604
630
  if (!st.isFile() || st.size <= 0) continue;
605
631
  if (st.mtimeMs < lo || st.mtimeMs > hi) continue;
606
632
  hit = { path: p, size: st.size, mtime: new Date(st.mtimeMs).toISOString() };
@@ -615,6 +641,28 @@ function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
615
641
  }
616
642
  }
617
643
 
644
+ /**
645
+ * Capture artifact evidence for a DECLARED artifact-only PRD while the job
646
+ * worktree still exists (spawnJob tears it down before verifyRun runs). Runs
647
+ * the same artifactsCheck verifyRun would, against `roots` (main checkout
648
+ * first, then the worktree), with an open-ended window (finishedAt: null =
649
+ * now). Returns null when the PRD is not an artifact-only declaration or on any
650
+ * read/parse error — never throws. Otherwise { ok, verified, paths, capturedAt }
651
+ * where `paths` is a copy of the frontmatter artifactPaths, so verifyRun can
652
+ * refuse evidence captured for a different declaration.
653
+ */
654
+ function captureArtifactEvidence({ prdPath, roots, startedAt, fsImpl = fs } = {}) {
655
+ try {
656
+ const text = fs.readFileSync(prdPath, 'utf8');
657
+ const fm = parsePrdFile(text).frontmatter;
658
+ if (!isArtifactOnlyDeclaration(fm)) return null;
659
+ const check = artifactsCheck({ cwd: roots, paths: fm.artifactPaths, startedAt, finishedAt: null, fsImpl });
660
+ return { ok: check.ok, verified: check.verified, paths: [...fm.artifactPaths], capturedAt: new Date().toISOString() };
661
+ } catch {
662
+ return null;
663
+ }
664
+ }
665
+
618
666
  // ─── main verifier ────────────────────────────────────────────────────────────
619
667
 
620
668
  /**
@@ -658,11 +706,18 @@ function artifactsCheck({ cwd, paths, startedAt, finishedAt, fsImpl = fs }) {
658
706
  * ever applies when this is exactly 0 — default
659
707
  * null so callers that don't pass it keep
660
708
  * today's behavior byte-for-byte.
709
+ * @param {object|null} [params.artifactEvidence] Result of captureArtifactEvidence,
710
+ * taken by the caller while the job worktree
711
+ * still existed (before teardown). The artifact
712
+ * exemption checks queueEntry.cwd live; only when
713
+ * that fails does it accept this evidence, and
714
+ * only if ok === true and its paths equal the
715
+ * frontmatter artifactPaths. Default null.
661
716
  * @returns {Promise<{verdict:string, reason:string, downgradeTo:string|null}>}
662
717
  */
663
718
  async function verifyRun({
664
719
  runDir, prdPath, queueEntry, allJobs = [], committedDuringRun = false,
665
- ghExecImpl, priorLandedCommit = null, jobLandedCommitThisRun = null, exitCode = null, worktreeDir = null,
720
+ ghExecImpl, priorLandedCommit = null, jobLandedCommitThisRun = null, exitCode = null, artifactEvidence = null,
666
721
  }) {
667
722
  const { slug } = queueEntry;
668
723
  const logPath = path.join(runDir, `${slug}.log`);
@@ -927,9 +982,10 @@ async function verifyRun({
927
982
  // (all deliverables live in a git-excluded dir, so "no commit" is
928
983
  // correct). Reads the declared list from frontmatter — never scrapes
929
984
  // prose — and stat-checks each file on disk (non-empty, in the run
930
- // window). Paths resolve against queueEntry.cwd, then retry against the
931
- // run's worktree dir when the caller supplies one. Any doubt falls
932
- // through to pass_no_commit below. The commit guard separately requires
985
+ // window). Paths resolve against queueEntry.cwd live; when that fails,
986
+ // the caller's artifactEvidence (captureArtifactEvidence, run in the job
987
+ // worktree before teardown) counts only if ok and its paths equal the
988
+ // frontmatter artifactPaths. Any doubt falls through to pass_no_commit. The commit guard separately requires
933
989
  // a clean tree for this verdict (scheduler.cjs commitGuardVerdict).
934
990
  let artifactVerified = false;
935
991
  if (!mergeMainVerified && !priorRunVerified) {
@@ -937,22 +993,30 @@ async function verifyRun({
937
993
  try { fm = parsePrdFile(prdFullText).frontmatter; } catch { fm = null; }
938
994
  if (isArtifactOnlyDeclaration(fm)) {
939
995
  const check = artifactsCheck({
940
- cwd: [queueEntry?.cwd, worktreeDir],
996
+ cwd: [queueEntry?.cwd],
941
997
  paths: fm.artifactPaths,
942
998
  startedAt: queueEntry?.startedAt,
943
999
  finishedAt: queueEntry?.finishedAt,
944
1000
  });
945
- if (check.ok) {
1001
+ const evidenceOk = !check.ok
1002
+ && artifactEvidence && artifactEvidence.ok === true
1003
+ && Array.isArray(artifactEvidence.paths) && Array.isArray(artifactEvidence.verified)
1004
+ && artifactEvidence.paths.length === fm.artifactPaths.length
1005
+ && artifactEvidence.paths.every((p, i) => p === fm.artifactPaths[i]);
1006
+ if (check.ok || evidenceOk) {
946
1007
  artifactVerified = true;
1008
+ const verified = check.ok ? check.verified : artifactEvidence.verified;
947
1009
  return conclude(
948
1010
  'pass_no_commit_artifact_verified',
949
1011
  'SCHEDULER_VERDICT: PASS with no commit, but every declared artifact exists, is non-empty, and was '
950
- + `written inside the run window (${check.verified.map((v) => v.path).join(', ')})`,
1012
+ + `written inside the run window (${verified.map((v) => v.path).join(', ')})`
1013
+ + (check.ok ? '' : ' (checked in the job worktree before teardown)'),
951
1014
  null,
952
1015
  {
953
1016
  ...(annotations.length ? { annotations } : {}),
954
1017
  sentinel,
955
- verifiedArtifacts: check.verified,
1018
+ verifiedArtifacts: verified,
1019
+ ...(check.ok ? {} : { artifactEvidenceSource: 'pre-teardown' }),
956
1020
  },
957
1021
  );
958
1022
  }
@@ -1003,6 +1067,7 @@ module.exports = {
1003
1067
  extractMergeMainPrNumber,
1004
1068
  checkMergeablePr,
1005
1069
  artifactsVerifiedOnDisk,
1070
+ captureArtifactEvidence,
1006
1071
  isAncestorCommit,
1007
1072
  commitExistsInRepo,
1008
1073
  commitOnAnyRef,
@@ -19,6 +19,7 @@ Runtime diagnosis (stuck queue, `needs_review`, reap gate) is NOT here — see
19
19
  | `needs_review` / auto-fix / auto-reset eligibility, verdict sets, thresholds | `reviewLadder.cjs` |
20
20
  | Git status/stash/HEAD helpers, shared-tree guard, commit-guard, finalize-drop predicates | `gitTreeGuard.cjs` |
21
21
  | Starvation / blocked-chain classifiers, dispatch-idle clock | `starvation.cjs` |
22
+ | Automatic-dispatch hold rule (usage threshold, manual fire policy, which windows count) | `utilizationHold.cjs` |
22
23
  | Stall / stranded-row / overrun / wall-clock budget selectors, failure backoff, `dependsOn` history lookup | `budget.cjs` |
23
24
  | `spawnJob` / execution, `tickQueue`, dead-process reaper, poll loop, IPC handlers, admin routes, queue-mutating ladder rungs and watchdogs | `../scheduler.cjs` (by section banner) |
24
25
 
@@ -16,7 +16,8 @@ const { LEGAL_TRANSITIONS } = require('../lib/scheduler/scheduleJobTransitions.c
16
16
  const {
17
17
  DEFAULT_PROJECT_CWD, DEP_HISTORY_FAIL_OPEN, enqueueTimestamp, findBlockingDep,
18
18
  } = require('../lib/scheduler/schedulerBatch.cjs');
19
- const { makeDepResolver, isCancelledRow, isSatisfiedDepRow } = require('../lib/prd/depSlugResolve.cjs');
19
+ const { makeDepResolver, isSatisfiedDepRow } = require('../lib/prd/depSlugResolve.cjs');
20
+ const { isCancelledRow } = require('../lib/scheduler/cancelledRow.cjs');
20
21
  const {
21
22
  JOB_OVERRUN_FACTOR: JOB_OVERRUN_FACTOR_DEFAULT,
22
23
  JOB_OVERRUN_FLOOR_MS: JOB_OVERRUN_FLOOR_MS_DEFAULT,
@@ -45,15 +46,16 @@ const JOB_BUDGET_CEILING_MS = numEnvOverride('SM_JOB_BUDGET_CEILING_MINUTES', 60
45
46
 
46
47
  /**
47
48
  * isNonProblemRow(row) — a row that is NOT waiting on anyone: completed,
48
- * skipped, or a `failed` row a human cancelled (isCancelledRow — `cancelledAt`
49
- * or an error starting 'cancelled via admin API'). A cancel is a decision,
49
+ * skipped, or any row a human cancelled (isCancelledRow, the shared rule in
50
+ * lib/scheduler/cancelledRow.cjs — covers both the 'failed' and the
51
+ * 'needs_review' cancel parks). A cancel is a decision,
50
52
  * not a fault; counting it as a parked problem flagged Self's closed Epic
51
53
  * (cancelled 1012-1016) as stalled every ~8 minutes (2026-11-22).
52
54
  */
53
55
  function isNonProblemRow(row) {
54
56
  if (!row) return false;
55
57
  if (row.status === 'completed' || row.status === 'skipped') return true;
56
- return row.status === 'failed' && isCancelledRow(row);
58
+ return isCancelledRow(row);
57
59
  }
58
60
 
59
61
  /**
@@ -952,7 +954,6 @@ module.exports = {
952
954
  JOB_BUDGET_FLOOR_MS,
953
955
  JOB_BUDGET_CEILING_MS,
954
956
  computeStallSummary,
955
- isCancelledRow,
956
957
  isNonProblemRow,
957
958
  classifyPendingHolds,
958
959
  findDependencyStalledProjects,
@@ -6,7 +6,9 @@
6
6
  * cache is module-private and keyed by absolute file path.
7
7
  *
8
8
  * Two-level cache for reconcile():
9
- * - dirCache: keyed by PRDS_DIR mtimeMs — invalidated when files added/removed.
9
+ * - dirCache: per prds/ dir path → { mtimeMs, files } — invalidated when that
10
+ * dir's files are added/removed. Keyed by path because scheduler.cjs scans
11
+ * every Epic prds/ dir in parallel and dirs often share one mtime tick.
10
12
  * - fileCache: per-PRD parse keyed by individual file mtimeMs — survives across
11
13
  * dir-cache invalidations so adding ONE new PRD doesn't re-parse the other 197.
12
14
  * Both layers also bound by ino so a rename + re-create can't alias.
@@ -21,6 +23,7 @@ const { splitFrontmatter, parseInlineList, parseFixes, parsePreflightValue, PRD_
21
23
  const { deriveEpicIdFromPrdPath } = require('../lib/prd/prdLocations.cjs');
22
24
  const { parseFilesSection } = require('../lib/prd/prdGateFiles.cjs');
23
25
  const { reportDanglingAgentTypeOnce } = require('../lib/prd/prdAgentType.cjs');
26
+ const { VOICE_ID_RE } = require('../lib/demo-video-kit/voiceLibrary.cjs');
24
27
 
25
28
  /**
26
29
  * Expand a PRD `cwd` value to an absolute path.
@@ -41,8 +44,7 @@ function expandCwd(cwd) {
41
44
  // already ~25k lines and well beyond any legitimate authored doc.
42
45
  const PRD_READ_MAX_BYTES = 1024 * 1024;
43
46
 
44
- let prdDirMtime = -1;
45
- let prdDirFiles = null; // sorted absolute paths
47
+ const prdDirCache = new Map(); // prdsDir -> { mtimeMs, files } (files = sorted absolute paths)
46
48
  const prdFileCache = new Map(); // path -> { mtimeMs, ino, parsed }
47
49
 
48
50
  /**
@@ -153,6 +155,8 @@ async function parsePrdRaw(filePath) {
153
155
  deliverable: (typeof fm.deliverable === 'string' && fm.deliverable.trim() === 'artifact') ? 'artifact' : null,
154
156
  artifactPaths: parseArtifactPaths(fm.artifactPaths),
155
157
  effort: (typeof fm.effort === 'string' && PRD_EFFORT_LEVELS.includes(fm.effort.trim())) ? fm.effort.trim() : null,
158
+ // In-process-only library voice (voiceLibrary.cjs VOICE_ID_RE); executeJob hands it to the job as SM_VOICE_ID.
159
+ voiceId: (typeof fm.voiceId === 'string' && VOICE_ID_RE.test(fm.voiceId.trim())) ? fm.voiceId.trim() : null,
156
160
  // Optional precondition command (preflightCheck.cjs); reconcile copies it
157
161
  // onto the queue row so spawnJob can hold the job while it exits non-zero.
158
162
  preflight: typeof fm.preflight === 'string' ? parsePreflightValue(rawFrontmatterValue(text, 'preflight')) : null,
@@ -192,8 +196,9 @@ function parseDependsOn(raw) {
192
196
  }
193
197
 
194
198
  /**
195
- * List `.md` PRD files under the given dir. Caches the result keyed by the
196
- * directory mtime so repeated reconcile() calls don't re-stat every entry.
199
+ * List `.md` PRD files under the given dir. Caches the result per dir path,
200
+ * validated by that dir's mtime, so repeated reconcile() calls don't re-read
201
+ * every dir.
197
202
  * Pass `prdsDir` so the scheduler can keep ownership of its PRDS_DIR path
198
203
  * without this module needing to know it.
199
204
  */
@@ -204,7 +209,8 @@ async function listPrdFiles(prdsDir) {
204
209
  } catch {
205
210
  dirMtime = -1;
206
211
  }
207
- if (dirMtime === prdDirMtime && prdDirFiles) return prdDirFiles;
212
+ const hit = prdDirCache.get(prdsDir);
213
+ if (hit && hit.mtimeMs === dirMtime) return hit.files;
208
214
  let entries;
209
215
  try {
210
216
  entries = await fsp.readdir(prdsDir);
@@ -215,16 +221,17 @@ async function listPrdFiles(prdsDir) {
215
221
  .filter((f) => f.endsWith('.md') && !f.startsWith('.'))
216
222
  .map((f) => path.join(prdsDir, f))
217
223
  .sort();
218
- // Drop file-cache entries whose path is no longer on disk so the map
219
- // doesn't accumulate ghosts after archives/deletes.
224
+ // Drop this dir's file-cache entries whose path is no longer on disk so the
225
+ // map doesn't accumulate ghosts after archives/deletes. Other dirs' entries
226
+ // are theirs to prune.
220
227
  if (prdFileCache.size > 0) {
221
228
  const live = new Set(files);
229
+ const dirKey = path.dirname(path.join(prdsDir, 'x')); // normalized, no trailing sep
222
230
  for (const k of prdFileCache.keys()) {
223
- if (!live.has(k)) prdFileCache.delete(k);
231
+ if (path.dirname(k) === dirKey && !live.has(k)) prdFileCache.delete(k);
224
232
  }
225
233
  }
226
- prdDirMtime = dirMtime;
227
- prdDirFiles = files;
234
+ prdDirCache.set(prdsDir, { mtimeMs: dirMtime, files });
228
235
  return files;
229
236
  }
230
237
 
@@ -257,10 +264,34 @@ async function parsePrd(filePath) {
257
264
  return parsed;
258
265
  }
259
266
 
267
+ /**
268
+ * Drop every dir-cache and file-cache entry whose folder is not in `dirs`.
269
+ * listPrdFiles prunes only within the folder it lists, so a folder the
270
+ * scheduler stopped scanning altogether (a removed Epic's prds/) would keep
271
+ * its entries for the life of the process. scheduler.cjs calls this once per
272
+ * pass with the full candidate folder list.
273
+ * @param {Iterable<string>} dirs
274
+ */
275
+ function retainPrdDirs(dirs) {
276
+ const norm = (d) => path.dirname(path.join(d, 'x')); // normalized, no trailing sep
277
+ const live = new Set();
278
+ for (const d of dirs) live.add(norm(d));
279
+ for (const k of prdDirCache.keys()) {
280
+ if (!live.has(norm(k))) prdDirCache.delete(k);
281
+ }
282
+ for (const k of prdFileCache.keys()) {
283
+ if (!live.has(path.dirname(k))) prdFileCache.delete(k);
284
+ }
285
+ }
286
+
287
+ /** Test-only: current cache keys. */
288
+ function _cacheKeys() {
289
+ return { dirs: [...prdDirCache.keys()], files: [...prdFileCache.keys()] };
290
+ }
291
+
260
292
  /** Test-only: drop both cache layers so successive runs see fresh disk state. */
261
293
  function _resetCache() {
262
- prdDirMtime = -1;
263
- prdDirFiles = null;
294
+ prdDirCache.clear();
264
295
  prdFileCache.clear();
265
296
  }
266
297
 
@@ -461,5 +492,7 @@ module.exports = {
461
492
  pruneStaleReservations,
462
493
  maxParallelGroupInUse,
463
494
  PRD_READ_MAX_BYTES,
495
+ retainPrdDirs,
464
496
  _resetCache,
497
+ _cacheKeys,
465
498
  };