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
@@ -23,7 +23,7 @@ const { kebabCase } = require('../util/kebabCase.cjs');
23
23
  const config = require('../../config.cjs');
24
24
  const { expandHome } = require('../util/expandHome.cjs');
25
25
  const { readBody, sendJson } = require('../feedback-remote/localAdminHttp.cjs');
26
- const { readActiveIndex } = require('../epic/epicMint.cjs');
26
+ const { readActiveIndex, withPathLock } = require('../epic/epicMint.cjs');
27
27
  const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
28
28
  const { resolveProjectContext } = require('../projectRootResolve.cjs');
29
29
  const { fixChainDepthOf, baseSlugOf } = require('../scheduler/fixChainDepth.cjs');
@@ -81,7 +81,8 @@ const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
81
81
  const { execGit } = require('../git/gitExec.cjs');
82
82
  const { extractRepoPathCandidates, worktreeReachWarnings } = require('./prdWorktreeReach.cjs');
83
83
  const { isSweepValidatorSlug } = require('../epic/epicSweepValidator.cjs');
84
- const { validateGate, validateFiles, renderFilesSection, renderGateSection, parseFilesSection } = require('./prdGateFiles.cjs');
84
+ const { NONE_GATE_WARNING, validateGate, validateFiles, renderFilesSection, renderGateSection, parseFilesSection } = require('./prdGateFiles.cjs');
85
+ const { normalizeCriteria, validateCriteria, serializeCriteria, renderCriteriaLines } = require('./prdCriteria.cjs');
85
86
  const { filesOverlap } = require('../scheduler/schedulerBatch.cjs');
86
87
  const { resolveGate, parseChain, isNoneGate } = require('../scheduler/definitionOfDone.cjs');
87
88
  const { MISS_KINDS } = require('../scheduler/validatorVerdictSchema.cjs');
