claude-code-session-manager 0.139.0 → 0.140.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 (150) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  3. package/dist/assets/History--JwsFnbn.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-ijEXs--3.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-CALyU0pe.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-sdlA-fUb.js} +1 -1
  7. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-DtRzghn5.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-DApeu7x8.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-B7qLXRAH.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-DtStfv1H.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-ydfnwepc.js} +1 -1
  14. package/dist/assets/index-CtxruO1L.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/develop/SKILL.md +26 -19
  23. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  32. package/scripts/README.md +1 -0
  33. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  34. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  35. package/scripts/ops-sweep.cjs +53 -23
  36. package/scripts/scheduler-mcp-server.cjs +200 -18
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/config.cjs +112 -8
  39. package/src/main/docEdit.cjs +6 -1
  40. package/src/main/files.cjs +7 -27
  41. package/src/main/health.cjs +48 -15
  42. package/src/main/historyAggregator.cjs +88 -5
  43. package/src/main/historyDashboard.cjs +69 -4
  44. package/src/main/index.cjs +56 -2
  45. package/src/main/ipcSchemas.cjs +112 -16
  46. package/src/main/lib/AGENTS.md +54 -0
  47. package/src/main/lib/CLAUDE.md +1 -54
  48. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  49. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  50. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  51. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  52. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  53. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  54. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  55. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  56. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  57. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  58. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  59. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  60. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  61. package/src/main/lib/ephemeralCwd.cjs +37 -2
  62. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  63. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  64. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  65. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  66. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  67. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  68. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  69. package/src/main/lib/externalContract.cjs +31 -5
  70. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  71. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  72. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  73. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  75. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  76. package/src/main/lib/git/branchSweep.cjs +209 -4
  77. package/src/main/lib/git/gitWorktree.cjs +41 -5
  78. package/src/main/lib/guardShims.cjs +1 -1
  79. package/src/main/lib/historyRollup.cjs +26 -0
  80. package/src/main/lib/insideHome.cjs +27 -1
  81. package/src/main/lib/mcpToolCatalog.cjs +122 -12
  82. package/src/main/lib/mdDocCensus.cjs +59 -78
  83. package/src/main/lib/mdDocRefs.cjs +71 -93
  84. package/src/main/lib/mdNetworkScan.cjs +245 -250
  85. package/src/main/lib/mdReviewRecord.cjs +22 -9
  86. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  87. package/src/main/lib/opsOwnership.cjs +18 -2
  88. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  89. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  90. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  91. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  92. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  93. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  96. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  97. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  98. package/src/main/lib/prd/prdCreate.cjs +351 -23
  99. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  100. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  101. package/src/main/lib/process/loginItem.cjs +171 -0
  102. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  103. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  104. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  105. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  106. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  107. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  108. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  109. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  110. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  111. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  112. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  113. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  114. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  115. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  116. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  117. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  118. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  119. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  120. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  121. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  122. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  123. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  124. package/src/main/lib/tasks/taskRun.cjs +313 -0
  125. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  126. package/src/main/loginItemIpc.cjs +35 -0
  127. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  128. package/src/main/projectPages.cjs +6 -15
  129. package/src/main/promptSessionEvents.cjs +9 -1
  130. package/src/main/queueOps.cjs +260 -3
  131. package/src/main/runVerify.cjs +53 -25
  132. package/src/main/scheduler/AGENTS.md +26 -0
  133. package/src/main/scheduler/CLAUDE.md +1 -26
  134. package/src/main/scheduler/budget.cjs +239 -9
  135. package/src/main/scheduler/cancelDependents.cjs +154 -0
  136. package/src/main/scheduler/prdParser.cjs +4 -1
  137. package/src/main/scheduler/starvation.cjs +20 -18
  138. package/src/main/scheduler.cjs +745 -64
  139. package/src/main/supervisor.cjs +5 -1
  140. package/src/main/templates/PRD_AUTHORING.md +6 -1
  141. package/src/main/validationQualityHandlers.cjs +199 -0
  142. package/src/main/webRemote.cjs +10 -2
  143. package/src/preload/api.d.ts +364 -21
  144. package/src/preload/apiSurface.json +89 -10
  145. package/src/preload/index.cjs +23 -2
  146. package/src/seed/agents/validator.md +19 -8
  147. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  148. package/dist/assets/History-DDnqaLyw.js +0 -2
  149. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  150. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -28,18 +28,48 @@ 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
