claude-code-session-manager 0.139.0 → 0.141.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 (154) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
  3. package/dist/assets/History-DJMiuXyK.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
  7. package/dist/assets/Scheduler-cyr61UAC.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
  14. package/dist/assets/index-B2TQz3nd.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  33. package/scripts/README.md +1 -0
  34. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  35. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  36. package/scripts/ops-sweep.cjs +53 -23
  37. package/scripts/scheduler-mcp-server.cjs +205 -18
  38. package/src/main/build-info.json +4 -4
  39. package/src/main/config.cjs +112 -8
  40. package/src/main/docEdit.cjs +6 -1
  41. package/src/main/files.cjs +7 -27
  42. package/src/main/health.cjs +48 -15
  43. package/src/main/historyAggregator.cjs +88 -5
  44. package/src/main/historyDashboard.cjs +69 -4
  45. package/src/main/index.cjs +56 -2
  46. package/src/main/ipcSchemas.cjs +122 -16
  47. package/src/main/lib/AGENTS.md +54 -0
  48. package/src/main/lib/CLAUDE.md +1 -54
  49. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  50. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  51. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  52. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  53. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  54. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  55. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  56. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  57. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  58. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  59. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  60. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  61. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  62. package/src/main/lib/ephemeralCwd.cjs +37 -2
  63. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  64. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  65. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  66. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  67. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  68. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  69. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  70. package/src/main/lib/externalContract.cjs +31 -5
  71. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  72. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  73. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  74. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  75. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  76. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  77. package/src/main/lib/git/branchSweep.cjs +209 -4
  78. package/src/main/lib/git/gitWorktree.cjs +41 -5
  79. package/src/main/lib/guardShims.cjs +1 -1
  80. package/src/main/lib/historyRollup.cjs +26 -0
  81. package/src/main/lib/insideHome.cjs +27 -1
  82. package/src/main/lib/mcpToolCatalog.cjs +132 -13
  83. package/src/main/lib/mdDocCensus.cjs +59 -78
  84. package/src/main/lib/mdDocRefs.cjs +71 -93
  85. package/src/main/lib/mdNetworkScan.cjs +245 -250
  86. package/src/main/lib/mdReviewRecord.cjs +22 -9
  87. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  88. package/src/main/lib/opsOwnership.cjs +18 -2
  89. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  90. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  91. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  92. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  93. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  94. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  95. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  96. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  97. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  98. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  99. package/src/main/lib/prd/prdCreate.cjs +377 -23
  100. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  101. package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
  102. package/src/main/lib/process/loginItem.cjs +171 -0
  103. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  104. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  105. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  106. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  107. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  108. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  109. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  110. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  111. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  112. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  113. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  114. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  115. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  116. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  117. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  118. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  119. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  120. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  121. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  122. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  123. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  124. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  125. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  126. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  127. package/src/main/lib/tasks/taskRun.cjs +313 -0
  128. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  129. package/src/main/loginItemIpc.cjs +35 -0
  130. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  131. package/src/main/projectPages.cjs +6 -15
  132. package/src/main/promptSessionEvents.cjs +9 -1
  133. package/src/main/queueOps.cjs +260 -3
  134. package/src/main/runVerify.cjs +53 -25
  135. package/src/main/scheduler/AGENTS.md +26 -0
  136. package/src/main/scheduler/CLAUDE.md +1 -26
  137. package/src/main/scheduler/budget.cjs +239 -9
  138. package/src/main/scheduler/cancelDependents.cjs +154 -0
  139. package/src/main/scheduler/prdParser.cjs +19 -1
  140. package/src/main/scheduler/reviewLadder.cjs +36 -3
  141. package/src/main/scheduler/starvation.cjs +89 -18
  142. package/src/main/scheduler.cjs +1080 -89
  143. package/src/main/supervisor.cjs +5 -1
  144. package/src/main/templates/PRD_AUTHORING.md +14 -1
  145. package/src/main/validationQualityHandlers.cjs +199 -0
  146. package/src/main/webRemote.cjs +10 -2
  147. package/src/preload/api.d.ts +364 -21
  148. package/src/preload/apiSurface.json +89 -10
  149. package/src/preload/index.cjs +23 -2
  150. package/src/seed/agents/validator.md +19 -8
  151. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  152. package/dist/assets/History-DDnqaLyw.js +0 -2
  153. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  154. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -28,18 +28,63 @@ const { appendAuditEvent } = require('../telemetry/auditLog.cjs');
28
28
  const { resolveProjectContext } = require('../projectRootResolve.cjs');
29
29
  const { fixChainDepthOf, baseSlugOf } = require('../scheduler/fixChainDepth.cjs');
