claude-code-session-manager 0.142.0 → 0.144.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -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');
@@ -35,6 +35,7 @@ const { isIncomplete, resolveChainTerminals, isValidPlanId, mintPlanId, resolveI
35
35
  const { splitFrontmatter, PRD_EFFORT_LEVELS, formatQuotedInlineList } = require('./prdFrontmatter.cjs');
36
36
  const { parseRule: parseToolRiskRule } = require('../claude/toolRiskMarks.cjs');
37
37
  const { normalizePreflight } = require('../scheduler/preflightCheck.cjs');
38
+ const { qualifiesForReview, planReviewEnabled } = require('../../scheduler/planReviewHold.cjs');
38
39
 
39
40
  // Cap on riskTools entries — mirrors ipcSchemas.cjs RiskToolsSchema.
40
41
  const RISK_TOOLS_MAX = 20;
@@ -77,6 +78,24 @@ function normalizeRiskTools(value) {
77
78
  return { ok: true, value: seen };
78
79
  }
79
80
  const { sizingWarnings } = require('./prdSizing.cjs');
81
+ const { sandboxWarnings } = require('./prdSandboxWarnings.cjs');
82
+ const { mcpReachWarnings } = require('./prdMcpReachWarnings.cjs');
83
+
84
+ /** Real deps for mcpReachWarnings: persona servers resolved the way the scheduler snapshot does. Never throws. */
85
+ const mcpReachDeps = {
86
+ resolve: (o) => require('../claude/headlessMcpServers.cjs').resolveHeadlessMcpServers(o),
87
+ readPersonaServers: (input) => {
88
+ try {
89
+ const { readOverlayAwarePersona, DEFAULT_PRD_AGENT_TYPE: dflt } = require('../claude/agentModelResolve.cjs');
90
+ const { parseTools, parseCapabilityList } = require('../../agentLibrary.cjs');
91
+ const { resolvedMcpServerNames } = require('../claude/personaToolScope.cjs');
92
+ const fm = (readOverlayAwarePersona(input.agentType || dflt, { cwd: input.cwd }) || {}).fm;
93
+ if (!fm) return null;
94
+ const tools = parseTools(typeof fm.tools === 'string' ? fm.tools : '');
95
+ return resolvedMcpServerNames(tools, parseCapabilityList(fm.mcpServers));
96
+ } catch { return null; }
97
+ },
98
+ };
80
99
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
81
100
  const { execGit } = require('../git/gitExec.cjs');
82
101
  const { extractRepoPathCandidates, worktreeReachWarnings } = require('./prdWorktreeReach.cjs');
@@ -137,7 +156,7 @@ function isValidMacroId(id) {
137
156
  function buildPrdBody(input) {
138
157
  const {
139
158
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
140
- implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, voiceId, riskTools, preflight,
159
+ implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, voiceId, riskTools, preflight, planReview,
141
160
  gate, files, budgetExempt, fixes,
142
161
  } = input;
143
162
  // Structured criteria (prdCriteria.cjs): createPrd() normalizes once and
@@ -206,6 +225,7 @@ function buildPrdBody(input) {
206
225
  // Precondition command — validated by createPrd() via normalizePreflightField.
207
226
  // JSON-string form, matching prdFrontmatter.cjs's serializer.
208
227
  if (typeof preflight === 'string' && preflight) fmLines.push(`preflight: ${JSON.stringify(preflight)}`);
228
+ if (planReview === 'required') fmLines.push('planReview: required');
209
229
  if (quietMachine === true) fmLines.push('quietMachine: true');
210
230
  // Budget exemption is for a sweep validator that cannot be split further;
211
231
  // every other caller's budgetExempt is ignored.
@@ -440,16 +460,22 @@ function crossEpicDuplicateError(slug, dups) {
440
460
  * Cross-Epic files-overlap advisory (2026-11-22 Self stall: 1047 and 1056 also
441
461
  * declared the same files). Dispatch already serializes overlapping files, so
442
462
  * this only WARNS — never refuses. Candidates: listing rows of another Epic
443
- * whose status is pending/running/investigating. A row's `files` is used when
463
+ * whose status is pending/running/investigating, plus live (not archived) rows
464
+ * whose status is null — a PRD file written moments ago has no queue row until
465
+ * the next reconcile pass, so the listing gives it status null (2026-11-24
466
+ * Bilko: 2005 named the same files as 2001, unreconciled, and got no warning).
467
+ * Archived, completed and cancelled rows never warn. A row's `files` is used when
444
468
  * present, else its `# Files` section is read via remote.readPrd + the shared
445
469
  * parseFilesSection. Overlap uses the scheduler's own filesOverlap rule.
446
470
  */
447
471
  const OVERLAP_ACTIVE_STATUSES = new Set(['pending', 'running', 'investigating']);
472
+ const isOverlapCandidate = (r) => OVERLAP_ACTIVE_STATUSES.has(r.status)
473
+ || (r.status == null && r.archived !== true);
448
474
  async function crossEpicFilesOverlapWarnings(newFiles, epicId, rows, remote, cwd) {
449
475
  if (!Array.isArray(newFiles) || !newFiles.length || !Array.isArray(rows)) return [];
450
476
  const warnings = [];
451
477
  for (const r of rows) {
452
- if (!r || typeof r.slug !== 'string' || !OVERLAP_ACTIVE_STATUSES.has(r.status)) continue;
478
+ if (!r || typeof r.slug !== 'string' || !isOverlapCandidate(r)) continue;
453
479
  if (r.epicId == null || r.epicId === '' || r.epicId === (epicId ?? null)) continue;
454
480
  let otherFiles = Array.isArray(r.files) ? r.files : null;
455
481
  if (!otherFiles) {
@@ -571,10 +597,14 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
571
597
  // caller didn't already give an explicit dependsOn (that already fixes
572
598
  // its position in some chain) — joining an Epic whose sourcePromptId this
573
599
  // PRD shares. See prdDisposition.cjs's header for the full contract.
600
+ // Slugs this pre-lock read saw: the in-lock same-Epic re-check refuses only rows
601
+ // written since (null = no pre-lock read, every same-Epic row counts as new).
602
+ let seenBeforeLock = null;
574
603
  if (input.sourcePromptId && (!input.dependsOn || input.dependsOn.length === 0)) {
575
604
  let epicRows = [];
576
605
  try {
577
606
  const listing = await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
607
+ seenBeforeLock = new Set((listing?.prds ?? []).map((r) => r?.slug));
578
608
  epicRows = (listing?.prds ?? []).filter((p) => p.sourcePromptId === input.sourcePromptId);
579
609
  } catch (e) {
580
610
  console.warn(`[prdCreate] disposition resolution skipped (listPrds failed): ${e?.message ?? e}`);
@@ -835,227 +865,266 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
835
865
  }
836
866
  }
837
867
 
838
- // One full listing (slug/epicId/status per live + archived PRD) serves both the
839
- // cross-Epic duplicate guard below and the dependsOn FK check after NN allocation.
840
- // A read failure is skipped-with-a-warning, never a write outage.
841
- const needCrossEpicGuard = opts.internalMint !== true;
842
- let listing = null;
843
- const hasFixes = input.fixes !== undefined && input.fixes !== null;
844
- if (needCrossEpicGuard || hasFixes || (input.dependsOn && input.dependsOn.length) || (filesList && filesList.length)) {
845
- try {
846
- listing = opts.listingCache
847
- ? await (opts.listingCache.promise ??= remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER }))
848
- : await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
849
- } catch (e) {
850
- console.warn(`[prdCreate] listPrds failed (cross-Epic duplicate + dependsOn checks skipped): ${e?.message ?? e}`);
851
- listing = null;
868
+ // Everything from the listing read through remote.writePrd runs as one phase.
869
+ // A real create runs it inside the per-project create lock on a FRESH listing
870
+ // (2026-11-24 Bilko 2001/2005: a create read its listing, awaited NN
871
+ // allocation, and wrote while another Epic's create wrote the same bare slug).
872
+ // A dry run (createPrdBatch's validate pass) takes no lock; the batch re-checks
873
+ // inside the lock itself. The phase returns an early-refusal / dry-run result,
874
+ // or null once the file is written (writeResult, nn, filenameSlug,
875
+ // duplicateAllowed and input are set on the closure).
876
+ let duplicateAllowed = null;
877
+ let nn;
878
+ let filenameSlug;
879
+ let writeResult;
880
+ const createPhase = async () => {
881
+ // One full listing (slug/epicId/status per live + archived PRD) serves both the
882
+ // cross-Epic duplicate guard below and the dependsOn FK check after NN allocation.
883
+ // A read failure is skipped-with-a-warning, never a write outage.
884
+ const needCrossEpicGuard = opts.internalMint !== true;
885
+ let listing = null;
886
+ const hasFixes = input.fixes !== undefined && input.fixes !== null;
887
+ // A real create always reads: the in-lock same-Epic re-check must not depend
888
+ // on which optional fields (fixes/dependsOn/files) the caller sends.
889
+ if (!opts.dryRun || needCrossEpicGuard || hasFixes || (input.dependsOn && input.dependsOn.length) || (filesList && filesList.length)) {
890
+ try {
891
+ const q = { cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER };
892
+ if (!opts.dryRun) listing = await remote.listPrds({ ...q, fresh: true });
893
+ else if (opts.listingCache) listing = await (opts.listingCache.promise ??= remote.listPrds(q));
894
+ else listing = await remote.listPrds(q);
895
+ } catch (e) {
896
+ console.warn(`[prdCreate] listPrds failed (cross-Epic duplicate + dependsOn checks skipped): ${e?.message ?? e}`);
897
+ listing = null;
898
+ }
852
899
  }
853
- }
854
900
 
855
- // Cross-Epic duplicate guard: refused before NN allocation so it burns no number.
856
- let duplicateAllowed = null;
857
- if (needCrossEpicGuard && listing) {
858
- const dups = findCrossEpicDuplicates(slug, input.sourcePromptId ?? null, listing.prds ?? []);
859
- if (dups.length) {
860
- const allowed = new Set(Array.isArray(input.allowDuplicateOf) ? input.allowDuplicateOf : []);
861
- if (!dups.every((r) => allowed.has(r.slug))) {
862
- return { ok: false, applied: false, status: 409, error: crossEpicDuplicateError(slug, dups) };
901
+ // Same-Epic re-check on the fresh listing, inside the lock: a same-Epic create
902
+ // that wrote this bare slug since the pre-lock reads is refused here,
903
+ // before NN allocation, with the directory scan's own wording.
904
+ if (!opts.dryRun && listing && input.sourcePromptId && !isFixPlanSlug(`0-${slug}`)) {
905
+ const target = bareSlug(slug);
906
+ const same = (listing.prds ?? []).find((r) => r && typeof r.slug === 'string'
907
+ && r.epicId === input.sourcePromptId && !(seenBeforeLock && seenBeforeLock.has(r.slug))
908
+ && bareSlug(r.slug) === target);
909
+ if (same) {
910
+ return {
911
+ ok: false, applied: false,
912
+ status: 409,
913
+ error: `A PRD with slug "${slug}" already exists in this Epic as "${same.slug}.md". Its work may already have landed. ` +
914
+ 'Use scheduler_update_prd / scheduler_reset_job on it, or pick a distinct slug.',
915
+ };
863
916
  }
864
- duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
865
917
  }
866
- }
867
918
 
868
- // Cross-Epic files-overlap advisory: a warning, never a refusal.
869
- if (listing && filesList && filesList.length) {
870
- extraWarnings.push(...await crossEpicFilesOverlapWarnings(filesList, input.sourcePromptId ?? null, listing.prds ?? [], remote, input.cwd));
871
- }
919
+ // Cross-Epic duplicate guard: refused before NN allocation so it burns no number.
920
+ if (needCrossEpicGuard && listing) {
921
+ const dups = findCrossEpicDuplicates(slug, input.sourcePromptId ?? null, listing.prds ?? []);
922
+ if (dups.length) {
923
+ const allowed = new Set(Array.isArray(input.allowDuplicateOf) ? input.allowDuplicateOf : []);
924
+ if (!dups.every((r) => allowed.has(r.slug))) {
925
+ return { ok: false, applied: false, status: 409, error: crossEpicDuplicateError(slug, dups) };
926
+ }
927
+ duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
928
+ }
929
+ }
872
930
 
873
- // fixes: shape-checked and resolved to full NN slugs before NN allocation, so a
874
- // refusal burns no number. Fail-closed when the listing could not be read — an
875
- // unresolved fixes link would miscount escapes.
876
- if (hasFixes) {
877
- const shapeErrors = validateFixesShape(input.fixes, slug);
878
- if (shapeErrors.length) {
879
- return { ok: false, applied: false, status: 400, error: shapeErrors.join('; ') };
931
+ // Cross-Epic files-overlap advisory: a warning, never a refusal.
932
+ // Skipped on a dry run: createPrdBatch re-runs it on a fresh listing inside the
933
+ // create lock, so the batch never reports a warning twice.
934
+ if (!opts.dryRun && listing && filesList && filesList.length) {
935
+ extraWarnings.push(...await crossEpicFilesOverlapWarnings(filesList, input.sourcePromptId ?? null, listing.prds ?? [], remote, input.cwd));
880
936
  }
881
- if (!listing) {
882
- return { ok: false, applied: false, status: 503, error: 'fixes could not be checked: the PRD listing for this project could not be read — retry' };
937
+
938
+ // fixes: shape-checked and resolved to full NN slugs before NN allocation, so a
939
+ // refusal burns no number. Fail-closed when the listing could not be read — an
940
+ // unresolved fixes link would miscount escapes.
941
+ if (hasFixes) {
942
+ const shapeErrors = validateFixesShape(input.fixes, slug);
943
+ if (shapeErrors.length) {
944
+ return { ok: false, applied: false, status: 400, error: shapeErrors.join('; ') };
945
+ }
946
+ if (!listing) {
947
+ return { ok: false, applied: false, status: 503, error: 'fixes could not be checked: the PRD listing for this project could not be read — retry' };
948
+ }
949
+ const r = resolveFixes(input.fixes, listing.prds ?? [], { epicId: input.sourcePromptId ?? null });
950
+ if (r.errors.length) return { ok: false, applied: false, status: 400, error: r.errors.join('; ') };
951
+ extraWarnings.push(...r.warnings);
952
+ input = { ...input, fixes: r.fixes };
883
953
  }
884
- const r = resolveFixes(input.fixes, listing.prds ?? [], { epicId: input.sourcePromptId ?? null });
885
- if (r.errors.length) return { ok: false, applied: false, status: 400, error: r.errors.join('; ') };
886
- extraWarnings.push(...r.warnings);
887
- input = { ...input, fixes: r.fixes };
888
- }
889
954
 
890
- // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
891
- const nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
892
- const filenameSlug = `${nn}-${slug}`;
893
-
894
- // Fix-chain depth guard (PRD 1113): refuse a fix-of-a-fix before it's ever
895
- // written. depth >= 2 means the base job has already failed to close via
896
- // at least one prior fix attempt for reasons a repeat attempt won't
897
- // resolve — checked first so this distinct, human-escalation error still
898
- // wins over the more general fix-plan-slug guard below for that shape.
899
- const chainDepth = fixChainDepthOf(filenameSlug);
900
- if (chainDepth > FIX_CHAIN_DEPTH_CAP) {
901
- const base = baseSlugOf(filenameSlug);
902
- return {
903
- ok: false, applied: false,
904
- status: 409,
905
- error: `Fix-chain depth cap exceeded: "${base}" has already failed to close ${chainDepth} time(s) for ` +
906
- `infrastructure reasons (refusing to write "${filenameSlug}.md" at depth ${chainDepth}). Authoring a ` +
907
- 'deeper fix PRD is not the correct response — stop and surface this to a human instead of retrying again.',
908
- };
909
- }
955
+ // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
956
+ nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
957
+ filenameSlug = `${nn}-${slug}`;
958
+
959
+ // Fix-chain depth guard (PRD 1113): refuse a fix-of-a-fix before it's ever
960
+ // written. depth >= 2 means the base job has already failed to close via
961
+ // at least one prior fix attempt for reasons a repeat attempt won't
962
+ // resolve — checked first so this distinct, human-escalation error still
963
+ // wins over the more general fix-plan-slug guard below for that shape.
964
+ const chainDepth = fixChainDepthOf(filenameSlug);
965
+ if (chainDepth > FIX_CHAIN_DEPTH_CAP) {
966
+ const base = baseSlugOf(filenameSlug);
967
+ return {
968
+ ok: false, applied: false,
969
+ status: 409,
970
+ error: `Fix-chain depth cap exceeded: "${base}" has already failed to close ${chainDepth} time(s) for ` +
971
+ `infrastructure reasons (refusing to write "${filenameSlug}.md" at depth ${chainDepth}). Authoring a ` +
972
+ 'deeper fix PRD is not the correct response — stop and surface this to a human instead of retrying again.',
973
+ };
974
+ }
910
975
 
911
- // Fix-plan-slug collision guard (PRD 1131): a caller-supplied or
912
- // title-derived slug that happens to start with "fix-" collides with the
913
- // scheduler's own NN-fix-... naming convention for fix plans it authors
914
- // itself (spawnInvestigation) — and that shape carries real special-case
915
- // semantics (depth-capped auto-investigation eligibility,
916
- // commitGuardVerdict's zero-edit exemption) that a PRD authored through
917
- // this API never asked for. Refused outright, not silently renamed, same
918
- // fail-closed posture as the SLUG_HAS_NN_PREFIX_RE check above (PRD 1126:
919
- // "126-fix-plan-death-reopens-parent" was wrongly stamped
920
- // investigationDepth before it ever ran and had to be withdrawn). This
921
- // subsumes the depth-1 case the chain-depth guard above deliberately let
922
- // through (MAX_INVESTIGATION_DEPTH=1 means a first fix-plan is legitimate
923
- // — but only when spawnInvestigation authors it, never through this API).
924
- if (isFixPlanSlug(filenameSlug)) {
925
- return {
926
- ok: false, applied: false,
927
- status: 400,
928
- error: `slug "${filenameSlug}" collides with the reserved NN-fix-... fix-plan naming convention ` +
929
- '(reserved for PRDs the scheduler\'s own investigation loop authors itself). Reword the title/slug ' +
930
- 'so it does not start with "fix-" — e.g. "resolve-x" or "repair-x" instead of "fix-x".',
931
- };
932
- }
976
+ // Fix-plan-slug collision guard (PRD 1131): a caller-supplied or
977
+ // title-derived slug that happens to start with "fix-" collides with the
978
+ // scheduler's own NN-fix-... naming convention for fix plans it authors
979
+ // itself (spawnInvestigation) — and that shape carries real special-case
980
+ // semantics (depth-capped auto-investigation eligibility,
981
+ // commitGuardVerdict's zero-edit exemption) that a PRD authored through
982
+ // this API never asked for. Refused outright, not silently renamed, same
983
+ // fail-closed posture as the SLUG_HAS_NN_PREFIX_RE check above (PRD 1126:
984
+ // "126-fix-plan-death-reopens-parent" was wrongly stamped
985
+ // investigationDepth before it ever ran and had to be withdrawn). This
986
+ // subsumes the depth-1 case the chain-depth guard above deliberately let
987
+ // through (MAX_INVESTIGATION_DEPTH=1 means a first fix-plan is legitimate
988
+ // — but only when spawnInvestigation authors it, never through this API).
989
+ if (isFixPlanSlug(filenameSlug)) {
990
+ return {
991
+ ok: false, applied: false,
992
+ status: 400,
993
+ error: `slug "${filenameSlug}" collides with the reserved NN-fix-... fix-plan naming convention ` +
994
+ '(reserved for PRDs the scheduler\'s own investigation loop authors itself). Reword the title/slug ' +
995
+ 'so it does not start with "fix-" — e.g. "resolve-x" or "repair-x" instead of "fix-x".',
996
+ };
997
+ }
933
998
 
934
- // An explicit `parallelGroup` bypasses allocateParallelGroup()'s
935
- // collision-proof reservation, so re-check for an existing file at
936
- // this exact destination before writing — remote.writePrd itself has
937
- // no existence guard (by design, it doubles as the edit-in-place
938
- // path for Scheduler UI PRD edits), so "create" must not silently
939
- // clobber an existing job's PRD.
940
- const existing = opts.dryRun ? null : await remote.readPrd(filenameSlug, input.cwd);
941
- if (existing?.ok) {
942
- return { ok: false, applied: false, status: 409, error: `PRD already exists: ${filenameSlug}.md` };
943
- }
999
+ // An explicit `parallelGroup` bypasses allocateParallelGroup()'s
1000
+ // collision-proof reservation, so re-check for an existing file at
1001
+ // this exact destination before writing — remote.writePrd itself has
1002
+ // no existence guard (by design, it doubles as the edit-in-place
1003
+ // path for Scheduler UI PRD edits), so "create" must not silently
1004
+ // clobber an existing job's PRD.
1005
+ const existing = opts.dryRun ? null : await remote.readPrd(filenameSlug, input.cwd);
1006
+ if (existing?.ok) {
1007
+ return { ok: false, applied: false, status: 409, error: `PRD already exists: ${filenameSlug}.md` };
1008
+ }
944
1009
 
945
- // Write-time FK check (throw on write, report on read — see
946
- // prdAgentType.cjs's header): a caller-supplied agentType that doesn't
947
- // resolve to a readable persona file is rejected before anything is
948
- // written, naming the available personas. A no-op when agentType is
949
- // omitted — buildPrdBody fills in DEFAULT_PRD_AGENT_TYPE for that case,
950
- // and the default persona is trusted without a lookup.
951
- if (input.agentType) {
952
- try {
953
- await assertAgentTypeWritable(input.cwd, input.agentType);
954
- } catch (e) {
955
- return { ok: false, applied: false, status: 400, error: e?.message ?? 'invalid agentType' };
1010
+ // Write-time FK check (throw on write, report on read — see
1011
+ // prdAgentType.cjs's header): a caller-supplied agentType that doesn't
1012
+ // resolve to a readable persona file is rejected before anything is
1013
+ // written, naming the available personas. A no-op when agentType is
1014
+ // omitted — buildPrdBody fills in DEFAULT_PRD_AGENT_TYPE for that case,
1015
+ // and the default persona is trusted without a lookup.
1016
+ if (input.agentType) {
1017
+ try {
1018
+ await assertAgentTypeWritable(input.cwd, input.agentType);
1019
+ } catch (e) {
1020
+ return { ok: false, applied: false, status: 400, error: e?.message ?? 'invalid agentType' };
1021
+ }
956
1022
  }
957
- }
958
1023
 
959
- // Write-time FK check for dependsOn (report on read / throw on write — see
960
- // prdAgentType.cjs's header): every entry must resolve to a PRD that
961
- // actually exists in this project, using the SAME resolution rule
962
- // schedulerBatch.cjs's findBlockingDep applies at run time (exact slug,
963
- // else bare-name after stripping one leading `NN-`) — a dep that
964
- // validates here is guaranteed to be a dep findBlockingDep can actually
965
- // see later. A listPrds() read failure is skipped-with-a-warning, never a
966
- // write outage: an I/O hiccup on the read side must not block every PRD
967
- // write in the project.
968
- let depRows = null;
969
- if (input.dependsOn && input.dependsOn.length) {
970
- if (listing) {
971
- depRows = listing.prds ?? [];
972
- const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
973
- for (const dep of input.dependsOn) {
974
- if (resolveDepSlug(dep, candidateSlugs).length > 0) continue;
975
- const near = findNearMatches(dep, candidateSlugs);
976
- const suggestion = near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : '';
1024
+ // Write-time FK check for dependsOn (report on read / throw on write — see
1025
+ // prdAgentType.cjs's header): every entry must resolve to a PRD that
1026
+ // actually exists in this project, using the SAME resolution rule
1027
+ // schedulerBatch.cjs's findBlockingDep applies at run time (exact slug,
1028
+ // else bare-name after stripping one leading `NN-`) — a dep that
1029
+ // validates here is guaranteed to be a dep findBlockingDep can actually
1030
+ // see later. A listPrds() read failure is skipped-with-a-warning, never a
1031
+ // write outage: an I/O hiccup on the read side must not block every PRD
1032
+ // write in the project.
1033
+ let depRows = null;
1034
+ if (input.dependsOn && input.dependsOn.length) {
1035
+ if (listing) {
1036
+ depRows = listing.prds ?? [];
1037
+ const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
1038
+ for (const dep of input.dependsOn) {
1039
+ if (resolveDepSlug(dep, candidateSlugs).length > 0) continue;
1040
+ const near = findNearMatches(dep, candidateSlugs);
1041
+ const suggestion = near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : '';
1042
+ return {
1043
+ ok: false, applied: false,
1044
+ status: 400,
1045
+ error: `dependsOn entry "${dep}" does not resolve to any existing PRD in this project.${suggestion} ` +
1046
+ 'Pass the bare name (preferred) or the exact NN-prefixed slug of an existing PRD.',
1047
+ };
1048
+ }
1049
+ }
1050
+ }
1051
+
1052
+ // Store every dependsOn entry as the full NN slug it resolved to (queue rows keep
1053
+ // dependsOn verbatim, so a bare name would silently re-point at a later same-name
1054
+ // PRD). Batch siblings stay bare here — createPrdBatch rewrites them to the
1055
+ // sibling's allocated slug once NNs exist — and are excluded from planId
1056
+ // inheritance (they share the batch's planId).
1057
+ const batchSiblingDeps = new Set();
1058
+ if (input.dependsOn && input.dependsOn.length && depRows) {
1059
+ const resolvedDeps = resolveDependsOnToFullSlugs(input.dependsOn, depRows, {
1060
+ epicId: input.sourcePromptId ?? null,
1061
+ siblingSlugs: opts.extraDepSlugs ?? [],
1062
+ });
1063
+ for (const d of resolvedDeps.siblingDeps) batchSiblingDeps.add(d);
1064
+ extraWarnings.push(...resolvedDeps.warnings);
1065
+ input = { ...input, dependsOn: resolvedDeps.dependsOn };
1066
+ }
1067
+
1068
+ // planId is API-owned: any caller-supplied value is discarded. Inherited from the
1069
+ // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
1070
+ // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
1071
+ let planId = null;
1072
+ if (input.dependsOn && input.dependsOn.length && depRows) {
1073
+ const inherited = resolveInheritedPlanId(
1074
+ input.dependsOn.filter((d) => !batchSiblingDeps.has(d)),
1075
+ depRows,
1076
+ // Scoped only when this PRD has an Epic: an Epic-less PRD has no plan boundary to protect.
1077
+ input.sourcePromptId ? { epicId: input.sourcePromptId } : {},
1078
+ );
1079
+ planId = inherited.planId;
1080
+ if (inherited.diverged) {
1081
+ console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
1082
+ }
1083
+ }
1084
+ const inheritedPlanId = planId;
1085
+ if (!planId) planId = mintPlanId();
1086
+
1087
+ const body = buildPrdBody({ ...input, planId, gate: gateCommands, files: filesList });
1088
+
1089
+ // Read-back check (gate-and-files-in-PRD-body unit): the whole point of a
1090
+ // declared gate is that the scheduler's own reader (resolveGate/parseChain
1091
+ // in definitionOfDone.cjs) gets back exactly what was declared. A stray
1092
+ // ```gate fence elsewhere in the body (goal/notes/criteria/out-of-scope)
1093
+ // would otherwise win — readExplicitGate takes the FIRST fence in the
1094
+ // text — and the scheduler would silently re-run the wrong gate. Caught
1095
+ // here, before the write, rather than discovered later from a job log.
1096
+ if (gateCommands) {
1097
+ const expectedSource = gateCommands.length === 1 && isNoneGate(gateCommands[0]) ? 'none' : 'explicit';
1098
+ const expectedSequence = expectedSource === 'none' ? [] : gateCommands.flatMap(parseChain);
1099
+ const resolved = resolveGate(body);
1100
+ const matches = resolved.source === expectedSource
1101
+ && JSON.stringify(resolved.sequence) === JSON.stringify(expectedSequence);
1102
+ if (!matches) {
977
1103
  return {
978
1104
  ok: false, applied: false,
979
1105
  status: 400,
980
- error: `dependsOn entry "${dep}" does not resolve to any existing PRD in this project.${suggestion} ` +
981
- 'Pass the bare name (preferred) or the exact NN-prefixed slug of an existing PRD.',
1106
+ error: 'The PRD text already holds a gate fence (three backticks + gate), so the scheduler would read '
1107
+ + 'the wrong gate. Remove it from the goal, implementation notes, acceptance criteria, out of scope '
1108
+ + 'or files, and call again.',
982
1109
  };
983
1110
  }
984
1111
  }
985
- }
986
1112
 
987
- // Store every dependsOn entry as the full NN slug it resolved to (queue rows keep
988
- // dependsOn verbatim, so a bare name would silently re-point at a later same-name
989
- // PRD). Batch siblings stay bare here — createPrdBatch rewrites them to the
990
- // sibling's allocated slug once NNs exist — and are excluded from planId
991
- // inheritance (they share the batch's planId).
992
- const batchSiblingDeps = new Set();
993
- if (input.dependsOn && input.dependsOn.length && depRows) {
994
- const resolvedDeps = resolveDependsOnToFullSlugs(input.dependsOn, depRows, {
995
- epicId: input.sourcePromptId ?? null,
996
- siblingSlugs: opts.extraDepSlugs ?? [],
997
- });
998
- for (const d of resolvedDeps.siblingDeps) batchSiblingDeps.add(d);
999
- extraWarnings.push(...resolvedDeps.warnings);
1000
- input = { ...input, dependsOn: resolvedDeps.dependsOn };
1001
- }
1002
-
1003
- // planId is API-owned: any caller-supplied value is discarded. Inherited from the
1004
- // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
1005
- // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
1006
- let planId = null;
1007
- if (input.dependsOn && input.dependsOn.length && depRows) {
1008
- const inherited = resolveInheritedPlanId(
1009
- input.dependsOn.filter((d) => !batchSiblingDeps.has(d)),
1010
- depRows,
1011
- // Scoped only when this PRD has an Epic: an Epic-less PRD has no plan boundary to protect.
1012
- input.sourcePromptId ? { epicId: input.sourcePromptId } : {},
1013
- );
1014
- planId = inherited.planId;
1015
- if (inherited.diverged) {
1016
- console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
1017
- }
1018
- }
1019
- const inheritedPlanId = planId;
1020
- if (!planId) planId = mintPlanId();
1021
-
1022
- const body = buildPrdBody({ ...input, planId, gate: gateCommands, files: filesList });
1023
-
1024
- // Read-back check (gate-and-files-in-PRD-body unit): the whole point of a
1025
- // declared gate is that the scheduler's own reader (resolveGate/parseChain
1026
- // in definitionOfDone.cjs) gets back exactly what was declared. A stray
1027
- // ```gate fence elsewhere in the body (goal/notes/criteria/out-of-scope)
1028
- // would otherwise win — readExplicitGate takes the FIRST fence in the
1029
- // text — and the scheduler would silently re-run the wrong gate. Caught
1030
- // here, before the write, rather than discovered later from a job log.
1031
- if (gateCommands) {
1032
- const expectedSource = gateCommands.length === 1 && isNoneGate(gateCommands[0]) ? 'none' : 'explicit';
1033
- const expectedSequence = expectedSource === 'none' ? [] : gateCommands.flatMap(parseChain);
1034
- const resolved = resolveGate(body);
1035
- const matches = resolved.source === expectedSource
1036
- && JSON.stringify(resolved.sequence) === JSON.stringify(expectedSequence);
1037
- if (!matches) {
1113
+ if (opts.dryRun) {
1038
1114
  return {
1039
- ok: false, applied: false,
1040
- status: 400,
1041
- error: 'The PRD text already holds a gate fence (three backticks + gate), so the scheduler would read '
1042
- + 'the wrong gate. Remove it from the goal, implementation notes, acceptance criteria, out of scope '
1043
- + 'or files, and call again.',
1115
+ ok: true, dryRun: true, slug, input, gateCommands, filesList,
1116
+ inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input), ...sandboxWarnings(input), ...mcpReachWarnings(input, mcpReachDeps)],
1044
1117
  };
1045
1118
  }
1046
- }
1047
1119
 
1048
- if (opts.dryRun) {
1049
- return {
1050
- ok: true, dryRun: true, slug, input, gateCommands, filesList,
1051
- inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
1052
- };
1053
- }
1054
-
1055
- const writeResult = await remote.writePrd(filenameSlug, body, input.cwd);
1056
- if (!writeResult?.ok) {
1057
- return { ok: false, applied: false, status: 500, error: writeResult?.error ?? 'write failed' };
1058
- }
1120
+ writeResult = await remote.writePrd(filenameSlug, body, input.cwd);
1121
+ if (!writeResult?.ok) {
1122
+ return { ok: false, applied: false, status: 500, error: writeResult?.error ?? 'write failed' };
1123
+ }
1124
+ return null;
1125
+ };
1126
+ const early = opts.dryRun ? await createPhase() : await withProjectCreateLock(cwd, createPhase);
1127
+ if (early) return early;
1059
1128
 
1060
1129
  // Trace-back point for "who/what created this PRD" (auditLog.cjs) — every
1061
1130
  // PRD write, whether from the admin/MCP route or the renderer's chat:create-prd
@@ -1136,12 +1205,25 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
1136
1205
  // Advisory only (PRD 1403 sizing warnings + gate-and-files-in-PRD-body
1137
1206
  // absent/none-gate warnings) — never blocks the write. See prdSizing.cjs
1138
1207
  // and prdGateFiles.cjs.
1139
- warnings: [...extraWarnings, ...sizingWarnings(input)],
1208
+ warnings: [...extraWarnings, ...sizingWarnings(input), ...sandboxWarnings(input), ...mcpReachWarnings(input, mcpReachDeps)],
1140
1209
  };
1141
1210
  }
1142
1211
 
1143
1212
  const PRD_BATCH_MAX = 40;
1144
1213
 
1214
+ /**
1215
+ * Per-project PRD-create lock (2026-11-24 Bilko 2001/2005: two Epics' batches
1216
+ * validated against listings read before either wrote, then both wrote the same
1217
+ * bare slug). Every PRD create runs in the app's main process (admin routes,
1218
+ * chat:create-prd IPC, in-process mints), so an in-process lock serializes them
1219
+ * all. Keyed by the resolved project cwd (p.input.cwd, already normalized from a
1220
+ * worktree path to the main checkout). Never activeIndexPath(cwd): remote.writePrd
1221
+ * -> ensureEpic takes that lock, so sharing it would deadlock.
1222
+ */
1223
+ function withProjectCreateLock(cwd, task) {
1224
+ return withPathLock(`${cwd}\u0000prd-create`, task);
1225
+ }
1226
+
1145
1227
  /**
1146
1228
  * Create several PRDs all-or-nothing. Every entry goes through createPrd's own
1147
1229
  * validation (dry run: no NN, no file); `dependsOn` may also name other entries
@@ -1214,6 +1296,26 @@ async function createPrdBatch(inputs, remote, opts = {}) {
1214
1296
  return fail([{ index: at, slug: cycle[0], error: `dependsOn cycle inside batch: ${cycle.join(' -> ')}` }]);
1215
1297
  }
1216
1298
 
1299
+ // Plan review: stamp planReview: required on each validator whose in-batch
1300
+ // dependsOn closure qualifies (planReviewHold.qualifiesForReview). Batch-only.
1301
+ const stampReview = new Set();
1302
+ if (planReviewEnabled()) {
1303
+ prepared.forEach((p, i) => {
1304
+ if (p.input.agentType !== 'validator') return;
1305
+ const seen = new Set();
1306
+ const stack = [...edges[i]];
1307
+ while (stack.length) {
1308
+ const n = stack.pop();
1309
+ if (seen.has(n)) continue;
1310
+ seen.add(n);
1311
+ stack.push(...edges[n]);
1312
+ }
1313
+ const members = [...seen].filter((n) => prepared[n].input.agentType !== 'validator')
1314
+ .map((n) => ({ slug: slugs[n], dependsOn: edges[n].map((m) => slugs[m]) }));
1315
+ if (qualifiesForReview(members)) stampReview.add(i);
1316
+ });
1317
+ }
1318
+
1217
1319
  // One planId for the whole batch unless an entry inherits one from existing deps.
1218
1320
  const planId = prepared.map((p) => p.inheritedPlanId).find(Boolean) || mintPlanId();
1219
1321
 
@@ -1228,37 +1330,100 @@ async function createPrdBatch(inputs, remote, opts = {}) {
1228
1330
  } catch (e) { console.warn(`[prdCreate] batch rollback could not remove ${w.filenameSlug}: ${e?.message ?? e}`); }
1229
1331
  }
1230
1332
  };
1231
- // Allocate every NN before writing anything, so a dep on a LATER sibling can be
1232
- // rewritten to that sibling's full `${nn}-${slug}` too. Burned numbers on an
1233
- // allocation failure leave a gap, never an inconsistency.
1234
- const nns = [];
1235
- try {
1236
- for (const p of prepared) nns.push(await remote.allocateParallelGroup(p.input.cwd));
1237
- } catch (e) {
1238
- return fail([{ index: nns.length, slug: prepared[nns.length]?.slug ?? null, error: `NN allocation failed: ${e?.message ?? e}` }]);
1239
- }
1240
- const fullDeps = (deps) => (deps && deps.length
1241
- ? Array.from(new Set(deps.map((d) => (firstIndex.has(d) ? `${nns[firstIndex.get(d)]}-${d}` : d))))
1242
- : deps);
1243
- for (let i = 0; i < prepared.length; i++) {
1244
- const p = prepared[i];
1245
- let nn; let filenameSlug;
1333
+ const projectCwd = prepared[0].input.cwd;
1334
+ const committed = await withProjectCreateLock(projectCwd, async () => {
1335
+ // Commit-time re-check on a FRESH listing, inside the lock: the validation pass
1336
+ // read its listing 15-25 s ago on a busy machine, and another Epic's create may
1337
+ // have written the same bare slug since. A read failure skips the re-check
1338
+ // (never a write outage).
1339
+ let freshListing = null;
1246
1340
  try {
1247
- nn = nns[i];
1248
- filenameSlug = `${nn}-${p.slug}`;
1249
- const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
1250
- // A validated preflight must reach the file (PRD 3805 ran unheld when one
1251
- // was lost); a body without the line rolls the whole batch back.
1252
- if (p.input.preflight && !/^preflight: /m.test(body)) throw new Error('preflight was not written to the PRD frontmatter');
1253
- const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
1254
- if (!w?.ok) throw new Error(w?.error ?? 'write failed');
1255
- written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
1256
- results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, preflight: p.input.preflight || null, warnings: p.warnings });
1341
+ freshListing = await remote.listPrds({ cwd: projectCwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER, fresh: true });
1257
1342
  } catch (e) {
1258
- await rollback();
1259
- return fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]);
1343
+ console.warn(`[prdCreate] batch fresh listPrds failed (commit-time duplicate + files-overlap re-checks skipped): ${e?.message ?? e}`);
1344
+ freshListing = null;
1260
1345
  }
1261
- }
1346
+ const overlapWarnings = prepared.map(() => []);
1347
+ if (freshListing) {
1348
+ const freshRows = freshListing.prds ?? [];
1349
+ // Same-Epic rows already in the validation snapshot were judged by the
1350
+ // validation pass's own-Epic directory scan; only rows written since then
1351
+ // (a concurrent create in this Epic) are refused here.
1352
+ let seenAtValidation = new Set();
1353
+ try {
1354
+ const v = listingCache.promise ? await listingCache.promise : null;
1355
+ seenAtValidation = new Set((v?.prds ?? []).map((r) => r?.slug));
1356
+ } catch { /* validation read failed — every same-Epic row counts as new */ }
1357
+ const refused = [];
1358
+ for (let i = 0; i < prepared.length; i++) {
1359
+ const p = prepared[i];
1360
+ const epicId = p.input.sourcePromptId ?? null;
1361
+ if (opts.internalMint !== true) {
1362
+ const dups = findCrossEpicDuplicates(p.slug, epicId, freshRows);
1363
+ if (dups.length) {
1364
+ const allowed = new Set(Array.isArray(p.input.allowDuplicateOf) ? p.input.allowDuplicateOf : []);
1365
+ if (!dups.every((r) => allowed.has(r.slug))) {
1366
+ refused.push({ index: i, slug: p.slug, error: crossEpicDuplicateError(p.slug, dups), status: 409 });
1367
+ continue;
1368
+ }
1369
+ p.duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
1370
+ } else {
1371
+ p.duplicateAllowed = null;
1372
+ }
1373
+ }
1374
+ if (epicId != null && !isFixPlanSlug(`0-${p.slug}`)) {
1375
+ const target = bareSlug(p.slug);
1376
+ const same = freshRows.find((r) => r && typeof r.slug === 'string' && r.epicId === epicId
1377
+ && !seenAtValidation.has(r.slug) && bareSlug(r.slug) === target);
1378
+ if (same) {
1379
+ refused.push({ index: i, slug: p.slug, error: `slug "${p.slug}" already exists in this Epic as "${same.slug}"`, status: 409 });
1380
+ continue;
1381
+ }
1382
+ }
1383
+ if (p.filesList && p.filesList.length) {
1384
+ overlapWarnings[i] = await crossEpicFilesOverlapWarnings(p.filesList, epicId, freshRows, remote, projectCwd);
1385
+ }
1386
+ }
1387
+ if (refused.length) return { failed: fail(refused) };
1388
+ }
1389
+ // Allocate every NN before writing anything, so a dep on a LATER sibling can be
1390
+ // rewritten to that sibling's full `${nn}-${slug}` too. Burned numbers on an
1391
+ // allocation failure leave a gap, never an inconsistency.
1392
+ const nns = [];
1393
+ try {
1394
+ for (const p of prepared) nns.push(await remote.allocateParallelGroup(p.input.cwd));
1395
+ } catch (e) {
1396
+ return { failed: fail([{ index: nns.length, slug: prepared[nns.length]?.slug ?? null, error: `NN allocation failed: ${e?.message ?? e}` }]) };
1397
+ }
1398
+ const fullDeps = (deps) => (deps && deps.length
1399
+ ? Array.from(new Set(deps.map((d) => (firstIndex.has(d) ? `${nns[firstIndex.get(d)]}-${d}` : d))))
1400
+ : deps);
1401
+ for (let i = 0; i < prepared.length; i++) {
1402
+ const p = prepared[i];
1403
+ let nn; let filenameSlug;
1404
+ try {
1405
+ nn = nns[i];
1406
+ filenameSlug = `${nn}-${p.slug}`;
1407
+ const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, planReview: stampReview.has(i) ? 'required' : undefined, gate: p.gateCommands, files: p.filesList });
1408
+ // A validated preflight must reach the file (PRD 3805 ran unheld when one
1409
+ // was lost); a body without the line rolls the whole batch back.
1410
+ if (p.input.preflight && !/^preflight: /m.test(body)) throw new Error('preflight was not written to the PRD frontmatter');
1411
+ const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
1412
+ if (!w?.ok) throw new Error(w?.error ?? 'write failed');
1413
+ written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
1414
+ results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, preflight: p.input.preflight || null,
1415
+ ...(stampReview.has(i) ? { planReview: 'required' } : {}),
1416
+ warnings: [...p.warnings, ...overlapWarnings[i], ...(stampReview.has(i) ? ['plan held for plan review before dispatch'] : [])] });
1417
+ } catch (e) {
1418
+ await rollback();
1419
+ return { failed: fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]) };
1420
+ }
1421
+ }
1422
+ return { failed: null };
1423
+ });
1424
+ // Audit rows, telemetry and the bounded reconcile wait run after the lock is
1425
+ // released, so a 2 s reconcile never holds other creates.
1426
+ if (committed.failed) return committed.failed;
1262
1427
 
1263
1428
  for (let i = 0; i < prepared.length; i++) {
1264
1429
  const p = prepared[i];
@@ -1368,6 +1533,7 @@ function registerAdminRoute(adminHttp, remote) {
1368
1533
  }
1369
1534
 
1370
1535
  module.exports = {
1536
+ mcpReachDeps,
1371
1537
  crossEpicFilesOverlapWarnings,
1372
1538
  PRD_CREATE_SLUG_RE,
1373
1539
  STANDARDS_PATH,