+
38
+ // Cap on riskTools entries — mirrors ipcSchemas.cjs RiskToolsSchema.
39
+ const RISK_TOOLS_MAX = 20;
40
+
41
+ /**
42
+ * Validate + normalize a `riskTools` value — the ONE check shared by
43
+ * createPrd and scheduler.cjs's updatePrd so create and update can never
44
+ * disagree. Each entry must parse under toolRiskMarks.parseRule; entries are
45
+ * de-duplicated in order and capped at RISK_TOOLS_MAX.
46
+ * @returns {{ ok: true, value: string[] } | { ok: false, error: string }}
47
+ */
48
+ function normalizeRiskTools(value) {
49
+ if (!Array.isArray(value)) {
50
+ return { ok: false, error: 'riskTools must be an array of tool-risk rule strings when given' };
51
+ }
52
+ const seen = [];
53
+ for (const rule of value) {
54
+ if (parseToolRiskRule(rule) === null) {
55
+ 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>:*)` };
56
+ }
57
+ if (!seen.includes(rule)) seen.push(rule);
58
+ }
59
+ if (seen.length > RISK_TOOLS_MAX) {
60
+ return { ok: false, error: `riskTools has ${seen.length} entries; the maximum is ${RISK_TOOLS_MAX}` };
61
+ }
62
+ return { ok: true, value: seen };
63
+ }
36
64
  const { sizingWarnings } = require('./prdSizing.cjs');
37
65
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
38
66
  const { execGit } = require('../git/gitExec.cjs');
39
67
  const { extractRepoPathCandidates, worktreeReachWarnings } = require('./prdWorktreeReach.cjs');
40
68
  const { isSweepValidatorSlug } = require('../epic/epicSweepValidator.cjs');
41
- const { validateGate, validateFiles, renderFilesSection, renderGateSection } = require('./prdGateFiles.cjs');
69
+ const { validateGate, validateFiles, renderFilesSection, renderGateSection, parseFilesSection } = require('./prdGateFiles.cjs');
70
+ const { filesOverlap } = require('../scheduler/schedulerBatch.cjs');
42
71
  const { resolveGate, parseChain, isNoneGate } = require('../scheduler/definitionOfDone.cjs');
72
+ const { MISS_KINDS } = require('../scheduler/validatorVerdictSchema.cjs');
43
73
 
44
74
  // A caller-supplied slug that already starts with its own `NN-` (e.g.
45
75
  // "254-perf-x") used to silently become the double-prefixed row
@@ -89,8 +119,8 @@ function isValidMacroId(id) {
89
119
  function buildPrdBody(input) {
90
120
  const {
91
121
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
92
- implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort,
93
- gate, files, budgetExempt,
122
+ implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort, riskTools,
123
+ gate, files, budgetExempt, fixes,
94
124
  } = input;
95
125
 
96
126
  // No `parallelGroup` frontmatter key (PRD_AUTHORING.md §5) — the NN-
@@ -126,6 +156,10 @@ function buildPrdBody(input) {
126
156
  fmLines.push(`agentType: ${agentType || DEFAULT_PRD_AGENT_TYPE}`);
127
157
  // Explicit ordering (PRD 832): replaces the retired shared-NN convention.
128
158
  if (dependsOn && dependsOn.length) fmLines.push(`dependsOn: [${dependsOn.join(', ')}]`);
159
+ // Earlier PRDs this one repairs (validator-miss / escape link) — one-line JSON
160
+ // array, already validated and resolved to NN slugs by createPrd(); see
161
+ // prdFrontmatter.cjs's applyKey for the matching parse.
162
+ if (Array.isArray(fixes) && fixes.length) fmLines.push(`fixes: ${serializeFixes(fixes)}`);
129
163
  // Wave-authoring decision (scheduler wave-disposition PRD) — only ever set
130
164
  // when createPrd() actually had a disposition to record (see the call
131
165
  // site above); a first-ever PRD in an Epic, or one with its own explicit
@@ -144,6 +178,8 @@ function buildPrdBody(input) {
144
178
  // prdFrontmatter.cjs's applyKey for the matching "only true opts in" parse.
145
179
  if (isValidMacroId(macroId)) fmLines.push(`macroId: ${macroId}`);
146
180
  if (PRD_EFFORT_LEVELS.includes(effort)) fmLines.push(`effort: ${effort}`);
181
+ // Risky tools this PRD is cleared to call — validated + de-duplicated by createPrd().
182
+ if (Array.isArray(riskTools) && riskTools.length) fmLines.push(`riskTools: ${formatQuotedInlineList(riskTools)}`);
147
183
  if (quietMachine === true) fmLines.push('quietMachine: true');
148
184
  // Budget exemption is for a sweep validator that cannot be split further;
149
185
  // every other caller's budgetExempt is ignored.
@@ -210,11 +246,22 @@ function resolveSourcePromptIdFromClaudeSession(cwd, claudeSessionId) {
210
246
  * worktree). execGit has no stdin, so candidates go as argv after `--` (still one call). Exit 1 =
211
247
  * nothing ignored; any other failure (not a repo, timeout) is swallowed — never blocks the write.
212
248
  */
249
+ const PLAN_RECORDS_PREFIX = 'session-manager-operations/plan-records/';
250
+
251
+ /** True when `files` is a non-empty list whose every entry is under plan-records/. */
252
+ function isPlanRecordOnlyFiles(files) {
253
+ return Array.isArray(files) && files.length > 0
254
+ && files.every((f) => typeof f === 'string' && f.startsWith(PLAN_RECORDS_PREFIX) && f.length > PLAN_RECORDS_PREFIX.length);
255
+ }
256
+
213
257
  async function worktreeReachAdvisory(input, cwd) {
214
258
  try {
215
259
  const text = [input.goal, ...(Array.isArray(input.acceptanceCriteria) ? input.acceptanceCriteria : []),
216
260
  input.implementationNotes].filter((s) => typeof s === 'string').join('\n');
217
- const candidates = extractRepoPathCandidates(text);
261
+ // Plan records are gitignored on purpose: the job writes them in its
262
+ // worktree and the scheduler harvests them to the main checkout, so
263
+ // naming one is not a worktree-reach mistake.
264
+ const candidates = extractRepoPathCandidates(text).filter((p) => !p.startsWith(PLAN_RECORDS_PREFIX));
218
265
  if (candidates.length === 0) return [];
219
266
  const out = await execGit(cwd, ['check-ignore', '--', ...candidates], { timeout: 10000 });
220
267
  const ignored = out.split('\n').map((l) => l.trim()).filter(Boolean);
@@ -239,10 +286,172 @@ async function worktreeReachAdvisory(input, cwd) {
239
286
  */
240
287
  const inFlightCreates = new Set();
241
288
 
242
- async function createPrd(input, remote) {
289
+ const nnOf = (slug) => {
290
+ const m = /^(\d+)-/.exec(slug);
291
+ return m ? Number(m[1]) : -1;
292
+ };
293
+
294
+ /**
295
+ * Map each `dependsOn` entry to the full NN slug it names, in priority order: a
296
+ * batch sibling's bare slug (kept bare; the batch path rewrites it after NN
297
+ * allocation), an exact existing slug, then bare-name matches in the new PRD's own
298
+ * Epic, then bare-name matches anywhere. Within the chosen tier the highest NN (the
299
+ * most recent same-name PRD) wins. A bare match spanning more than one Epic yields a
300
+ * warning naming every candidate and the one chosen. Entries that resolve to nothing
301
+ * are kept verbatim (the FK check above already refused those when it could read).
302
+ */
303
+ function resolveDependsOnToFullSlugs(dependsOn, rows, { epicId = null, siblingSlugs = [] } = {}) {
304
+ const slugs = rows.map((r) => r.slug);
305
+ const epicBySlug = new Map(rows.map((r) => [r.slug, epicOf(r)]));
306
+ const siblings = new Set(siblingSlugs);
307
+ const out = [];
308
+ const siblingDeps = [];
309
+ const warnings = [];
310
+ for (const dep of dependsOn) {
311
+ if (siblings.has(dep)) { out.push(dep); siblingDeps.push(dep); continue; }
312
+ const matches = resolveDepSlug(dep, slugs);
313
+ if (matches.length === 0) { out.push(dep); continue; }
314
+ if (matches.length === 1 && matches[0] === dep) { out.push(dep); continue; }
315
+ const sameEpic = epicId != null ? matches.filter((m) => epicBySlug.get(m) === epicId) : [];
316
+ const tier = sameEpic.length ? sameEpic : matches;
317
+ const chosen = [...tier].sort((a, b) => nnOf(b) - nnOf(a) || b.localeCompare(a))[0];
318
+ const epics = new Set(matches.map((m) => epicBySlug.get(m) ?? null));
319
+ if (epics.size > 1) {
320
+ const list = matches.map((m) => `${m} (Epic ${epicBySlug.get(m) ?? 'none'})`).join(', ');
321
+ warnings.push(`dependsOn "${dep}" matches PRDs in more than one Epic: ${list}. Stored as "${chosen}". ` +
322
+ 'Pass the exact NN-prefixed slug if you meant another one.');
323
+ }
324
+ out.push(chosen);
325
+ }
326
+ return { dependsOn: Array.from(new Set(out)), siblingDeps, warnings };
327
+ }
328
+
329
+ const FIXES_MAX = 20;
330
+ const FIX_REASON_MAX = 200;
331
+
332
+ /** Serialize resolved fixes as the one-line JSON array prdFrontmatter.cjs parses. */
333
+ function serializeFixes(fixes) {
334
+ return JSON.stringify(fixes.map((f) => ({ prd: f.prd, missKind: f.missKind, reason: f.reason })));
335
+ }
336
+
337
+ /**
338
+ * Shape check for the optional `fixes` input: 1-FIXES_MAX entries of
339
+ * { prd, missKind (one of MISS_KINDS), reason (one line, 1-200 chars) }, none
340
+ * naming the PRD being created. Returns one error string per bad entry, each
341
+ * naming its index.
342
+ */
343
+ function validateFixesShape(fixes, selfSlug) {
344
+ if (!Array.isArray(fixes)) return ['fixes must be an array of { prd, missKind, reason }'];
345
+ if (fixes.length < 1 || fixes.length > FIXES_MAX) return [`fixes must have 1-${FIXES_MAX} entries (got ${fixes.length})`];
346
+ const errors = [];
347
+ fixes.forEach((f, i) => {
348
+ const at = `fixes[${i}]`;
349
+ if (f == null || typeof f !== 'object' || Array.isArray(f)) { errors.push(`${at}: must be an object { prd, missKind, reason }`); return; }
350
+ if (typeof f.prd !== 'string' || !/^\S+$/.test(f.prd)) {
351
+ errors.push(`${at}.prd: must be the NN-slug or bare slug of an existing PRD`);
352
+ } else if (f.prd === selfSlug) {
353
+ errors.push(`${at}.prd: "${f.prd}" names this PRD itself`);
354
+ }
355
+ if (!MISS_KINDS.includes(f.missKind)) errors.push(`${at}.missKind: must be one of ${MISS_KINDS.join(', ')}`);
356
+ if (typeof f.reason !== 'string' || f.reason.trim() === '') errors.push(`${at}.reason: must be a non-empty string`);
357
+ else if (/[\r\n]/.test(f.reason)) errors.push(`${at}.reason: must be one line`);
358
+ else if (f.reason.length > FIX_REASON_MAX) errors.push(`${at}.reason: must be at most ${FIX_REASON_MAX} chars (got ${f.reason.length})`);
359
+ });
360
+ return errors;
361
+ }
362
+
363
+ /**
364
+ * Resolve each fixes[].prd to the full NN slug of an existing PRD in this project,
365
+ * with the same rule dependsOn uses (resolveDepSlug + resolveDependsOnToFullSlugs:
366
+ * exact slug, else bare name preferring the same Epic, highest NN).
367
+ */
368
+ function resolveFixes(fixes, rows, { epicId = null } = {}) {
369
+ const slugs = rows.map((r) => r.slug);
370
+ const errors = [];
371
+ const warnings = [];
372
+ const out = [];
373
+ fixes.forEach((f, i) => {
374
+ if (resolveDepSlug(f.prd, slugs).length === 0) {
375
+ const near = findNearMatches(f.prd, slugs);
376
+ errors.push(`fixes[${i}].prd: "${f.prd}" does not resolve to any existing PRD in this project.` +
377
+ (near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : ''));
378
+ return;
379
+ }
380
+ const r = resolveDependsOnToFullSlugs([f.prd], rows, { epicId });
381
+ warnings.push(...r.warnings.map((w) => w.replace(/^dependsOn /, `fixes[${i}].prd `)));
382
+ out.push({ prd: r.dependsOn[0], missKind: f.missKind, reason: f.reason });
383
+ });
384
+ return { fixes: out, errors, warnings };
385
+ }
386
+
387
+ /**
388
+ * Cross-Epic duplicate guard (2026-11-22 Self stall: 1047-sm-contract-client and
389
+ * 1056-sm-contract-client queued ~2 minutes apart from two Epics). Pure: returns
390
+ * every listing row whose bare slug equals `newBareSlug` and whose `epicId` is set
391
+ * and differs from `epicId`. Rows with no epicId (retired flat layout) are ignored;
392
+ * live and archived rows of any status count.
393
+ */
394
+ function findCrossEpicDuplicates(newBareSlug, epicId, rows) {
395
+ if (!newBareSlug || !Array.isArray(rows)) return [];
396
+ const target = bareSlug(newBareSlug);
397
+ return rows.filter((r) => r && typeof r.slug === 'string'
398
+ && r.epicId != null && r.epicId !== ''
399
+ && r.epicId !== (epicId ?? null)
400
+ && bareSlug(r.slug) === target);
401
+ }
402
+
403
+ function crossEpicDuplicateError(slug, dups) {
404
+ const list = dups.map((r) => `${r.slug} (Epic ${r.epicId}, status ${r.status ?? 'unknown'})`).join('; ');
405
+ const slugs = dups.map((r) => r.slug);
406
+ return `A PRD with slug "${slug}" already exists in another Epic: ${list}. ` +
407
+ `Add ${slugs.length === 1 ? 'it' : 'them'} to dependsOn instead of queueing the same work twice, ` +
408
+ `or pass allowDuplicateOf: [${slugs.join(', ')}] to create a deliberate duplicate.`;
409
+ }
410
+
411
+ /**
412
+ * Cross-Epic files-overlap advisory (2026-11-22 Self stall: 1047 and 1056 also
413
+ * declared the same files). Dispatch already serializes overlapping files, so
414
+ * this only WARNS — never refuses. Candidates: listing rows of another Epic
415
+ * whose status is pending/running/investigating. A row's `files` is used when
416
+ * present, else its `# Files` section is read via remote.readPrd + the shared
417
+ * parseFilesSection. Overlap uses the scheduler's own filesOverlap rule.
418
+ */
419
+ const OVERLAP_ACTIVE_STATUSES = new Set(['pending', 'running', 'investigating']);
420
+ async function crossEpicFilesOverlapWarnings(newFiles, epicId, rows, remote, cwd) {
421
+ if (!Array.isArray(newFiles) || !newFiles.length || !Array.isArray(rows)) return [];
422
+ const warnings = [];
423
+ for (const r of rows) {
424
+ if (!r || typeof r.slug !== 'string' || !OVERLAP_ACTIVE_STATUSES.has(r.status)) continue;
425
+ if (r.epicId == null || r.epicId === '' || r.epicId === (epicId ?? null)) continue;
426
+ let otherFiles = Array.isArray(r.files) ? r.files : null;
427
+ if (!otherFiles) {
428
+ try {
429
+ const read = typeof remote?.readPrd === 'function' ? await remote.readPrd(r.slug, cwd) : null;
430
+ otherFiles = read?.ok ? parseFilesSection(read.text) : [];
431
+ } catch { otherFiles = []; }
432
+ }
433
+ if (!filesOverlap(newFiles, otherFiles)) continue;
434
+ const pairs = [];
435
+ for (const a of newFiles) {
436
+ for (const b of otherFiles) {
437
+ if (filesOverlap([a], [b])) pairs.push(a === b ? a : `${a} ~ ${b}`);
438
+ }
439
+ }
440
+ warnings.push(`Files overlap with ${r.slug} (Epic ${r.epicId}, status ${r.status}): ${pairs.join(', ')}. ` +
441
+ 'Dispatch will serialize the two; add it to dependsOn if this PRD needs its changes first.');
442
+ }
443
+ return warnings;
444
+ }
445
+
446
+ /**
447
+ * createPrd(input, remote, opts?) — opts.internalMint: true marks a scheduler-
448
+ * internal mint (defaultScheduleSettle's validate-sweep validators), which skips
449
+ * the cross-Epic duplicate guard.
450
+ */
451
+ async function createPrd(input, remote, opts = {}) {
243
452
  const ctl = { key: null };
244
453
  try {
245
- return await createPrdInner(input, remote, ctl);
454
+ return await createPrdInner(input, remote, ctl, { internalMint: opts?.internalMint === true });
246
455
  } finally {
247
456
  if (ctl.key) inFlightCreates.delete(ctl.key);
248
457
  }
@@ -403,6 +612,15 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
403
612
  if (input.parallelGroup != null) {
404
613
  console.warn(`[prdCreate] parallelGroup input is deprecated and ignored (got ${input.parallelGroup}) — numbers are unique per project; use dependsOn for ordering`);
405
614
  }
615
+ // Plan-record auto-declaration: a PRD whose every files entry is a plan
616
+ // record (gitignored runtime namespace, harvested by the scheduler) can
617
+ // never commit its output, so it is artifact-only by construction. Derived
618
+ // here, before the declaration checks below, so the same checks run on it.
619
+ // An explicit declaration, or a files list mixing in any other path, is
620
+ // left as the caller gave it.
621
+ if (input.deliverable == null && input.artifactPaths == null && isPlanRecordOnlyFiles(input.files)) {
622
+ input = { ...input, deliverable: 'artifact', artifactPaths: [...input.files] };
623
+ }
406
624
  // Artifact-only declaration (deliverable + artifactPaths): fail-closed,
407
625
  // checked BEFORE the NN allocation so a refusal burns no number.
408
626
  const hasArtifactPaths = Array.isArray(input.artifactPaths) && input.artifactPaths.length > 0;
@@ -434,6 +652,13 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
434
652
  if (input.effort != null && !PRD_EFFORT_LEVELS.includes(input.effort)) {
435
653
  return { ok: false, applied: false, status: 400, error: 'effort must be one of low, medium, high, xhigh, max when given' };
436
654
  }
655
+ // riskTools: tool-risk rule strings (toolRiskMarks.parseRule grammar) this PRD
656
+ // is cleared to call. Refused before NN allocation; de-duplicated in order.
657
+ if (input.riskTools != null) {
658
+ const rt = normalizeRiskTools(input.riskTools);
659
+ if (!rt.ok) return { ok: false, applied: false, status: 400, error: rt.error };
660
+ input = { ...input, riskTools: rt.value };
661
+ }
437
662
 
438
663
  // Fake-heading guard (gate-and-files-in-PRD-body unit): a caller-supplied
439
664
  // free-text field that itself contains a "# Gate" or "# Files" heading line
@@ -556,6 +781,58 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
556
781
  }
557
782
  }
558
783
 
784
+ // One full listing (slug/epicId/status per live + archived PRD) serves both the
785
+ // cross-Epic duplicate guard below and the dependsOn FK check after NN allocation.
786
+ // A read failure is skipped-with-a-warning, never a write outage.
787
+ const needCrossEpicGuard = opts.internalMint !== true;
788
+ let listing = null;
789
+ const hasFixes = input.fixes !== undefined && input.fixes !== null;
790
+ if (needCrossEpicGuard || hasFixes || (input.dependsOn && input.dependsOn.length) || (filesList && filesList.length)) {
791
+ try {
792
+ listing = opts.listingCache
793
+ ? await (opts.listingCache.promise ??= remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER }))
794
+ : await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
795
+ } catch (e) {
796
+ console.warn(`[prdCreate] listPrds failed (cross-Epic duplicate + dependsOn checks skipped): ${e?.message ?? e}`);
797
+ listing = null;
798
+ }
799
+ }
800
+
801
+ // Cross-Epic duplicate guard: refused before NN allocation so it burns no number.
802
+ let duplicateAllowed = null;
803
+ if (needCrossEpicGuard && listing) {
804
+ const dups = findCrossEpicDuplicates(slug, input.sourcePromptId ?? null, listing.prds ?? []);
805
+ if (dups.length) {
806
+ const allowed = new Set(Array.isArray(input.allowDuplicateOf) ? input.allowDuplicateOf : []);
807
+ if (!dups.every((r) => allowed.has(r.slug))) {
808
+ return { ok: false, applied: false, status: 409, error: crossEpicDuplicateError(slug, dups) };
809
+ }
810
+ duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
811
+ }
812
+ }
813
+
814
+ // Cross-Epic files-overlap advisory: a warning, never a refusal.
815
+ if (listing && filesList && filesList.length) {
816
+ extraWarnings.push(...await crossEpicFilesOverlapWarnings(filesList, input.sourcePromptId ?? null, listing.prds ?? [], remote, input.cwd));
817
+ }
818
+
819
+ // fixes: shape-checked and resolved to full NN slugs before NN allocation, so a
820
+ // refusal burns no number. Fail-closed when the listing could not be read — an
821
+ // unresolved fixes link would miscount escapes.
822
+ if (hasFixes) {
823
+ const shapeErrors = validateFixesShape(input.fixes, slug);
824
+ if (shapeErrors.length) {
825
+ return { ok: false, applied: false, status: 400, error: shapeErrors.join('; ') };
826
+ }
827
+ if (!listing) {
828
+ return { ok: false, applied: false, status: 503, error: 'fixes could not be checked: the PRD listing for this project could not be read — retry' };
829
+ }
830
+ const r = resolveFixes(input.fixes, listing.prds ?? [], { epicId: input.sourcePromptId ?? null });
831
+ if (r.errors.length) return { ok: false, applied: false, status: 400, error: r.errors.join('; ') };
832
+ extraWarnings.push(...r.warnings);
833
+ input = { ...input, fixes: r.fixes };
834
+ }
835
+
559
836
  // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