@@ -127,6 +128,8 @@ function deriveSlugFromTitle(title) {
127
128
  * Engineering standards, in order.
128
129
  */
129
130
  const MACRO_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
131
+ // Voice-library id pattern: the one owner is voiceLibrary.cjs.
132
+ const { VOICE_ID_RE } = require('../demo-video-kit/voiceLibrary.cjs');
130
133
  function isValidMacroId(id) {
131
134
  return typeof id === 'string' && MACRO_ID_RE.test(id);
132
135
  }
@@ -134,9 +137,13 @@ function isValidMacroId(id) {
134
137
  function buildPrdBody(input) {
135
138
  const {
136
139
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
137
- implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, riskTools, preflight,
140
+ implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, voiceId, riskTools, preflight,
138
141
  gate, files, budgetExempt, fixes,
139
142
  } = input;
143
+ // Structured criteria (prdCriteria.cjs): createPrd() normalizes once and
144
+ // passes `criteria`; a direct caller with only string criteria gets the
145
+ // same normalization here, so every PRD carries ids.
146
+ const criteria = Array.isArray(input.criteria) ? input.criteria : normalizeCriteria(acceptanceCriteria);
140
147
 
141
148
  // No `parallelGroup` frontmatter key (PRD_AUTHORING.md §5) — the NN-
142
149
  // filename prefix is the single source of truth for grouping; adding a
@@ -193,6 +200,7 @@ function buildPrdBody(input) {
193
200
  // prdFrontmatter.cjs's applyKey for the matching "only true opts in" parse.
194
201
  if (isValidMacroId(macroId)) fmLines.push(`macroId: ${macroId}`);
195
202
  if (PRD_EFFORT_LEVELS.includes(effort)) fmLines.push(`effort: ${effort}`);
203
+ if (typeof voiceId === 'string' && VOICE_ID_RE.test(voiceId)) fmLines.push(`voiceId: ${voiceId}`);
196
204
  // Risky tools this PRD is cleared to call — validated + de-duplicated by createPrd().
197
205
  if (Array.isArray(riskTools) && riskTools.length) fmLines.push(`riskTools: ${formatQuotedInlineList(riskTools)}`);
198
206
  // Precondition command — validated by createPrd() via normalizePreflightField.
@@ -202,9 +210,11 @@ function buildPrdBody(input) {
202
210
  // Budget exemption is for a sweep validator that cannot be split further;
203
211
  // every other caller's budgetExempt is ignored.
204
212
  if (budgetExempt === true && agentType === 'validator' && isSweepValidatorSlug(input.slug)) fmLines.push('budgetExempt: true');
213
+ // Normalized criteria as one-line JSON — [{ id, statement, check: { kind, spec? } }].
214
+ fmLines.push(`criteria: ${serializeCriteria(criteria)}`);
205
215
  fmLines.push('---', '');
206
216
 
207
- const acLines = acceptanceCriteria.map((line) => `- [ ] ${line}`).join('\n');
217
+ const acLines = renderCriteriaLines(criteria).join('\n');
208
218
  const oosSource = outOfScope && outOfScope.length ? outOfScope : ['(none)'];
209
219
  const oosLines = oosSource.map((line) => `- ${line}`).join('\n');
210
220
 
@@ -430,16 +440,22 @@ function crossEpicDuplicateError(slug, dups) {
430
440
  * Cross-Epic files-overlap advisory (2026-11-22 Self stall: 1047 and 1056 also
431
441
  * declared the same files). Dispatch already serializes overlapping files, so
432
442
  * this only WARNS — never refuses. Candidates: listing rows of another Epic
433
- * whose status is pending/running/investigating. A row's `files` is used when
443
+ * whose status is pending/running/investigating, plus live (not archived) rows
444
+ * whose status is null — a PRD file written moments ago has no queue row until
445
+ * the next reconcile pass, so the listing gives it status null (2026-11-24
446
+ * Bilko: 2005 named the same files as 2001, unreconciled, and got no warning).
447
+ * Archived, completed and cancelled rows never warn. A row's `files` is used when
434
448
  * present, else its `# Files` section is read via remote.readPrd + the shared
435
449
  * parseFilesSection. Overlap uses the scheduler's own filesOverlap rule.
436
450
  */
437
451
  const OVERLAP_ACTIVE_STATUSES = new Set(['pending', 'running', 'investigating']);
452
+ const isOverlapCandidate = (r) => OVERLAP_ACTIVE_STATUSES.has(r.status)
453
+ || (r.status == null && r.archived !== true);
438
454
  async function crossEpicFilesOverlapWarnings(newFiles, epicId, rows, remote, cwd) {
439
455
  if (!Array.isArray(newFiles) || !newFiles.length || !Array.isArray(rows)) return [];
440
456
  const warnings = [];
441
457
  for (const r of rows) {
442
- if (!r || typeof r.slug !== 'string' || !OVERLAP_ACTIVE_STATUSES.has(r.status)) continue;
458
+ if (!r || typeof r.slug !== 'string' || !isOverlapCandidate(r)) continue;
443
459
  if (r.epicId == null || r.epicId === '' || r.epicId === (epicId ?? null)) continue;
444
460
  let otherFiles = Array.isArray(r.files) ? r.files : null;
445
461
  if (!otherFiles) {
@@ -561,10 +577,14 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
561
577
  // caller didn't already give an explicit dependsOn (that already fixes
562
578
  // its position in some chain) — joining an Epic whose sourcePromptId this
563
579
  // PRD shares. See prdDisposition.cjs's header for the full contract.
580
+ // Slugs this pre-lock read saw: the in-lock same-Epic re-check refuses only rows
581
+ // written since (null = no pre-lock read, every same-Epic row counts as new).
582
+ let seenBeforeLock = null;
564
583
  if (input.sourcePromptId && (!input.dependsOn || input.dependsOn.length === 0)) {
565
584
  let epicRows = [];
566
585
  try {
567
586
  const listing = await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
587
+ seenBeforeLock = new Set((listing?.prds ?? []).map((r) => r?.slug));
568
588
  epicRows = (listing?.prds ?? []).filter((p) => p.sourcePromptId === input.sourcePromptId);
569
589
  } catch (e) {
570
590
  console.warn(`[prdCreate] disposition resolution skipped (listPrds failed): ${e?.message ?? e}`);
@@ -670,6 +690,11 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
670
690
  if (input.effort != null && !PRD_EFFORT_LEVELS.includes(input.effort)) {
671
691
  return { ok: false, applied: false, status: 400, error: 'effort must be one of low, medium, high, xhigh, max when given' };
672
692
  }
693
+ // voiceId (in-process callers only, like effort — the schedulerCreatePrd
694
+ // schema has no voiceId, so the HTTP/MCP path strips a caller-supplied one).
695
+ if (input.voiceId != null && !(typeof input.voiceId === 'string' && VOICE_ID_RE.test(input.voiceId))) {
696
+ return { ok: false, applied: false, status: 400, error: `voiceId must match /${VOICE_ID_RE.source}/ when given` };
697
+ }
673
698
  // riskTools: tool-risk rule strings (toolRiskMarks.parseRule grammar) this PRD
674
699
  // is cleared to call. Refused before NN allocation; de-duplicated in order.
675
700
  if (input.riskTools != null) {
@@ -685,6 +710,16 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
685
710
  input = { ...input, preflight: pf.value || undefined };
686
711
  }
687
712
 
713
+ // Structured criteria (prdCriteria.cjs): strings become manual ac-<n>
714
+ // criteria; objects are checked per kind. Refused before NN allocation.
715
+ // acceptanceCriteria is rewritten to the plain statements so every
716
+ // string-only consumer below (heading guard, sizing, worktree reach) works.
717
+ {
718
+ const cv = validateCriteria(input.acceptanceCriteria);
719
+ if (!cv.ok) return { ok: false, applied: false, status: 400, error: `acceptance ${cv.error}` };
720
+ input = { ...input, criteria: cv.criteria, acceptanceCriteria: cv.criteria.map((c) => c.statement) };
721
+ }
722
+
688
723
  // Fake-heading guard (gate-and-files-in-PRD-body unit): a caller-supplied
689
724
  // free-text field that itself contains a "# Gate" or "# Files" heading line
690
725
  // would, after buildPrdBody splices in the real section below, read as TWO
@@ -731,7 +766,11 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
731
766
  return { ok: false, applied: false, status: 400, error: gateValidation.error };
732
767
  }
733
768
  gateCommands = gateValidation.commands;
734
- extraWarnings.push(...gateValidation.warnings);
769
+ // A validator PRD's gate is always none (it re-runs the plan's gates itself),
770
+ // so the none-gate warning is expected noise for it — drop only that one.
771
+ extraWarnings.push(...gateValidation.warnings.filter(
772
+ (w) => !(input.agentType === 'validator' && w === NONE_GATE_WARNING),
773
+ ));
735
774
  } else {
736
775
  extraWarnings.push('No gate: the scheduler cannot re-check this PRD.');
737
776
  }
@@ -806,227 +845,266 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
806
845
  }
807
846
  }
808
847
 
809
- // One full listing (slug/epicId/status per live + archived PRD) serves both the
810
- // cross-Epic duplicate guard below and the dependsOn FK check after NN allocation.
811
- // A read failure is skipped-with-a-warning, never a write outage.
812
- const needCrossEpicGuard = opts.internalMint !== true;
813
- let listing = null;
814
- const hasFixes = input.fixes !== undefined && input.fixes !== null;
815
- if (needCrossEpicGuard || hasFixes || (input.dependsOn && input.dependsOn.length) || (filesList && filesList.length)) {
816
- try {
817
- listing = opts.listingCache
818
- ? await (opts.listingCache.promise ??= remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER }))
819
- : await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
820
- } catch (e) {
821
- console.warn(`[prdCreate] listPrds failed (cross-Epic duplicate + dependsOn checks skipped): ${e?.message ?? e}`);
822
- listing = null;
848
+ // Everything from the listing read through remote.writePrd runs as one phase.
849
+ // A real create runs it inside the per-project create lock on a FRESH listing
850
+ // (2026-11-24 Bilko 2001/2005: a create read its listing, awaited NN
851
+ // allocation, and wrote while another Epic's create wrote the same bare slug).
852
+ // A dry run (createPrdBatch's validate pass) takes no lock; the batch re-checks
853
+ // inside the lock itself. The phase returns an early-refusal / dry-run result,
854
+ // or null once the file is written (writeResult, nn, filenameSlug,
855
+ // duplicateAllowed and input are set on the closure).
856
+ let duplicateAllowed = null;
857
+ let nn;
858
+ let filenameSlug;
859
+ let writeResult;
860
+ const createPhase = async () => {
861
+ // One full listing (slug/epicId/status per live + archived PRD) serves both the
862
+ // cross-Epic duplicate guard below and the dependsOn FK check after NN allocation.
863
+ // A read failure is skipped-with-a-warning, never a write outage.
864
+ const needCrossEpicGuard = opts.internalMint !== true;
865
+ let listing = null;
866
+ const hasFixes = input.fixes !== undefined && input.fixes !== null;
867
+ // A real create always reads: the in-lock same-Epic re-check must not depend
868
+ // on which optional fields (fixes/dependsOn/files) the caller sends.
869
+ if (!opts.dryRun || needCrossEpicGuard || hasFixes || (input.dependsOn && input.dependsOn.length) || (filesList && filesList.length)) {
870
+ try {
871
+ const q = { cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER };
872
+ if (!opts.dryRun) listing = await remote.listPrds({ ...q, fresh: true });
873
+ else if (opts.listingCache) listing = await (opts.listingCache.promise ??= remote.listPrds(q));
874
+ else listing = await remote.listPrds(q);
875
+ } catch (e) {
876
+ console.warn(`[prdCreate] listPrds failed (cross-Epic duplicate + dependsOn checks skipped): ${e?.message ?? e}`);
877
+ listing = null;
878
+ }
823
879
  }
824
- }
825
880
 
826
- // Cross-Epic duplicate guard: refused before NN allocation so it burns no number.
827
- let duplicateAllowed = null;
828
- if (needCrossEpicGuard && listing) {
829
- const dups = findCrossEpicDuplicates(slug, input.sourcePromptId ?? null, listing.prds ?? []);
830
- if (dups.length) {
831
- const allowed = new Set(Array.isArray(input.allowDuplicateOf) ? input.allowDuplicateOf : []);
832
- if (!dups.every((r) => allowed.has(r.slug))) {
833
- return { ok: false, applied: false, status: 409, error: crossEpicDuplicateError(slug, dups) };
881
+ // Same-Epic re-check on the fresh listing, inside the lock: a same-Epic create
882
+ // that wrote this bare slug since the pre-lock reads is refused here,
883
+ // before NN allocation, with the directory scan's own wording.
884
+ if (!opts.dryRun && listing && input.sourcePromptId && !isFixPlanSlug(`0-${slug}`)) {
885
+ const target = bareSlug(slug);
886
+ const same = (listing.prds ?? []).find((r) => r && typeof r.slug === 'string'
887
+ && r.epicId === input.sourcePromptId && !(seenBeforeLock && seenBeforeLock.has(r.slug))
888
+ && bareSlug(r.slug) === target);
889
+ if (same) {
890
+ return {
891
+ ok: false, applied: false,
892
+ status: 409,
893
+ error: `A PRD with slug "${slug}" already exists in this Epic as "${same.slug}.md". Its work may already have landed. ` +
894
+ 'Use scheduler_update_prd / scheduler_reset_job on it, or pick a distinct slug.',
895
+ };
834
896
  }
835
- duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
836
897
  }
837
- }
838
898
 
839
- // Cross-Epic files-overlap advisory: a warning, never a refusal.
840
- if (listing && filesList && filesList.length) {
841
- extraWarnings.push(...await crossEpicFilesOverlapWarnings(filesList, input.sourcePromptId ?? null, listing.prds ?? [], remote, input.cwd));
842
- }
899
+ // Cross-Epic duplicate guard: refused before NN allocation so it burns no number.
900
+ if (needCrossEpicGuard && listing) {
901
+ const dups = findCrossEpicDuplicates(slug, input.sourcePromptId ?? null, listing.prds ?? []);
902
+ if (dups.length) {
903
+ const allowed = new Set(Array.isArray(input.allowDuplicateOf) ? input.allowDuplicateOf : []);
904
+ if (!dups.every((r) => allowed.has(r.slug))) {
905
+ return { ok: false, applied: false, status: 409, error: crossEpicDuplicateError(slug, dups) };
906
+ }
907
+ duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
908
+ }
909
+ }
843
910
 
844
- // fixes: shape-checked and resolved to full NN slugs before NN allocation, so a
845
- // refusal burns no number. Fail-closed when the listing could not be read — an
846
- // unresolved fixes link would miscount escapes.
847
- if (hasFixes) {
848
- const shapeErrors = validateFixesShape(input.fixes, slug);
849
- if (shapeErrors.length) {
850
- return { ok: false, applied: false, status: 400, error: shapeErrors.join('; ') };
911
+ // Cross-Epic files-overlap advisory: a warning, never a refusal.
912
+ // Skipped on a dry run: createPrdBatch re-runs it on a fresh listing inside the
913
+ // create lock, so the batch never reports a warning twice.
914
+ if (!opts.dryRun && listing && filesList && filesList.length) {
915
+ extraWarnings.push(...await crossEpicFilesOverlapWarnings(filesList, input.sourcePromptId ?? null, listing.prds ?? [], remote, input.cwd));
851
916
  }
852
- if (!listing) {
853
- return { ok: false, applied: false, status: 503, error: 'fixes could not be checked: the PRD listing for this project could not be read — retry' };
917
+
918
+ // fixes: shape-checked and resolved to full NN slugs before NN allocation, so a
919
+ // refusal burns no number. Fail-closed when the listing could not be read — an
920
+ // unresolved fixes link would miscount escapes.
921
+ if (hasFixes) {
922
+ const shapeErrors = validateFixesShape(input.fixes, slug);
923
+ if (shapeErrors.length) {
924
+ return { ok: false, applied: false, status: 400, error: shapeErrors.join('; ') };
925
+ }
926
+ if (!listing) {
927
+ return { ok: false, applied: false, status: 503, error: 'fixes could not be checked: the PRD listing for this project could not be read — retry' };
928
+ }
929
+ const r = resolveFixes(input.fixes, listing.prds ?? [], { epicId: input.sourcePromptId ?? null });
930
+ if (r.errors.length) return { ok: false, applied: false, status: 400, error: r.errors.join('; ') };
931
+ extraWarnings.push(...r.warnings);
932
+ input = { ...input, fixes: r.fixes };
854
933
  }
855
- const r = resolveFixes(input.fixes, listing.prds ?? [], { epicId: input.sourcePromptId ?? null });
856
- if (r.errors.length) return { ok: false, applied: false, status: 400, error: r.errors.join('; ') };
857
- extraWarnings.push(...r.warnings);
858
- input = { ...input, fixes: r.fixes };
859
- }
860
934
 
861
- // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
862
- const nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
863
- const filenameSlug = `${nn}-${slug}`;
864
-
865
- // Fix-chain depth guard (PRD 1113): refuse a fix-of-a-fix before it's ever
866
- // written. depth >= 2 means the base job has already failed to close via
867
- // at least one prior fix attempt for reasons a repeat attempt won't
868
- // resolve — checked first so this distinct, human-escalation error still
869
- // wins over the more general fix-plan-slug guard below for that shape.
870
- const chainDepth = fixChainDepthOf(filenameSlug);
871
- if (chainDepth > FIX_CHAIN_DEPTH_CAP) {
872
- const base = baseSlugOf(filenameSlug);
873
- return {
874
- ok: false, applied: false,
875
- status: 409,
876
- error: `Fix-chain depth cap exceeded: "${base}" has already failed to close ${chainDepth} time(s) for ` +
877
- `infrastructure reasons (refusing to write "${filenameSlug}.md" at depth ${chainDepth}). Authoring a ` +
878
- 'deeper fix PRD is not the correct response — stop and surface this to a human instead of retrying again.',
879
- };
880
- }
935
+ // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
936
+ nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
937
+ filenameSlug = `${nn}-${slug}`;
938
+
939
+ // Fix-chain depth guard (PRD 1113): refuse a fix-of-a-fix before it's ever
940
+ // written. depth >= 2 means the base job has already failed to close via
941
+ // at least one prior fix attempt for reasons a repeat attempt won't
942
+ // resolve — checked first so this distinct, human-escalation error still
943
+ // wins over the more general fix-plan-slug guard below for that shape.
944
+ const chainDepth = fixChainDepthOf(filenameSlug);
945
+ if (chainDepth > FIX_CHAIN_DEPTH_CAP) {
946
+ const base = baseSlugOf(filenameSlug);
947
+ return {
948
+ ok: false, applied: false,
949
+ status: 409,
950
+ error: `Fix-chain depth cap exceeded: "${base}" has already failed to close ${chainDepth} time(s) for ` +
951
+ `infrastructure reasons (refusing to write "${filenameSlug}.md" at depth ${chainDepth}). Authoring a ` +
952
+ 'deeper fix PRD is not the correct response — stop and surface this to a human instead of retrying again.',
953
+ };
954
+ }
881
955
 
882
- // Fix-plan-slug collision guard (PRD 1131): a caller-supplied or
883
- // title-derived slug that happens to start with "fix-" collides with the
884
- // scheduler's own NN-fix-... naming convention for fix plans it authors
885
- // itself (spawnInvestigation) — and that shape carries real special-case
886
- // semantics (depth-capped auto-investigation eligibility,
887
- // commitGuardVerdict's zero-edit exemption) that a PRD authored through
888
- // this API never asked for. Refused outright, not silently renamed, same
889
- // fail-closed posture as the SLUG_HAS_NN_PREFIX_RE check above (PRD 1126:
890
- // "126-fix-plan-death-reopens-parent" was wrongly stamped
891
- // investigationDepth before it ever ran and had to be withdrawn). This
892
- // subsumes the depth-1 case the chain-depth guard above deliberately let
893
- // through (MAX_INVESTIGATION_DEPTH=1 means a first fix-plan is legitimate
894
- // — but only when spawnInvestigation authors it, never through this API).
895
- if (isFixPlanSlug(filenameSlug)) {
896
- return {
897
- ok: false, applied: false,
898
- status: 400,
899
- error: `slug "${filenameSlug}" collides with the reserved NN-fix-... fix-plan naming convention ` +
900
- '(reserved for PRDs the scheduler\'s own investigation loop authors itself). Reword the title/slug ' +
901
- 'so it does not start with "fix-" — e.g. "resolve-x" or "repair-x" instead of "fix-x".',
902
- };
903
- }
956
+ // Fix-plan-slug collision guard (PRD 1131): a caller-supplied or
957
+ // title-derived slug that happens to start with "fix-" collides with the
958
+ // scheduler's own NN-fix-... naming convention for fix plans it authors
959
+ // itself (spawnInvestigation) — and that shape carries real special-case
960
+ // semantics (depth-capped auto-investigation eligibility,
961
+ // commitGuardVerdict's zero-edit exemption) that a PRD authored through
962
+ // this API never asked for. Refused outright, not silently renamed, same
963
+ // fail-closed posture as the SLUG_HAS_NN_PREFIX_RE check above (PRD 1126:
964
+ // "126-fix-plan-death-reopens-parent" was wrongly stamped
965
+ // investigationDepth before it ever ran and had to be withdrawn). This
966
+ // subsumes the depth-1 case the chain-depth guard above deliberately let
967
+ // through (MAX_INVESTIGATION_DEPTH=1 means a first fix-plan is legitimate
968
+ // — but only when spawnInvestigation authors it, never through this API).
969
+ if (isFixPlanSlug(filenameSlug)) {
970
+ return {
971
+ ok: false, applied: false,
972
+ status: 400,
973
+ error: `slug "${filenameSlug}" collides with the reserved NN-fix-... fix-plan naming convention ` +
974
+ '(reserved for PRDs the scheduler\'s own investigation loop authors itself). Reword the title/slug ' +
975
+ 'so it does not start with "fix-" — e.g. "resolve-x" or "repair-x" instead of "fix-x".',
976
+ };
977
+ }
904
978
 
905
- // An explicit `parallelGroup` bypasses allocateParallelGroup()'s
906
- // collision-proof reservation, so re-check for an existing file at
907
- // this exact destination before writing — remote.writePrd itself has
908
- // no existence guard (by design, it doubles as the edit-in-place
909
- // path for Scheduler UI PRD edits), so "create" must not silently
910
- // clobber an existing job's PRD.
911
- const existing = opts.dryRun ? null : await remote.readPrd(filenameSlug, input.cwd);
912
- if (existing?.ok) {
913
- return { ok: false, applied: false, status: 409, error: `PRD already exists: ${filenameSlug}.md` };
914
- }
979
+ // An explicit `parallelGroup` bypasses allocateParallelGroup()'s
980
+ // collision-proof reservation, so re-check for an existing file at
981
+ // this exact destination before writing — remote.writePrd itself has
982
+ // no existence guard (by design, it doubles as the edit-in-place
983
+ // path for Scheduler UI PRD edits), so "create" must not silently
984
+ // clobber an existing job's PRD.
985
+ const existing = opts.dryRun ? null : await remote.readPrd(filenameSlug, input.cwd);
986
+ if (existing?.ok) {
987
+ return { ok: false, applied: false, status: 409, error: `PRD already exists: ${filenameSlug}.md` };
988
+ }
915
989
 
916
- // Write-time FK check (throw on write, report on read — see
917
- // prdAgentType.cjs's header): a caller-supplied agentType that doesn't
918
- // resolve to a readable persona file is rejected before anything is
919
- // written, naming the available personas. A no-op when agentType is
920
- // omitted — buildPrdBody fills in DEFAULT_PRD_AGENT_TYPE for that case,
921
- // and the default persona is trusted without a lookup.
922
- if (input.agentType) {
923
- try {
924
- await assertAgentTypeWritable(input.cwd, input.agentType);
925
- } catch (e) {
926
- return { ok: false, applied: false, status: 400, error: e?.message ?? 'invalid agentType' };
990
+ // Write-time FK check (throw on write, report on read — see
991
+ // prdAgentType.cjs's header): a caller-supplied agentType that doesn't
992
+ // resolve to a readable persona file is rejected before anything is
993
+ // written, naming the available personas. A no-op when agentType is
994
+ // omitted — buildPrdBody fills in DEFAULT_PRD_AGENT_TYPE for that case,
995
+ // and the default persona is trusted without a lookup.
996
+ if (input.agentType) {
997
+ try {
998
+ await assertAgentTypeWritable(input.cwd, input.agentType);
999
+ } catch (e) {
1000
+ return { ok: false, applied: false, status: 400, error: e?.message ?? 'invalid agentType' };
1001
+ }
927
1002
  }
928
- }
929
1003
 
930
- // Write-time FK check for dependsOn (report on read / throw on write — see
931
- // prdAgentType.cjs's header): every entry must resolve to a PRD that
932
- // actually exists in this project, using the SAME resolution rule
933
- // schedulerBatch.cjs's findBlockingDep applies at run time (exact slug,
934
- // else bare-name after stripping one leading `NN-`) — a dep that
935
- // validates here is guaranteed to be a dep findBlockingDep can actually
936
- // see later. A listPrds() read failure is skipped-with-a-warning, never a
937
- // write outage: an I/O hiccup on the read side must not block every PRD
938
- // write in the project.
939
- let depRows = null;
940
- if (input.dependsOn && input.dependsOn.length) {
941
- if (listing) {
942
- depRows = listing.prds ?? [];
943
- const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
944
- for (const dep of input.dependsOn) {
945
- if (resolveDepSlug(dep, candidateSlugs).length > 0) continue;
946
- const near = findNearMatches(dep, candidateSlugs);
947
- const suggestion = near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : '';
1004
+ // Write-time FK check for dependsOn (report on read / throw on write — see
1005
+ // prdAgentType.cjs's header): every entry must resolve to a PRD that
1006
+ // actually exists in this project, using the SAME resolution rule
1007
+ // schedulerBatch.cjs's findBlockingDep applies at run time (exact slug,
1008
+ // else bare-name after stripping one leading `NN-`) — a dep that
1009
+ // validates here is guaranteed to be a dep findBlockingDep can actually
1010
+ // see later. A listPrds() read failure is skipped-with-a-warning, never a
1011
+ // write outage: an I/O hiccup on the read side must not block every PRD
1012
+ // write in the project.
1013
+ let depRows = null;
1014
+ if (input.dependsOn && input.dependsOn.length) {
1015
+ if (listing) {
1016
+ depRows = listing.prds ?? [];
1017
+ const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
1018
+ for (const dep of input.dependsOn) {
1019
+ if (resolveDepSlug(dep, candidateSlugs).length > 0) continue;
1020
+ const near = findNearMatches(dep, candidateSlugs);
1021
+ const suggestion = near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : '';
1022
+ return {
1023
+ ok: false, applied: false,
1024
+ status: 400,
1025
+ error: `dependsOn entry "${dep}" does not resolve to any existing PRD in this project.${suggestion} ` +
1026
+ 'Pass the bare name (preferred) or the exact NN-prefixed slug of an existing PRD.',
1027
+ };
1028
+ }
1029
+ }
1030
+ }
1031
+
1032
+ // Store every dependsOn entry as the full NN slug it resolved to (queue rows keep
1033
+ // dependsOn verbatim, so a bare name would silently re-point at a later same-name
1034
+ // PRD). Batch siblings stay bare here — createPrdBatch rewrites them to the
1035
+ // sibling's allocated slug once NNs exist — and are excluded from planId
1036
+ // inheritance (they share the batch's planId).
1037
+ const batchSiblingDeps = new Set();
1038
+ if (input.dependsOn && input.dependsOn.length && depRows) {
1039
+ const resolvedDeps = resolveDependsOnToFullSlugs(input.dependsOn, depRows, {
1040
+ epicId: input.sourcePromptId ?? null,
1041
+ siblingSlugs: opts.extraDepSlugs ?? [],
1042
+ });
1043
+ for (const d of resolvedDeps.siblingDeps) batchSiblingDeps.add(d);
1044
+ extraWarnings.push(...resolvedDeps.warnings);
1045
+ input = { ...input, dependsOn: resolvedDeps.dependsOn };
1046
+ }
1047
+
1048
+ // planId is API-owned: any caller-supplied value is discarded. Inherited from the
1049
+ // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
1050
+ // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
1051
+ let planId = null;
1052
+ if (input.dependsOn && input.dependsOn.length && depRows) {
1053
+ const inherited = resolveInheritedPlanId(
1054
+ input.dependsOn.filter((d) => !batchSiblingDeps.has(d)),
1055
+ depRows,
1056
+ // Scoped only when this PRD has an Epic: an Epic-less PRD has no plan boundary to protect.
1057
+ input.sourcePromptId ? { epicId: input.sourcePromptId } : {},
1058
+ );
1059
+ planId = inherited.planId;
1060
+ if (inherited.diverged) {
1061
+ console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
1062
+ }
1063
+ }
1064
+ const inheritedPlanId = planId;
1065
+ if (!planId) planId = mintPlanId();
1066
+
1067
+ const body = buildPrdBody({ ...input, planId, gate: gateCommands, files: filesList });
1068
+
1069
+ // Read-back check (gate-and-files-in-PRD-body unit): the whole point of a
1070
+ // declared gate is that the scheduler's own reader (resolveGate/parseChain
1071
+ // in definitionOfDone.cjs) gets back exactly what was declared. A stray
1072
+ // ```gate fence elsewhere in the body (goal/notes/criteria/out-of-scope)
1073
+ // would otherwise win — readExplicitGate takes the FIRST fence in the
1074
+ // text — and the scheduler would silently re-run the wrong gate. Caught
1075
+ // here, before the write, rather than discovered later from a job log.
1076
+ if (gateCommands) {
1077
+ const expectedSource = gateCommands.length === 1 && isNoneGate(gateCommands[0]) ? 'none' : 'explicit';
1078
+ const expectedSequence = expectedSource === 'none' ? [] : gateCommands.flatMap(parseChain);
1079
+ const resolved = resolveGate(body);
1080
+ const matches = resolved.source === expectedSource
1081
+ && JSON.stringify(resolved.sequence) === JSON.stringify(expectedSequence);
1082
+ if (!matches) {
948
1083
  return {
949
1084
  ok: false, applied: false,
950
1085
  status: 400,
951
- error: `dependsOn entry "${dep}" does not resolve to any existing PRD in this project.${suggestion} ` +
952
- 'Pass the bare name (preferred) or the exact NN-prefixed slug of an existing PRD.',
1086
+ error: 'The PRD text already holds a gate fence (three backticks + gate), so the scheduler would read '
1087
+ + 'the wrong gate. Remove it from the goal, implementation notes, acceptance criteria, out of scope '
1088
+ + 'or files, and call again.',
953
1089
  };
954
1090
  }
955
1091
  }
956
- }
957
-
958
- // Store every dependsOn entry as the full NN slug it resolved to (queue rows keep
959
- // dependsOn verbatim, so a bare name would silently re-point at a later same-name
960
- // PRD). Batch siblings stay bare here — createPrdBatch rewrites them to the
961
- // sibling's allocated slug once NNs exist — and are excluded from planId
962
- // inheritance (they share the batch's planId).
963
- const batchSiblingDeps = new Set();
964
- if (input.dependsOn && input.dependsOn.length && depRows) {
965
- const resolvedDeps = resolveDependsOnToFullSlugs(input.dependsOn, depRows, {
966
- epicId: input.sourcePromptId ?? null,
967
- siblingSlugs: opts.extraDepSlugs ?? [],
968
- });
969
- for (const d of resolvedDeps.siblingDeps) batchSiblingDeps.add(d);
970
- extraWarnings.push(...resolvedDeps.warnings);
971
- input = { ...input, dependsOn: resolvedDeps.dependsOn };
972
- }
973
1092
 
974
- // planId is API-owned: any caller-supplied value is discarded. Inherited from the
975
- // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
976
- // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
977
- let planId = null;
978
- if (input.dependsOn && input.dependsOn.length && depRows) {
979
- const inherited = resolveInheritedPlanId(
980
- input.dependsOn.filter((d) => !batchSiblingDeps.has(d)),
981
- depRows,
982
- // Scoped only when this PRD has an Epic: an Epic-less PRD has no plan boundary to protect.
983
- input.sourcePromptId ? { epicId: input.sourcePromptId } : {},
984
- );
985
- planId = inherited.planId;
986
- if (inherited.diverged) {
987
- console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
988
- }
989
- }
990
- const inheritedPlanId = planId;
991
- if (!planId) planId = mintPlanId();
992
-
993
- const body = buildPrdBody({ ...input, planId, gate: gateCommands, files: filesList });
994
-
995
- // Read-back check (gate-and-files-in-PRD-body unit): the whole point of a
996
- // declared gate is that the scheduler's own reader (resolveGate/parseChain
997
- // in definitionOfDone.cjs) gets back exactly what was declared. A stray
998
- // ```gate fence elsewhere in the body (goal/notes/criteria/out-of-scope)
999
- // would otherwise win — readExplicitGate takes the FIRST fence in the
1000
- // text — and the scheduler would silently re-run the wrong gate. Caught
1001
- // here, before the write, rather than discovered later from a job log.
1002
- if (gateCommands) {
1003
- const expectedSource = gateCommands.length === 1 && isNoneGate(gateCommands[0]) ? 'none' : 'explicit';
1004
- const expectedSequence = expectedSource === 'none' ? [] : gateCommands.flatMap(parseChain);
1005
- const resolved = resolveGate(body);
1006
- const matches = resolved.source === expectedSource
1007
- && JSON.stringify(resolved.sequence) === JSON.stringify(expectedSequence);
1008
- if (!matches) {
1093
+ if (opts.dryRun) {
1009
1094
  return {
1010
- ok: false, applied: false,
1011
- status: 400,
1012
- error: 'The PRD text already holds a gate fence (three backticks + gate), so the scheduler would read '
1013
- + 'the wrong gate. Remove it from the goal, implementation notes, acceptance criteria, out of scope '
1014
- + 'or files, and call again.',
1095
+ ok: true, dryRun: true, slug, input, gateCommands, filesList,
1096
+ inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
1015
1097
  };
1016
1098
  }
1017
- }
1018
1099
 
1019
- if (opts.dryRun) {
1020
- return {
1021
- ok: true, dryRun: true, slug, input, gateCommands, filesList,
1022
- inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
1023
- };
1024
- }
1025
-
1026
- const writeResult = await remote.writePrd(filenameSlug, body, input.cwd);
1027
- if (!writeResult?.ok) {
1028
- return { ok: false, applied: false, status: 500, error: writeResult?.error ?? 'write failed' };
1029
- }
1100
+ writeResult = await remote.writePrd(filenameSlug, body, input.cwd);
1101
+ if (!writeResult?.ok) {
1102
+ return { ok: false, applied: false, status: 500, error: writeResult?.error ?? 'write failed' };
1103
+ }
1104
+ return null;
1105
+ };
1106
+ const early = opts.dryRun ? await createPhase() : await withProjectCreateLock(cwd, createPhase);
1107
+ if (early) return early;
1030
1108
 
1031
1109
  // Trace-back point for "who/what created this PRD" (auditLog.cjs) — every
1032
1110
  // PRD write, whether from the admin/MCP route or the renderer's chat:create-prd
@@ -1101,6 +1179,9 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
1101
1179
  commands: gateCommands || [],
1102
1180
  },
1103
1181
  files: filesList || [],
1182
+ // The preflight actually written (null = no key) — the MCP server checks
1183
+ // it against what the caller sent, so a dropped key is never silent.
1184
+ preflight: input.preflight || null,
1104
1185
  // Advisory only (PRD 1403 sizing warnings + gate-and-files-in-PRD-body
1105
1186
  // absent/none-gate warnings) — never blocks the write. See prdSizing.cjs
1106
1187
  // and prdGateFiles.cjs.
@@ -1110,6 +1191,19 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
1110
1191
 
1111
1192
  const PRD_BATCH_MAX = 40;
1112
1193
 
1194
+ /**
1195
+ * Per-project PRD-create lock (2026-11-24 Bilko 2001/2005: two Epics' batches
1196
+ * validated against listings read before either wrote, then both wrote the same
1197
+ * bare slug). Every PRD create runs in the app's main process (admin routes,
1198
+ * chat:create-prd IPC, in-process mints), so an in-process lock serializes them
1199
+ * all. Keyed by the resolved project cwd (p.input.cwd, already normalized from a
1200
+ * worktree path to the main checkout). Never activeIndexPath(cwd): remote.writePrd
1201
+ * -> ensureEpic takes that lock, so sharing it would deadlock.
1202
+ */
1203
+ function withProjectCreateLock(cwd, task) {
1204
+ return withPathLock(`${cwd}\u0000prd-create`, task);
1205
+ }
1206
+
1113
1207
  /**
1114
1208
  * Create several PRDs all-or-nothing. Every entry goes through createPrd's own
1115
1209
  * validation (dry run: no NN, no file); `dependsOn` may also name other entries
@@ -1196,34 +1290,98 @@ async function createPrdBatch(inputs, remote, opts = {}) {
1196
1290
  } catch (e) { console.warn(`[prdCreate] batch rollback could not remove ${w.filenameSlug}: ${e?.message ?? e}`); }
1197
1291
  }
1198
1292
  };
1199
- // Allocate every NN before writing anything, so a dep on a LATER sibling can be
1200
- // rewritten to that sibling's full `${nn}-${slug}` too. Burned numbers on an
1201
- // allocation failure leave a gap, never an inconsistency.
1202
- const nns = [];
1203
- try {
1204
- for (const p of prepared) nns.push(await remote.allocateParallelGroup(p.input.cwd));
1205
- } catch (e) {
1206
- return fail([{ index: nns.length, slug: prepared[nns.length]?.slug ?? null, error: `NN allocation failed: ${e?.message ?? e}` }]);
1207
- }
1208
- const fullDeps = (deps) => (deps && deps.length
1209
- ? Array.from(new Set(deps.map((d) => (firstIndex.has(d) ? `${nns[firstIndex.get(d)]}-${d}` : d))))
1210
- : deps);
1211
- for (let i = 0; i < prepared.length; i++) {
1212
- const p = prepared[i];
1213
- let nn; let filenameSlug;
1293
+ const projectCwd = prepared[0].input.cwd;
1294
+ const committed = await withProjectCreateLock(projectCwd, async () => {
1295
+ // Commit-time re-check on a FRESH listing, inside the lock: the validation pass
1296
+ // read its listing 15-25 s ago on a busy machine, and another Epic's create may
1297
+ // have written the same bare slug since. A read failure skips the re-check
1298
+ // (never a write outage).
1299
+ let freshListing = null;
1214
1300
  try {
1215
- nn = nns[i];
1216
- filenameSlug = `${nn}-${p.slug}`;
1217
- const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
1218
- const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
1219
- if (!w?.ok) throw new Error(w?.error ?? 'write failed');
1220
- written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
1221
- results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, warnings: p.warnings });
1301
+ freshListing = await remote.listPrds({ cwd: projectCwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER, fresh: true });
1222
1302
  } catch (e) {
1223
- await rollback();
1224
- return fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]);
1303
+ console.warn(`[prdCreate] batch fresh listPrds failed (commit-time duplicate + files-overlap re-checks skipped): ${e?.message ?? e}`);
1304
+ freshListing = null;
1225
1305
  }
1226
- }
1306
+ const overlapWarnings = prepared.map(() => []);
1307
+ if (freshListing) {
1308
+ const freshRows = freshListing.prds ?? [];
1309
+ // Same-Epic rows already in the validation snapshot were judged by the
1310
+ // validation pass's own-Epic directory scan; only rows written since then
1311
+ // (a concurrent create in this Epic) are refused here.
1312
+ let seenAtValidation = new Set();
1313
+ try {
1314
+ const v = listingCache.promise ? await listingCache.promise : null;
1315
+ seenAtValidation = new Set((v?.prds ?? []).map((r) => r?.slug));
1316
+ } catch { /* validation read failed — every same-Epic row counts as new */ }
1317
+ const refused = [];
1318
+ for (let i = 0; i < prepared.length; i++) {
1319
+ const p = prepared[i];
1320
+ const epicId = p.input.sourcePromptId ?? null;
1321
+ if (opts.internalMint !== true) {
1322
+ const dups = findCrossEpicDuplicates(p.slug, epicId, freshRows);
1323
+ if (dups.length) {
1324
+ const allowed = new Set(Array.isArray(p.input.allowDuplicateOf) ? p.input.allowDuplicateOf : []);
1325
+ if (!dups.every((r) => allowed.has(r.slug))) {
1326
+ refused.push({ index: i, slug: p.slug, error: crossEpicDuplicateError(p.slug, dups), status: 409 });
1327
+ continue;
1328
+ }
1329
+ p.duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
1330
+ } else {
1331
+ p.duplicateAllowed = null;
1332
+ }
1333
+ }
1334
+ if (epicId != null && !isFixPlanSlug(`0-${p.slug}`)) {
1335
+ const target = bareSlug(p.slug);
1336
+ const same = freshRows.find((r) => r && typeof r.slug === 'string' && r.epicId === epicId
1337
+ && !seenAtValidation.has(r.slug) && bareSlug(r.slug) === target);
1338
+ if (same) {
1339
+ refused.push({ index: i, slug: p.slug, error: `slug "${p.slug}" already exists in this Epic as "${same.slug}"`, status: 409 });
1340
+ continue;
1341
+ }
1342
+ }
1343
+ if (p.filesList && p.filesList.length) {
1344
+ overlapWarnings[i] = await crossEpicFilesOverlapWarnings(p.filesList, epicId, freshRows, remote, projectCwd);
1345
+ }
1346
+ }
1347
+ if (refused.length) return { failed: fail(refused) };
1348
+ }
1349
+ // Allocate every NN before writing anything, so a dep on a LATER sibling can be
1350
+ // rewritten to that sibling's full `${nn}-${slug}` too. Burned numbers on an
1351
+ // allocation failure leave a gap, never an inconsistency.
1352
+ const nns = [];
1353
+ try {
1354
+ for (const p of prepared) nns.push(await remote.allocateParallelGroup(p.input.cwd));
1355
+ } catch (e) {
1356
+ return { failed: fail([{ index: nns.length, slug: prepared[nns.length]?.slug ?? null, error: `NN allocation failed: ${e?.message ?? e}` }]) };
1357
+ }
1358
+ const fullDeps = (deps) => (deps && deps.length
1359
+ ? Array.from(new Set(deps.map((d) => (firstIndex.has(d) ? `${nns[firstIndex.get(d)]}-${d}` : d))))
1360
+ : deps);
1361
+ for (let i = 0; i < prepared.length; i++) {
1362
+ const p = prepared[i];
1363
+ let nn; let filenameSlug;
1364
+ try {
1365
+ nn = nns[i];
1366
+ filenameSlug = `${nn}-${p.slug}`;
1367
+ const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
1368
+ // A validated preflight must reach the file (PRD 3805 ran unheld when one
1369
+ // was lost); a body without the line rolls the whole batch back.
1370
+ if (p.input.preflight && !/^preflight: /m.test(body)) throw new Error('preflight was not written to the PRD frontmatter');
1371
+ const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
1372
+ if (!w?.ok) throw new Error(w?.error ?? 'write failed');
1373
+ written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
1374
+ results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, preflight: p.input.preflight || null, warnings: [...p.warnings, ...overlapWarnings[i]] });
1375
+ } catch (e) {
1376
+ await rollback();
1377
+ return { failed: fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]) };
1378
+ }
1379
+ }
1380
+ return { failed: null };
1381
+ });
1382
+ // Audit rows, telemetry and the bounded reconcile wait run after the lock is
1383
+ // released, so a 2 s reconcile never holds other creates.
1384
+ if (committed.failed) return committed.failed;
1227
1385
 
1228
1386
  for (let i = 0; i < prepared.length; i++) {
1229
1387
  const p = prepared[i];
@@ -1301,6 +1459,7 @@ function registerAdminRoute(adminHttp, remote) {
1301
1459
  note: result.note,
1302
1460
  gate: result.gate,
1303
1461
  files: result.files,
1462
+ preflight: result.preflight ?? null,
1304
1463
  warnings: result.warnings,
1305
1464
  });
1306
1465
  });