30
30
  const { DEFAULT_PRD_AGENT_TYPE, assertAgentTypeWritable } = require('./prdAgentType.cjs');
31
- const { resolveDepSlug, findNearMatches } = require('./depSlugResolve.cjs');
31
+ const { bareSlug, resolveDepSlug, findNearMatches, epicOf } = require('./depSlugResolve.cjs');
32
32
  const { resolveEpicPrdWriteDir } = require('./prdLocations.cjs');
33
33
  const { isFixPlanSlug } = require('../scheduler/fixPlanSlug.cjs');
34
34
  const { isIncomplete, resolveChainTerminals, isValidPlanId, mintPlanId, resolveInheritedPlanId } = require('./prdDisposition.cjs');
35
- const { splitFrontmatter, PRD_EFFORT_LEVELS } = require('./prdFrontmatter.cjs');
35
+ const { splitFrontmatter, PRD_EFFORT_LEVELS, formatQuotedInlineList } = require('./prdFrontmatter.cjs');
36
+ const { parseRule: parseToolRiskRule } = require('../claude/toolRiskMarks.cjs');
37
+ const { normalizePreflight } = require('../scheduler/preflightCheck.cjs');
38
+
39
+ // Cap on riskTools entries — mirrors ipcSchemas.cjs RiskToolsSchema.
40
+ const RISK_TOOLS_MAX = 20;
41
+
42
+ /**
43
+ * Validate + normalize a `preflight` value — wraps preflightCheck's
44
+ * normalizePreflight (which throws) into the { ok, value | error } shape the
45
+ * other field checks return, so createPrd and the update path share one check.
46
+ * value is null when the input is empty/absent (no frontmatter key).
47
+ */
48
+ function normalizePreflightField(value) {
49
+ try {
50
+ return { ok: true, value: normalizePreflight(value) };
51
+ } catch (e) {
52
+ return { ok: false, error: e && e.message ? e.message : String(e) };
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Validate + normalize a `riskTools` value — the ONE check shared by
58
+ * createPrd and scheduler.cjs's updatePrd so create and update can never
59
+ * disagree. Each entry must parse under toolRiskMarks.parseRule; entries are
60
+ * de-duplicated in order and capped at RISK_TOOLS_MAX.
61
+ * @returns {{ ok: true, value: string[] } | { ok: false, error: string }}
62
+ */
63
+ function normalizeRiskTools(value) {
64
+ if (!Array.isArray(value)) {
65
+ return { ok: false, error: 'riskTools must be an array of tool-risk rule strings when given' };
66
+ }
67
+ const seen = [];
68
+ for (const rule of value) {
69
+ if (parseToolRiskRule(rule) === null) {
70
+ return { ok: false, error: `riskTools entry ${JSON.stringify(rule)} is not a valid tool-risk rule — use mcp__<server>__<tool>, mcp__<server>__*, Bash(<cmd>) or Bash(<cmd>:*)` };
71
+ }
72
+ if (!seen.includes(rule)) seen.push(rule);
73
+ }
74
+ if (seen.length > RISK_TOOLS_MAX) {
75
+ return { ok: false, error: `riskTools has ${seen.length} entries; the maximum is ${RISK_TOOLS_MAX}` };
76
+ }
77
+ return { ok: true, value: seen };
78
+ }
36
79
  const { sizingWarnings } = require('./prdSizing.cjs');
37
80
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
38
81
  const { execGit } = require('../git/gitExec.cjs');
39
82
  const { extractRepoPathCandidates, worktreeReachWarnings } = require('./prdWorktreeReach.cjs');
40
83
  const { isSweepValidatorSlug } = require('../epic/epicSweepValidator.cjs');
41
- const { validateGate, validateFiles, renderFilesSection, renderGateSection } = require('./prdGateFiles.cjs');
84
+ const { validateGate, validateFiles, renderFilesSection, renderGateSection, parseFilesSection } = require('./prdGateFiles.cjs');
85
+ const { filesOverlap } = require('../scheduler/schedulerBatch.cjs');
42
86
  const { resolveGate, parseChain, isNoneGate } = require('../scheduler/definitionOfDone.cjs');
87
+ const { MISS_KINDS } = require('../scheduler/validatorVerdictSchema.cjs');
43
88
 
44
89
  // A caller-supplied slug that already starts with its own `NN-` (e.g.
45
90
  // "254-perf-x") used to silently become the double-prefixed row
@@ -89,8 +134,8 @@ function isValidMacroId(id) {
89
134
  function buildPrdBody(input) {
90
135
  const {
91
136
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
92
- implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort,
93
- gate, files, budgetExempt,
137
+ implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, riskTools, preflight,
138
+ gate, files, budgetExempt, fixes,
94
139
  } = input;
95
140
 
96
141
  // No `parallelGroup` frontmatter key (PRD_AUTHORING.md §5) — the NN-
@@ -126,6 +171,10 @@ function buildPrdBody(input) {
126
171
  fmLines.push(`agentType: ${agentType || DEFAULT_PRD_AGENT_TYPE}`);
127
172
  // Explicit ordering (PRD 832): replaces the retired shared-NN convention.
128
173
  if (dependsOn && dependsOn.length) fmLines.push(`dependsOn: [${dependsOn.join(', ')}]`);
174
+ // Earlier PRDs this one repairs (validator-miss / escape link) — one-line JSON
175
+ // array, already validated and resolved to NN slugs by createPrd(); see
176
+ // prdFrontmatter.cjs's applyKey for the matching parse.
177
+ if (Array.isArray(fixes) && fixes.length) fmLines.push(`fixes: ${serializeFixes(fixes)}`);
129
178
  // Wave-authoring decision (scheduler wave-disposition PRD) — only ever set
130
179
  // when createPrd() actually had a disposition to record (see the call
131
180
  // site above); a first-ever PRD in an Epic, or one with its own explicit
@@ -144,6 +193,11 @@ function buildPrdBody(input) {
144
193
  // prdFrontmatter.cjs's applyKey for the matching "only true opts in" parse.
145
194
  if (isValidMacroId(macroId)) fmLines.push(`macroId: ${macroId}`);
146
195
  if (PRD_EFFORT_LEVELS.includes(effort)) fmLines.push(`effort: ${effort}`);
196
+ // Risky tools this PRD is cleared to call — validated + de-duplicated by createPrd().
197
+ if (Array.isArray(riskTools) && riskTools.length) fmLines.push(`riskTools: ${formatQuotedInlineList(riskTools)}`);
198
+ // Precondition command — validated by createPrd() via normalizePreflightField.
199
+ // JSON-string form, matching prdFrontmatter.cjs's serializer.
200
+ if (typeof preflight === 'string' && preflight) fmLines.push(`preflight: ${JSON.stringify(preflight)}`);
147
201
  if (quietMachine === true) fmLines.push('quietMachine: true');
148
202
  // Budget exemption is for a sweep validator that cannot be split further;
149
203
  // every other caller's budgetExempt is ignored.
@@ -210,11 +264,22 @@ function resolveSourcePromptIdFromClaudeSession(cwd, claudeSessionId) {
210
264
  * worktree). execGit has no stdin, so candidates go as argv after `--` (still one call). Exit 1 =
211
265
  * nothing ignored; any other failure (not a repo, timeout) is swallowed — never blocks the write.
212
266
  */
267
+ const PLAN_RECORDS_PREFIX = 'session-manager-operations/plan-records/';
268
+
269
+ /** True when `files` is a non-empty list whose every entry is under plan-records/. */
270
+ function isPlanRecordOnlyFiles(files) {
271
+ return Array.isArray(files) && files.length > 0
272
+ && files.every((f) => typeof f === 'string' && f.startsWith(PLAN_RECORDS_PREFIX) && f.length > PLAN_RECORDS_PREFIX.length);
273
+ }
274
+
213
275
  async function worktreeReachAdvisory(input, cwd) {
214
276
  try {
215
277
  const text = [input.goal, ...(Array.isArray(input.acceptanceCriteria) ? input.acceptanceCriteria : []),
216
278
  input.implementationNotes].filter((s) => typeof s === 'string').join('\n');
217
- const candidates = extractRepoPathCandidates(text);
279
+ // Plan records are gitignored on purpose: the job writes them in its
280
+ // worktree and the scheduler harvests them to the main checkout, so
281
+ // naming one is not a worktree-reach mistake.
282
+ const candidates = extractRepoPathCandidates(text).filter((p) => !p.startsWith(PLAN_RECORDS_PREFIX));
218
283
  if (candidates.length === 0) return [];
219
284
  const out = await execGit(cwd, ['check-ignore', '--', ...candidates], { timeout: 10000 });
220
285
  const ignored = out.split('\n').map((l) => l.trim()).filter(Boolean);
@@ -239,10 +304,172 @@ async function worktreeReachAdvisory(input, cwd) {
239
304
  */
240
305
  const inFlightCreates = new Set();
241
306
 
242
- async function createPrd(input, remote) {
307
+ const nnOf = (slug) => {
308
+ const m = /^(\d+)-/.exec(slug);
309
+ return m ? Number(m[1]) : -1;
310
+ };
311
+
312
+ /**
313
+ * Map each `dependsOn` entry to the full NN slug it names, in priority order: a
314
+ * batch sibling's bare slug (kept bare; the batch path rewrites it after NN
315
+ * allocation), an exact existing slug, then bare-name matches in the new PRD's own
316
+ * Epic, then bare-name matches anywhere. Within the chosen tier the highest NN (the
317
+ * most recent same-name PRD) wins. A bare match spanning more than one Epic yields a
318
+ * warning naming every candidate and the one chosen. Entries that resolve to nothing
319
+ * are kept verbatim (the FK check above already refused those when it could read).
320
+ */
321
+ function resolveDependsOnToFullSlugs(dependsOn, rows, { epicId = null, siblingSlugs = [] } = {}) {
322
+ const slugs = rows.map((r) => r.slug);
323
+ const epicBySlug = new Map(rows.map((r) => [r.slug, epicOf(r)]));
324
+ const siblings = new Set(siblingSlugs);
325
+ const out = [];
326
+ const siblingDeps = [];
327
+ const warnings = [];
328
+ for (const dep of dependsOn) {
329
+ if (siblings.has(dep)) { out.push(dep); siblingDeps.push(dep); continue; }
330
+ const matches = resolveDepSlug(dep, slugs);
331
+ if (matches.length === 0) { out.push(dep); continue; }
332
+ if (matches.length === 1 && matches[0] === dep) { out.push(dep); continue; }
333
+ const sameEpic = epicId != null ? matches.filter((m) => epicBySlug.get(m) === epicId) : [];
334
+ const tier = sameEpic.length ? sameEpic : matches;
335
+ const chosen = [...tier].sort((a, b) => nnOf(b) - nnOf(a) || b.localeCompare(a))[0];
336
+ const epics = new Set(matches.map((m) => epicBySlug.get(m) ?? null));
337
+ if (epics.size > 1) {
338
+ const list = matches.map((m) => `${m} (Epic ${epicBySlug.get(m) ?? 'none'})`).join(', ');
339
+ warnings.push(`dependsOn "${dep}" matches PRDs in more than one Epic: ${list}. Stored as "${chosen}". ` +
340
+ 'Pass the exact NN-prefixed slug if you meant another one.');
341
+ }
342
+ out.push(chosen);
343
+ }
344
+ return { dependsOn: Array.from(new Set(out)), siblingDeps, warnings };
345
+ }
346
+
347
+ const FIXES_MAX = 20;
348
+ const FIX_REASON_MAX = 200;
349
+
350
+ /** Serialize resolved fixes as the one-line JSON array prdFrontmatter.cjs parses. */
351
+ function serializeFixes(fixes) {
352
+ return JSON.stringify(fixes.map((f) => ({ prd: f.prd, missKind: f.missKind, reason: f.reason })));
353
+ }
354
+
355
+ /**
356
+ * Shape check for the optional `fixes` input: 1-FIXES_MAX entries of
357
+ * { prd, missKind (one of MISS_KINDS), reason (one line, 1-200 chars) }, none
358
+ * naming the PRD being created. Returns one error string per bad entry, each
359
+ * naming its index.
360
+ */
361
+ function validateFixesShape(fixes, selfSlug) {
362
+ if (!Array.isArray(fixes)) return ['fixes must be an array of { prd, missKind, reason }'];
363
+ if (fixes.length < 1 || fixes.length > FIXES_MAX) return [`fixes must have 1-${FIXES_MAX} entries (got ${fixes.length})`];
364
+ const errors = [];
365
+ fixes.forEach((f, i) => {
366
+ const at = `fixes[${i}]`;
367
+ if (f == null || typeof f !== 'object' || Array.isArray(f)) { errors.push(`${at}: must be an object { prd, missKind, reason }`); return; }
368
+ if (typeof f.prd !== 'string' || !/^\S+$/.test(f.prd)) {
369
+ errors.push(`${at}.prd: must be the NN-slug or bare slug of an existing PRD`);
370
+ } else if (f.prd === selfSlug) {
371
+ errors.push(`${at}.prd: "${f.prd}" names this PRD itself`);
372
+ }
373
+ if (!MISS_KINDS.includes(f.missKind)) errors.push(`${at}.missKind: must be one of ${MISS_KINDS.join(', ')}`);
374
+ if (typeof f.reason !== 'string' || f.reason.trim() === '') errors.push(`${at}.reason: must be a non-empty string`);
375
+ else if (/[\r\n]/.test(f.reason)) errors.push(`${at}.reason: must be one line`);
376
+ else if (f.reason.length > FIX_REASON_MAX) errors.push(`${at}.reason: must be at most ${FIX_REASON_MAX} chars (got ${f.reason.length})`);
377
+ });
378
+ return errors;
379
+ }
380
+
381
+ /**
382
+ * Resolve each fixes[].prd to the full NN slug of an existing PRD in this project,
383
+ * with the same rule dependsOn uses (resolveDepSlug + resolveDependsOnToFullSlugs:
384
+ * exact slug, else bare name preferring the same Epic, highest NN).
385
+ */
386
+ function resolveFixes(fixes, rows, { epicId = null } = {}) {
387
+ const slugs = rows.map((r) => r.slug);
388
+ const errors = [];
389
+ const warnings = [];
390
+ const out = [];
391
+ fixes.forEach((f, i) => {
392
+ if (resolveDepSlug(f.prd, slugs).length === 0) {
393
+ const near = findNearMatches(f.prd, slugs);
394
+ errors.push(`fixes[${i}].prd: "${f.prd}" does not resolve to any existing PRD in this project.` +
395
+ (near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : ''));
396
+ return;
397
+ }
398
+ const r = resolveDependsOnToFullSlugs([f.prd], rows, { epicId });
399
+ warnings.push(...r.warnings.map((w) => w.replace(/^dependsOn /, `fixes[${i}].prd `)));
400
+ out.push({ prd: r.dependsOn[0], missKind: f.missKind, reason: f.reason });
401
+ });
402
+ return { fixes: out, errors, warnings };
403
+ }
404
+
405
+ /**
406
+ * Cross-Epic duplicate guard (2026-11-22 Self stall: 1047-sm-contract-client and
407
+ * 1056-sm-contract-client queued ~2 minutes apart from two Epics). Pure: returns
408
+ * every listing row whose bare slug equals `newBareSlug` and whose `epicId` is set
409
+ * and differs from `epicId`. Rows with no epicId (retired flat layout) are ignored;
410
+ * live and archived rows of any status count.
411
+ */
412
+ function findCrossEpicDuplicates(newBareSlug, epicId, rows) {
413
+ if (!newBareSlug || !Array.isArray(rows)) return [];
414
+ const target = bareSlug(newBareSlug);
415
+ return rows.filter((r) => r && typeof r.slug === 'string'
416
+ && r.epicId != null && r.epicId !== ''
417
+ && r.epicId !== (epicId ?? null)
418
+ && bareSlug(r.slug) === target);
419
+ }
420
+
421
+ function crossEpicDuplicateError(slug, dups) {
422
+ const list = dups.map((r) => `${r.slug} (Epic ${r.epicId}, status ${r.status ?? 'unknown'})`).join('; ');
423
+ const slugs = dups.map((r) => r.slug);
424
+ return `A PRD with slug "${slug}" already exists in another Epic: ${list}. ` +
425
+ `Add ${slugs.length === 1 ? 'it' : 'them'} to dependsOn instead of queueing the same work twice, ` +
426
+ `or pass allowDuplicateOf: [${slugs.join(', ')}] to create a deliberate duplicate.`;
427
+ }
428
+
429
+ /**
430
+ * Cross-Epic files-overlap advisory (2026-11-22 Self stall: 1047 and 1056 also
431
+ * declared the same files). Dispatch already serializes overlapping files, so
432
+ * 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
434
+ * present, else its `# Files` section is read via remote.readPrd + the shared
435
+ * parseFilesSection. Overlap uses the scheduler's own filesOverlap rule.
436
+ */
437
+ const OVERLAP_ACTIVE_STATUSES = new Set(['pending', 'running', 'investigating']);
438
+ async function crossEpicFilesOverlapWarnings(newFiles, epicId, rows, remote, cwd) {
439
+ if (!Array.isArray(newFiles) || !newFiles.length || !Array.isArray(rows)) return [];
440
+ const warnings = [];
441
+ for (const r of rows) {
442
+ if (!r || typeof r.slug !== 'string' || !OVERLAP_ACTIVE_STATUSES.has(r.status)) continue;
443
+ if (r.epicId == null || r.epicId === '' || r.epicId === (epicId ?? null)) continue;
444
+ let otherFiles = Array.isArray(r.files) ? r.files : null;
445
+ if (!otherFiles) {
446
+ try {
447
+ const read = typeof remote?.readPrd === 'function' ? await remote.readPrd(r.slug, cwd) : null;
448
+ otherFiles = read?.ok ? parseFilesSection(read.text) : [];
449
+ } catch { otherFiles = []; }
450
+ }
451
+ if (!filesOverlap(newFiles, otherFiles)) continue;
452
+ const pairs = [];
453
+ for (const a of newFiles) {
454
+ for (const b of otherFiles) {
455
+ if (filesOverlap([a], [b])) pairs.push(a === b ? a : `${a} ~ ${b}`);
456
+ }
457
+ }
458
+ warnings.push(`Files overlap with ${r.slug} (Epic ${r.epicId}, status ${r.status}): ${pairs.join(', ')}. ` +
459
+ 'Dispatch will serialize the two; add it to dependsOn if this PRD needs its changes first.');
460
+ }
461
+ return warnings;
462
+ }
463
+
464
+ /**
465
+ * createPrd(input, remote, opts?) — opts.internalMint: true marks a scheduler-
466
+ * internal mint (defaultScheduleSettle's validate-sweep validators), which skips
467
+ * the cross-Epic duplicate guard.
468
+ */
469
+ async function createPrd(input, remote, opts = {}) {
243
470
  const ctl = { key: null };
244
471
  try {
245
- return await createPrdInner(input, remote, ctl);
472
+ return await createPrdInner(input, remote, ctl, { internalMint: opts?.internalMint === true });
246
473
  } finally {
247
474
  if (ctl.key) inFlightCreates.delete(ctl.key);
248
475
  }
@@ -403,6 +630,15 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
403
630
  if (input.parallelGroup != null) {
404
631
  console.warn(`[prdCreate] parallelGroup input is deprecated and ignored (got ${input.parallelGroup}) — numbers are unique per project; use dependsOn for ordering`);
405
632
  }
633
+ // Plan-record auto-declaration: a PRD whose every files entry is a plan
634
+ // record (gitignored runtime namespace, harvested by the scheduler) can
635
+ // never commit its output, so it is artifact-only by construction. Derived
636
+ // here, before the declaration checks below, so the same checks run on it.
637
+ // An explicit declaration, or a files list mixing in any other path, is
638
+ // left as the caller gave it.
639
+ if (input.deliverable == null && input.artifactPaths == null && isPlanRecordOnlyFiles(input.files)) {
640
+ input = { ...input, deliverable: 'artifact', artifactPaths: [...input.files] };
641
+ }
406
642
  // Artifact-only declaration (deliverable + artifactPaths): fail-closed,
407
643
  // checked BEFORE the NN allocation so a refusal burns no number.
408
644
  const hasArtifactPaths = Array.isArray(input.artifactPaths) && input.artifactPaths.length > 0;
@@ -434,6 +670,20 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
434
670
  if (input.effort != null && !PRD_EFFORT_LEVELS.includes(input.effort)) {
435
671
  return { ok: false, applied: false, status: 400, error: 'effort must be one of low, medium, high, xhigh, max when given' };
436
672
  }
673
+ // riskTools: tool-risk rule strings (toolRiskMarks.parseRule grammar) this PRD
674
+ // is cleared to call. Refused before NN allocation; de-duplicated in order.
675
+ if (input.riskTools != null) {
676
+ const rt = normalizeRiskTools(input.riskTools);
677
+ if (!rt.ok) return { ok: false, applied: false, status: 400, error: rt.error };
678
+ input = { ...input, riskTools: rt.value };
679
+ }
680
+ // preflight: one-line precondition command (preflightCheck.normalizePreflight).
681
+ // Refused before NN allocation; an empty value writes no key.
682
+ if (input.preflight !== undefined) {
683
+ const pf = normalizePreflightField(input.preflight);
684
+ if (!pf.ok) return { ok: false, applied: false, status: 400, error: pf.error };
685
+ input = { ...input, preflight: pf.value || undefined };
686
+ }
437
687
 
438
688
  // Fake-heading guard (gate-and-files-in-PRD-body unit): a caller-supplied
439
689
  // free-text field that itself contains a "# Gate" or "# Files" heading line
@@ -556,6 +806,58 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
556
806
  }
557
807
  }
558
808
 
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;
823
+ }
824
+ }
825
+
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) };
834
+ }
835
+ duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
836
+ }
837
+ }
838
+
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
+ }
843
+
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('; ') };
851
+ }
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' };
854
+ }
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
+
559
861
  // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