560
837
  const nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
561
838
  const filenameSlug = `${nn}-${slug}`;
@@ -636,13 +913,6 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
636
913
  // write in the project.
637
914
  let depRows = null;
638
915
  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
916
  if (listing) {
647
917
  depRows = listing.prds ?? [];
648
918
  const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
@@ -660,12 +930,33 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
660
930
  }
661
931
  }
662
932
 
933
+ // Store every dependsOn entry as the full NN slug it resolved to (queue rows keep
934
+ // dependsOn verbatim, so a bare name would silently re-point at a later same-name
935
+ // PRD). Batch siblings stay bare here — createPrdBatch rewrites them to the
936
+ // sibling's allocated slug once NNs exist — and are excluded from planId
937
+ // inheritance (they share the batch's planId).
938
+ const batchSiblingDeps = new Set();
939
+ if (input.dependsOn && input.dependsOn.length && depRows) {
940
+ const resolvedDeps = resolveDependsOnToFullSlugs(input.dependsOn, depRows, {
941
+ epicId: input.sourcePromptId ?? null,
942
+ siblingSlugs: opts.extraDepSlugs ?? [],
943
+ });
944
+ for (const d of resolvedDeps.siblingDeps) batchSiblingDeps.add(d);
945
+ extraWarnings.push(...resolvedDeps.warnings);
946
+ input = { ...input, dependsOn: resolvedDeps.dependsOn };
947
+ }
948
+
663
949
  // planId is API-owned: any caller-supplied value is discarded. Inherited from the