560
862
  const nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
561
863
  const filenameSlug = `${nn}-${slug}`;
@@ -636,13 +938,6 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
636
938
  // write in the project.
637
939
  let depRows = null;
638
940
  if (input.dependsOn && input.dependsOn.length) {
639
- let listing;
640
- try {
641
- listing = await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
642
- } catch (e) {
643
- console.warn(`[prdCreate] dependsOn validation skipped (listPrds failed): ${e?.message ?? e}`);
644
- listing = null;
645
- }
646
941
  if (listing) {
647
942
  depRows = listing.prds ?? [];
648
943
  const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
@@ -660,12 +955,33 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
660
955
  }
661
956
  }
662
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
+
663
974
  // planId is API-owned: any caller-supplied value is discarded. Inherited from the
664
975
  // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
665
976
  // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
666
977
  let planId = null;
667
978
  if (input.dependsOn && input.dependsOn.length && depRows) {
668
- const inherited = resolveInheritedPlanId(input.dependsOn, 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
+ );
669
985
  planId = inherited.planId;
670
986
  if (inherited.diverged) {
671
987
  console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
@@ -703,7 +1019,7 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
703
1019
  if (opts.dryRun) {
704
1020
  return {
705
1021
  ok: true, dryRun: true, slug, input, gateCommands, filesList,
706
- inheritedPlanId, warnings: [...extraWarnings, ...sizingWarnings(input)],
1022
+ inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
707
1023
  };
708
1024
  }
709
1025
 
@@ -722,6 +1038,11 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
722
1038
  sourcePromptId: input.sourcePromptId ?? null,
723
1039
  sourceTabId: input.sourceTabId ?? null,
724
1040
  });
1041
+ if (duplicateAllowed) {
1042
+ appendAuditEvent('prd_create_duplicate_allowed', {
1043
+ cwd: input.cwd, slug: filenameSlug, sourcePromptId: input.sourcePromptId ?? null, duplicates: duplicateAllowed,
1044
+ });
1045
+ }
725
1046
  // Anonymous counter: enum-mapped agentType only (telemetryCounters.cjs).
726
1047
  telemetryCounters.trackPrdCreate({ agentType: input.agentType || DEFAULT_PRD_AGENT_TYPE });
727
1048
 
@@ -799,7 +1120,11 @@ const PRD_BATCH_MAX = 40;
799
1120
  * gap, not an inconsistency.
800
1121
  */
801
1122
  async function createPrdBatch(inputs, remote, opts = {}) {
802
- const fail = (errors) => ({ ok: false, applied: false, errors });
1123
+ // status: 409 when every refusal is a conflict (e.g. cross-Epic duplicate), else 400.
1124
+ const fail = (errors) => ({
1125
+ ok: false, applied: false, errors: errors.map(({ status: _s, ...e }) => e),
1126
+ status: errors.length && errors.every((e) => e.status === 409) ? 409 : 400,
1127
+ });
803
1128
  if (!Array.isArray(inputs) || inputs.length === 0) return fail([{ index: -1, slug: null, error: 'batch needs at least one entry' }]);
804
1129
  if (inputs.length > PRD_BATCH_MAX) return fail([{ index: -1, slug: null, error: `batch has ${inputs.length} entries; the maximum is ${PRD_BATCH_MAX}` }]);
805
1130
 
@@ -822,10 +1147,14 @@ async function createPrdBatch(inputs, remote, opts = {}) {
822
1147
  const batchSlugs = slugs.filter(Boolean);
823
1148
 
824
1149
  // Pass 2: per-entry validation through createPrd's own checks.
1150
+ // Every entry is checked (all-or-nothing); one shared listing serves them all.
825
1151
  const prepared = [];
1152
+ const listingCache = {};
826
1153
  for (let i = 0; i < entries.length; i++) {
827
- const r = await createPrdInner(entries[i], remote, { key: null }, { dryRun: true, extraDepSlugs: batchSlugs });
828
- if (!r.ok) { errors.push({ index: i, slug: slugs[i] ?? null, error: r.error }); continue; }
1154
+ const r = await createPrdInner(entries[i], remote, { key: null }, {
1155
+ dryRun: true, extraDepSlugs: batchSlugs, internalMint: opts.internalMint === true, listingCache,
1156
+ });
1157
+ if (!r.ok) { errors.push({ index: i, slug: slugs[i] ?? null, error: r.error, status: r.status }); continue; }
829
1158
  if (r.alreadyExisted) { errors.push({ index: i, slug: slugs[i], error: `slug "${slugs[i]}" already exists in this Epic as "${r.filename}"` }); continue; }
830
1159
  prepared.push(r);
831
1160
  }
@@ -867,13 +1196,25 @@ async function createPrdBatch(inputs, remote, opts = {}) {
867
1196
  } catch (e) { console.warn(`[prdCreate] batch rollback could not remove ${w.filenameSlug}: ${e?.message ?? e}`); }
868
1197
  }
869
1198
  };
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);
870
1211
  for (let i = 0; i < prepared.length; i++) {
871
1212
  const p = prepared[i];
872
1213
  let nn; let filenameSlug;
873
1214
  try {
874
- nn = await remote.allocateParallelGroup(p.input.cwd);
1215
+ nn = nns[i];
875
1216
  filenameSlug = `${nn}-${p.slug}`;
876
- const body = buildPrdBody({ ...p.input, planId, gate: p.gateCommands, files: p.filesList });
1217
+ const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
877
1218
  const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
878
1219
  if (!w?.ok) throw new Error(w?.error ?? 'write failed');
879
1220
  written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
@@ -890,6 +1231,12 @@ async function createPrdBatch(inputs, remote, opts = {}) {
890
1231
  cwd: p.input.cwd, slug: `${results[i].nn}-${p.slug}`, title: p.input.title,
891
1232
  sourcePromptId: p.input.sourcePromptId ?? null, sourceTabId: p.input.sourceTabId ?? null, batch: true,
892
1233
  });
1234
+ if (p.duplicateAllowed) {
1235
+ appendAuditEvent('prd_create_duplicate_allowed', {
1236
+ cwd: p.input.cwd, slug: `${results[i].nn}-${p.slug}`, sourcePromptId: p.input.sourcePromptId ?? null,
1237
+ duplicates: p.duplicateAllowed, batch: true,
1238
+ });
1239
+ }
893
1240
  telemetryCounters.trackPrdCreate({ agentType: p.input.agentType || DEFAULT_PRD_AGENT_TYPE });
894
1241
  }