664
950
  // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
665
951
  // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
666
952
  let planId = null;
667
953
  if (input.dependsOn && input.dependsOn.length && depRows) {
668
- const inherited = resolveInheritedPlanId(input.dependsOn, depRows);
954
+ const inherited = resolveInheritedPlanId(
955
+ input.dependsOn.filter((d) => !batchSiblingDeps.has(d)),
956
+ depRows,
957
+ // Scoped only when this PRD has an Epic: an Epic-less PRD has no plan boundary to protect.
958
+ input.sourcePromptId ? { epicId: input.sourcePromptId } : {},
959
+ );
669
960
  planId = inherited.planId;
670
961
  if (inherited.diverged) {
671
962
  console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
@@ -703,7 +994,7 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
703
994
  if (opts.dryRun) {
704
995
  return {
705
996
  ok: true, dryRun: true, slug, input, gateCommands, filesList,
706
- inheritedPlanId, warnings: [...extraWarnings, ...sizingWarnings(input)],
997
+ inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
707
998
  };
708
999
  }
709
1000
 
@@ -722,6 +1013,11 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
722
1013
  sourcePromptId: input.sourcePromptId ?? null,
723
1014
  sourceTabId: input.sourceTabId ?? null,
724
1015
  });
1016
+ if (duplicateAllowed) {
1017
+ appendAuditEvent('prd_create_duplicate_allowed', {
1018
+ cwd: input.cwd, slug: filenameSlug, sourcePromptId: input.sourcePromptId ?? null, duplicates: duplicateAllowed,
1019
+ });
1020
+ }
725
1021
  // Anonymous counter: enum-mapped agentType only (telemetryCounters.cjs).
726
1022
  telemetryCounters.trackPrdCreate({ agentType: input.agentType || DEFAULT_PRD_AGENT_TYPE });
727
1023
 
@@ -799,7 +1095,11 @@ const PRD_BATCH_MAX = 40;
799
1095
  * gap, not an inconsistency.
800
1096
  */
801
1097
  async function createPrdBatch(inputs, remote, opts = {}) {
802
- const fail = (errors) => ({ ok: false, applied: false, errors });
1098
+ // status: 409 when every refusal is a conflict (e.g. cross-Epic duplicate), else 400.
1099
+ const fail = (errors) => ({
1100
+ ok: false, applied: false, errors: errors.map(({ status: _s, ...e }) => e),
1101
+ status: errors.length && errors.every((e) => e.status === 409) ? 409 : 400,
1102
+ });
803
1103
  if (!Array.isArray(inputs) || inputs.length === 0) return fail([{ index: -1, slug: null, error: 'batch needs at least one entry' }]);
804
1104
  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
1105
 
@@ -822,10 +1122,14 @@ async function createPrdBatch(inputs, remote, opts = {}) {
822
1122
  const batchSlugs = slugs.filter(Boolean);
823
1123
 
824
1124
  // Pass 2: per-entry validation through createPrd's own checks.
1125
+ // Every entry is checked (all-or-nothing); one shared listing serves them all.
825
1126
  const prepared = [];
1127
+ const listingCache = {};
826
1128
  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; }
1129
+ const r = await createPrdInner(entries[i], remote, { key: null }, {
1130
+ dryRun: true, extraDepSlugs: batchSlugs, internalMint: opts.internalMint === true, listingCache,
1131
+ });
1132
+ if (!r.ok) { errors.push({ index: i, slug: slugs[i] ?? null, error: r.error, status: r.status }); continue; }
829
1133
  if (r.alreadyExisted) { errors.push({ index: i, slug: slugs[i], error: `slug "${slugs[i]}" already exists in this Epic as "${r.filename}"` }); continue; }
830
1134
  prepared.push(r);
831
1135
  }