895
1242
 
@@ -977,7 +1324,7 @@ function registerAdminRoute(adminHttp, remote) {
977
1324
  const { prds, ...envelope } = input;
978
1325
  const result = await createPrdBatch(prds, remote, envelope);
979
1326
  if (!result.ok) {
980
- sendJson(res, 400, { ok: false, applied: false, errors: result.errors });
1327
+ sendJson(res, result.status ?? 400, { ok: false, applied: false, errors: result.errors });
981
1328
  return;
982
1329
  }
983
1330
  sendJson(res, 200, { ok: true, applied: true, prds: result.prds });
@@ -985,6 +1332,7 @@ function registerAdminRoute(adminHttp, remote) {
985
1332
  }
986
1333
 
987
1334
  module.exports = {
1335
+ crossEpicFilesOverlapWarnings,
988
1336
  PRD_CREATE_SLUG_RE,
989
1337
  STANDARDS_PATH,
990
1338
  readStandards,
@@ -993,6 +1341,12 @@ module.exports = {
993
1341
  resolveSourcePromptIdFromClaudeSession,
994
1342
  createPrd,
995
1343
  createPrdBatch,
1344
+ normalizeRiskTools,
1345
+ normalizePreflightField,
1346
+ RISK_TOOLS_MAX,
1347
+ findCrossEpicDuplicates,
1348
+ validateFixesShape,
1349
+ FIXES_MAX,
996
1350
  PRD_BATCH_MAX,
997
1351
  registerAdminRoute,
998
1352
  };
@@ -29,7 +29,7 @@
29
29
  */
30
30
 
31
31
  const crypto = require('node:crypto');
32
- const { resolveDepSlug } = require('./depSlugResolve.cjs');
32
+ const { resolveDepSlug, epicOf } = require('./depSlugResolve.cjs');
33
33
 
34
34
  /** A row is "incomplete" (still part of the Epic's active plan) unless it
35
35
  * has actually finished. Treats every other status — including a brand-new
@@ -211,8 +211,17 @@ function mintPlanId() {
211
211
  * { planId, diverged } — planId is null when no dependency carries a valid one (caller
212
212
  * mints). When dependencies carry two or more DIFFERENT planIds, the lowest-numbered
213
213
  * dependency's wins (ties broken by slug) and `diverged` lists the distinct ids.
214
+ *
215
+ * `opts.epicId` (key present, even when null): only rows whose Epic (epicId, else
216
+ * sourcePromptId) equals it can donate a planId — a bare dep that also names another
217
+ * Epic's PRD must never pull this PRD into that Epic's plan (Self rows 1048-1055 of
218
+ * Epic f25f3d71 and 1056-1065 of Epic a23ae9c4 shared pl-mws3hfco-8a3e00).
214
219
  */
215
- function resolveInheritedPlanId(depSlugs, rows) {
220
+ function resolveInheritedPlanId(depSlugs, rows, opts = {}) {
221
+ if (Object.prototype.hasOwnProperty.call(opts, 'epicId')) {
222
+ const epicId = opts.epicId ?? null;
223
+ rows = rows.filter((r) => epicOf(r) === epicId);
224
+ }
216
225
  const slugs = rows.map((r) => r.slug);
217
226
  const seen = new Set();
218
227
  const deps = [];