@@ -867,13 +1171,25 @@ async function createPrdBatch(inputs, remote, opts = {}) {
867
1171
  } catch (e) { console.warn(`[prdCreate] batch rollback could not remove ${w.filenameSlug}: ${e?.message ?? e}`); }
868
1172
  }
869
1173
  };
1174
+ // Allocate every NN before writing anything, so a dep on a LATER sibling can be
1175
+ // rewritten to that sibling's full `${nn}-${slug}` too. Burned numbers on an
1176
+ // allocation failure leave a gap, never an inconsistency.
1177
+ const nns = [];
1178
+ try {
1179
+ for (const p of prepared) nns.push(await remote.allocateParallelGroup(p.input.cwd));
1180
+ } catch (e) {
1181
+ return fail([{ index: nns.length, slug: prepared[nns.length]?.slug ?? null, error: `NN allocation failed: ${e?.message ?? e}` }]);
1182
+ }
1183
+ const fullDeps = (deps) => (deps && deps.length
1184
+ ? Array.from(new Set(deps.map((d) => (firstIndex.has(d) ? `${nns[firstIndex.get(d)]}-${d}` : d))))
1185
+ : deps);
870
1186
  for (let i = 0; i < prepared.length; i++) {
871
1187
  const p = prepared[i];
872
1188
  let nn; let filenameSlug;
873
1189
  try {
874
- nn = await remote.allocateParallelGroup(p.input.cwd);
1190
+ nn = nns[i];
875
1191
  filenameSlug = `${nn}-${p.slug}`;
876
- const body = buildPrdBody({ ...p.input, planId, gate: p.gateCommands, files: p.filesList });
1192
+ const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
877
1193
  const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
878
1194
  if (!w?.ok) throw new Error(w?.error ?? 'write failed');
879
1195
  written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
@@ -890,6 +1206,12 @@ async function createPrdBatch(inputs, remote, opts = {}) {
890
1206
  cwd: p.input.cwd, slug: `${results[i].nn}-${p.slug}`, title: p.input.title,
891
1207
  sourcePromptId: p.input.sourcePromptId ?? null, sourceTabId: p.input.sourceTabId ?? null, batch: true,
892
1208
  });
1209
+ if (p.duplicateAllowed) {
1210
+ appendAuditEvent('prd_create_duplicate_allowed', {
1211
+ cwd: p.input.cwd, slug: `${results[i].nn}-${p.slug}`, sourcePromptId: p.input.sourcePromptId ?? null,
1212
+ duplicates: p.duplicateAllowed, batch: true,
1213
+ });
1214
+ }
893
1215
  telemetryCounters.trackPrdCreate({ agentType: p.input.agentType || DEFAULT_PRD_AGENT_TYPE });
894
1216
  }
895
1217
 
@@ -977,7 +1299,7 @@ function registerAdminRoute(adminHttp, remote) {
977
1299
  const { prds, ...envelope } = input;
978
1300
  const result = await createPrdBatch(prds, remote, envelope);
979
1301
  if (!result.ok) {
980
- sendJson(res, 400, { ok: false, applied: false, errors: result.errors });
1302
+ sendJson(res, result.status ?? 400, { ok: false, applied: false, errors: result.errors });
981
1303
  return;
982
1304
  }
983
1305
  sendJson(res, 200, { ok: true, applied: true, prds: result.prds });
@@ -985,6 +1307,7 @@ function registerAdminRoute(adminHttp, remote) {
985
1307
  }
986
1308
 
987
1309
  module.exports = {
1310
+ crossEpicFilesOverlapWarnings,
988
1311
  PRD_CREATE_SLUG_RE,
989
1312
  STANDARDS_PATH,
990
1313
  readStandards,
@@ -993,6 +1316,11 @@ module.exports = {
993
1316
  resolveSourcePromptIdFromClaudeSession,
994
1317
  createPrd,
995
1318
  createPrdBatch,
1319
+ normalizeRiskTools,
1320
+ RISK_TOOLS_MAX,
1321
+ findCrossEpicDuplicates,
1322
+ validateFixesShape,
1323
+ FIXES_MAX,
996
1324
  PRD_BATCH_MAX,
997
1325
  registerAdminRoute,
998
1326
  };
@@ -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 = [];