claude-code-session-manager 0.142.0 → 0.143.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -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');
@@ -440,16 +440,22 @@ function crossEpicDuplicateError(slug, dups) {
440
440
  * Cross-Epic files-overlap advisory (2026-11-22 Self stall: 1047 and 1056 also
441
441
  * declared the same files). Dispatch already serializes overlapping files, so
442
442
  * 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
443
+ * whose status is pending/running/investigating, plus live (not archived) rows
444
+ * whose status is null — a PRD file written moments ago has no queue row until
445
+ * the next reconcile pass, so the listing gives it status null (2026-11-24
446
+ * Bilko: 2005 named the same files as 2001, unreconciled, and got no warning).
447
+ * Archived, completed and cancelled rows never warn. A row's `files` is used when
444
448
  * present, else its `# Files` section is read via remote.readPrd + the shared
445
449
  * parseFilesSection. Overlap uses the scheduler's own filesOverlap rule.
446
450
  */
447
451
  const OVERLAP_ACTIVE_STATUSES = new Set(['pending', 'running', 'investigating']);
452
+ const isOverlapCandidate = (r) => OVERLAP_ACTIVE_STATUSES.has(r.status)
453
+ || (r.status == null && r.archived !== true);
448
454
  async function crossEpicFilesOverlapWarnings(newFiles, epicId, rows, remote, cwd) {
449
455
  if (!Array.isArray(newFiles) || !newFiles.length || !Array.isArray(rows)) return [];
450
456
  const warnings = [];
451
457
  for (const r of rows) {
452
- if (!r || typeof r.slug !== 'string' || !OVERLAP_ACTIVE_STATUSES.has(r.status)) continue;
458
+ if (!r || typeof r.slug !== 'string' || !isOverlapCandidate(r)) continue;
453
459
  if (r.epicId == null || r.epicId === '' || r.epicId === (epicId ?? null)) continue;
454
460
  let otherFiles = Array.isArray(r.files) ? r.files : null;
455
461
  if (!otherFiles) {
@@ -571,10 +577,14 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
571
577
  // caller didn't already give an explicit dependsOn (that already fixes
572
578
  // its position in some chain) — joining an Epic whose sourcePromptId this
573
579
  // PRD shares. See prdDisposition.cjs's header for the full contract.
580
+ // Slugs this pre-lock read saw: the in-lock same-Epic re-check refuses only rows
581
+ // written since (null = no pre-lock read, every same-Epic row counts as new).
582
+ let seenBeforeLock = null;
574
583
  if (input.sourcePromptId && (!input.dependsOn || input.dependsOn.length === 0)) {
575
584
  let epicRows = [];
576
585
  try {
577
586
  const listing = await remote.listPrds({ cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER });
587
+ seenBeforeLock = new Set((listing?.prds ?? []).map((r) => r?.slug));
578
588
  epicRows = (listing?.prds ?? []).filter((p) => p.sourcePromptId === input.sourcePromptId);
579
589
  } catch (e) {
580
590
  console.warn(`[prdCreate] disposition resolution skipped (listPrds failed): ${e?.message ?? e}`);
@@ -835,227 +845,266 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
835
845
  }
836
846
  }
837
847
 
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;
848
+ // Everything from the listing read through remote.writePrd runs as one phase.
849
+ // A real create runs it inside the per-project create lock on a FRESH listing
850
+ // (2026-11-24 Bilko 2001/2005: a create read its listing, awaited NN
851
+ // allocation, and wrote while another Epic's create wrote the same bare slug).
852
+ // A dry run (createPrdBatch's validate pass) takes no lock; the batch re-checks
853
+ // inside the lock itself. The phase returns an early-refusal / dry-run result,
854
+ // or null once the file is written (writeResult, nn, filenameSlug,
855
+ // duplicateAllowed and input are set on the closure).
856
+ let duplicateAllowed = null;
857
+ let nn;
858
+ let filenameSlug;
859
+ let writeResult;
860
+ const createPhase = async () => {
861
+ // One full listing (slug/epicId/status per live + archived PRD) serves both the
862
+ // cross-Epic duplicate guard below and the dependsOn FK check after NN allocation.
863
+ // A read failure is skipped-with-a-warning, never a write outage.
864
+ const needCrossEpicGuard = opts.internalMint !== true;
865
+ let listing = null;
866
+ const hasFixes = input.fixes !== undefined && input.fixes !== null;
867
+ // A real create always reads: the in-lock same-Epic re-check must not depend
868
+ // on which optional fields (fixes/dependsOn/files) the caller sends.
869
+ if (!opts.dryRun || needCrossEpicGuard || hasFixes || (input.dependsOn && input.dependsOn.length) || (filesList && filesList.length)) {
870
+ try {
871
+ const q = { cwd: input.cwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER };
872
+ if (!opts.dryRun) listing = await remote.listPrds({ ...q, fresh: true });
873
+ else if (opts.listingCache) listing = await (opts.listingCache.promise ??= remote.listPrds(q));
874
+ else listing = await remote.listPrds(q);
875
+ } catch (e) {
876
+ console.warn(`[prdCreate] listPrds failed (cross-Epic duplicate + dependsOn checks skipped): ${e?.message ?? e}`);
877
+ listing = null;
878
+ }
852
879
  }
853
- }
854
880
 
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) };
881
+ // Same-Epic re-check on the fresh listing, inside the lock: a same-Epic create
882
+ // that wrote this bare slug since the pre-lock reads is refused here,
883
+ // before NN allocation, with the directory scan's own wording.
884
+ if (!opts.dryRun && listing && input.sourcePromptId && !isFixPlanSlug(`0-${slug}`)) {
885
+ const target = bareSlug(slug);
886
+ const same = (listing.prds ?? []).find((r) => r && typeof r.slug === 'string'
887
+ && r.epicId === input.sourcePromptId && !(seenBeforeLock && seenBeforeLock.has(r.slug))
888
+ && bareSlug(r.slug) === target);
889
+ if (same) {
890
+ return {
891
+ ok: false, applied: false,
892
+ status: 409,
893
+ error: `A PRD with slug "${slug}" already exists in this Epic as "${same.slug}.md". Its work may already have landed. ` +
894
+ 'Use scheduler_update_prd / scheduler_reset_job on it, or pick a distinct slug.',
895
+ };
863
896
  }
864
- duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
865
897
  }
866
- }
867
898
 
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
- }
899
+ // Cross-Epic duplicate guard: refused before NN allocation so it burns no number.
900
+ if (needCrossEpicGuard && listing) {
901
+ const dups = findCrossEpicDuplicates(slug, input.sourcePromptId ?? null, listing.prds ?? []);
902
+ if (dups.length) {
903
+ const allowed = new Set(Array.isArray(input.allowDuplicateOf) ? input.allowDuplicateOf : []);
904
+ if (!dups.every((r) => allowed.has(r.slug))) {
905
+ return { ok: false, applied: false, status: 409, error: crossEpicDuplicateError(slug, dups) };
906
+ }
907
+ duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
908
+ }
909
+ }
872
910
 
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('; ') };
911
+ // Cross-Epic files-overlap advisory: a warning, never a refusal.
912
+ // Skipped on a dry run: createPrdBatch re-runs it on a fresh listing inside the
913
+ // create lock, so the batch never reports a warning twice.
914
+ if (!opts.dryRun && listing && filesList && filesList.length) {
915
+ extraWarnings.push(...await crossEpicFilesOverlapWarnings(filesList, input.sourcePromptId ?? null, listing.prds ?? [], remote, input.cwd));
880
916
  }
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' };
917
+
918
+ // fixes: shape-checked and resolved to full NN slugs before NN allocation, so a
919
+ // refusal burns no number. Fail-closed when the listing could not be read — an
920
+ // unresolved fixes link would miscount escapes.
921
+ if (hasFixes) {
922
+ const shapeErrors = validateFixesShape(input.fixes, slug);
923
+ if (shapeErrors.length) {
924
+ return { ok: false, applied: false, status: 400, error: shapeErrors.join('; ') };
925
+ }
926
+ if (!listing) {
927
+ return { ok: false, applied: false, status: 503, error: 'fixes could not be checked: the PRD listing for this project could not be read — retry' };
928
+ }
929
+ const r = resolveFixes(input.fixes, listing.prds ?? [], { epicId: input.sourcePromptId ?? null });
930
+ if (r.errors.length) return { ok: false, applied: false, status: 400, error: r.errors.join('; ') };
931
+ extraWarnings.push(...r.warnings);
932
+ input = { ...input, fixes: r.fixes };
883
933
  }
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
934
 
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
- }
935
+ // Dry run burns no number: a placeholder keeps the filename-shaped guards below meaningful.
936
+ nn = opts.dryRun ? 9999999 : await remote.allocateParallelGroup(input.cwd);
937
+ filenameSlug = `${nn}-${slug}`;
938
+
939
+ // Fix-chain depth guard (PRD 1113): refuse a fix-of-a-fix before it's ever
940
+ // written. depth >= 2 means the base job has already failed to close via
941
+ // at least one prior fix attempt for reasons a repeat attempt won't
942
+ // resolve — checked first so this distinct, human-escalation error still
943
+ // wins over the more general fix-plan-slug guard below for that shape.
944
+ const chainDepth = fixChainDepthOf(filenameSlug);
945
+ if (chainDepth > FIX_CHAIN_DEPTH_CAP) {
946
+ const base = baseSlugOf(filenameSlug);
947
+ return {
948
+ ok: false, applied: false,
949
+ status: 409,
950
+ error: `Fix-chain depth cap exceeded: "${base}" has already failed to close ${chainDepth} time(s) for ` +
951
+ `infrastructure reasons (refusing to write "${filenameSlug}.md" at depth ${chainDepth}). Authoring a ` +
952
+ 'deeper fix PRD is not the correct response — stop and surface this to a human instead of retrying again.',
953
+ };
954
+ }
910
955
 
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
- }
956
+ // Fix-plan-slug collision guard (PRD 1131): a caller-supplied or
957
+ // title-derived slug that happens to start with "fix-" collides with the
958
+ // scheduler's own NN-fix-... naming convention for fix plans it authors
959
+ // itself (spawnInvestigation) — and that shape carries real special-case
960
+ // semantics (depth-capped auto-investigation eligibility,
961
+ // commitGuardVerdict's zero-edit exemption) that a PRD authored through
962
+ // this API never asked for. Refused outright, not silently renamed, same
963
+ // fail-closed posture as the SLUG_HAS_NN_PREFIX_RE check above (PRD 1126:
964
+ // "126-fix-plan-death-reopens-parent" was wrongly stamped
965
+ // investigationDepth before it ever ran and had to be withdrawn). This
966
+ // subsumes the depth-1 case the chain-depth guard above deliberately let
967
+ // through (MAX_INVESTIGATION_DEPTH=1 means a first fix-plan is legitimate
968
+ // — but only when spawnInvestigation authors it, never through this API).
969
+ if (isFixPlanSlug(filenameSlug)) {
970
+ return {
971
+ ok: false, applied: false,
972
+ status: 400,
973
+ error: `slug "${filenameSlug}" collides with the reserved NN-fix-... fix-plan naming convention ` +
974
+ '(reserved for PRDs the scheduler\'s own investigation loop authors itself). Reword the title/slug ' +
975
+ 'so it does not start with "fix-" — e.g. "resolve-x" or "repair-x" instead of "fix-x".',
976
+ };
977
+ }
933
978
 
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
- }
979
+ // An explicit `parallelGroup` bypasses allocateParallelGroup()'s
980
+ // collision-proof reservation, so re-check for an existing file at
981
+ // this exact destination before writing — remote.writePrd itself has
982
+ // no existence guard (by design, it doubles as the edit-in-place
983
+ // path for Scheduler UI PRD edits), so "create" must not silently
984
+ // clobber an existing job's PRD.
985
+ const existing = opts.dryRun ? null : await remote.readPrd(filenameSlug, input.cwd);
986
+ if (existing?.ok) {
987
+ return { ok: false, applied: false, status: 409, error: `PRD already exists: ${filenameSlug}.md` };
988
+ }
944
989
 
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' };
990
+ // Write-time FK check (throw on write, report on read — see
991
+ // prdAgentType.cjs's header): a caller-supplied agentType that doesn't
992
+ // resolve to a readable persona file is rejected before anything is
993
+ // written, naming the available personas. A no-op when agentType is
994
+ // omitted — buildPrdBody fills in DEFAULT_PRD_AGENT_TYPE for that case,
995
+ // and the default persona is trusted without a lookup.
996
+ if (input.agentType) {
997
+ try {
998
+ await assertAgentTypeWritable(input.cwd, input.agentType);
999
+ } catch (e) {
1000
+ return { ok: false, applied: false, status: 400, error: e?.message ?? 'invalid agentType' };
1001
+ }
1002
+ }
1003
+
1004
+ // Write-time FK check for dependsOn (report on read / throw on write — see
1005
+ // prdAgentType.cjs's header): every entry must resolve to a PRD that
1006
+ // actually exists in this project, using the SAME resolution rule
1007
+ // schedulerBatch.cjs's findBlockingDep applies at run time (exact slug,
1008
+ // else bare-name after stripping one leading `NN-`) — a dep that
1009
+ // validates here is guaranteed to be a dep findBlockingDep can actually
1010
+ // see later. A listPrds() read failure is skipped-with-a-warning, never a
1011
+ // write outage: an I/O hiccup on the read side must not block every PRD
1012
+ // write in the project.
1013
+ let depRows = null;
1014
+ if (input.dependsOn && input.dependsOn.length) {
1015
+ if (listing) {
1016
+ depRows = listing.prds ?? [];
1017
+ const candidateSlugs = [...depRows.map((p) => p.slug), ...(opts.extraDepSlugs ?? [])];
1018
+ for (const dep of input.dependsOn) {
1019
+ if (resolveDepSlug(dep, candidateSlugs).length > 0) continue;
1020
+ const near = findNearMatches(dep, candidateSlugs);
1021
+ const suggestion = near.length ? ` Closest existing slug(s): ${near.join(', ')}.` : '';
1022
+ return {
1023
+ ok: false, applied: false,
1024
+ status: 400,
1025
+ error: `dependsOn entry "${dep}" does not resolve to any existing PRD in this project.${suggestion} ` +
1026
+ 'Pass the bare name (preferred) or the exact NN-prefixed slug of an existing PRD.',
1027
+ };
1028
+ }
1029
+ }
956
1030
  }
957
- }
958
1031
 
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(', ')}.` : '';
1032
+ // Store every dependsOn entry as the full NN slug it resolved to (queue rows keep
1033
+ // dependsOn verbatim, so a bare name would silently re-point at a later same-name
1034
+ // PRD). Batch siblings stay bare here — createPrdBatch rewrites them to the
1035
+ // sibling's allocated slug once NNs exist — and are excluded from planId
1036
+ // inheritance (they share the batch's planId).
1037
+ const batchSiblingDeps = new Set();
1038
+ if (input.dependsOn && input.dependsOn.length && depRows) {
1039
+ const resolvedDeps = resolveDependsOnToFullSlugs(input.dependsOn, depRows, {
1040
+ epicId: input.sourcePromptId ?? null,
1041
+ siblingSlugs: opts.extraDepSlugs ?? [],
1042
+ });
1043
+ for (const d of resolvedDeps.siblingDeps) batchSiblingDeps.add(d);
1044
+ extraWarnings.push(...resolvedDeps.warnings);
1045
+ input = { ...input, dependsOn: resolvedDeps.dependsOn };
1046
+ }
1047
+
1048
+ // planId is API-owned: any caller-supplied value is discarded. Inherited from the
1049
+ // resolved dependencies (append terminals or explicit dependsOn) using the FK-check
1050
+ // listing above; otherwise (first-ever / new-head / legacy deps) freshly minted.
1051
+ let planId = null;
1052
+ if (input.dependsOn && input.dependsOn.length && depRows) {
1053
+ const inherited = resolveInheritedPlanId(
1054
+ input.dependsOn.filter((d) => !batchSiblingDeps.has(d)),
1055
+ depRows,
1056
+ // Scoped only when this PRD has an Epic: an Epic-less PRD has no plan boundary to protect.
1057
+ input.sourcePromptId ? { epicId: input.sourcePromptId } : {},
1058
+ );
1059
+ planId = inherited.planId;
1060
+ if (inherited.diverged) {
1061
+ console.warn(`[prdCreate] dependsOn spans plans ${inherited.diverged.join(', ')} — inheriting ${planId} (lowest-numbered dependency)`);
1062
+ }
1063
+ }
1064
+ const inheritedPlanId = planId;
1065
+ if (!planId) planId = mintPlanId();
1066
+
1067
+ const body = buildPrdBody({ ...input, planId, gate: gateCommands, files: filesList });
1068
+
1069
+ // Read-back check (gate-and-files-in-PRD-body unit): the whole point of a
1070
+ // declared gate is that the scheduler's own reader (resolveGate/parseChain
1071
+ // in definitionOfDone.cjs) gets back exactly what was declared. A stray
1072
+ // ```gate fence elsewhere in the body (goal/notes/criteria/out-of-scope)
1073
+ // would otherwise win — readExplicitGate takes the FIRST fence in the
1074
+ // text — and the scheduler would silently re-run the wrong gate. Caught
1075
+ // here, before the write, rather than discovered later from a job log.
1076
+ if (gateCommands) {
1077
+ const expectedSource = gateCommands.length === 1 && isNoneGate(gateCommands[0]) ? 'none' : 'explicit';
1078
+ const expectedSequence = expectedSource === 'none' ? [] : gateCommands.flatMap(parseChain);
1079
+ const resolved = resolveGate(body);
1080
+ const matches = resolved.source === expectedSource
1081
+ && JSON.stringify(resolved.sequence) === JSON.stringify(expectedSequence);
1082
+ if (!matches) {
977
1083
  return {
978
1084
  ok: false, applied: false,
979
1085
  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.',
1086
+ error: 'The PRD text already holds a gate fence (three backticks + gate), so the scheduler would read '
1087
+ + 'the wrong gate. Remove it from the goal, implementation notes, acceptance criteria, out of scope '
1088
+ + 'or files, and call again.',
982
1089
  };
983
1090
  }
984
1091
  }
985
- }
986
1092
 
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) {
1093
+ if (opts.dryRun) {
1038
1094
  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.',
1095
+ ok: true, dryRun: true, slug, input, gateCommands, filesList,
1096
+ inheritedPlanId, duplicateAllowed, warnings: [...extraWarnings, ...sizingWarnings(input)],
1044
1097
  };
1045
1098
  }
1046
- }
1047
1099
 
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
- }
1100
+ writeResult = await remote.writePrd(filenameSlug, body, input.cwd);
1101
+ if (!writeResult?.ok) {
1102
+ return { ok: false, applied: false, status: 500, error: writeResult?.error ?? 'write failed' };
1103
+ }
1104
+ return null;
1105
+ };
1106
+ const early = opts.dryRun ? await createPhase() : await withProjectCreateLock(cwd, createPhase);
1107
+ if (early) return early;
1059
1108
 
1060
1109
  // Trace-back point for "who/what created this PRD" (auditLog.cjs) — every
1061
1110
  // PRD write, whether from the admin/MCP route or the renderer's chat:create-prd
@@ -1142,6 +1191,19 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
1142
1191
 
1143
1192
  const PRD_BATCH_MAX = 40;
1144
1193
 
1194
+ /**
1195
+ * Per-project PRD-create lock (2026-11-24 Bilko 2001/2005: two Epics' batches
1196
+ * validated against listings read before either wrote, then both wrote the same
1197
+ * bare slug). Every PRD create runs in the app's main process (admin routes,
1198
+ * chat:create-prd IPC, in-process mints), so an in-process lock serializes them
1199
+ * all. Keyed by the resolved project cwd (p.input.cwd, already normalized from a
1200
+ * worktree path to the main checkout). Never activeIndexPath(cwd): remote.writePrd
1201
+ * -> ensureEpic takes that lock, so sharing it would deadlock.
1202
+ */
1203
+ function withProjectCreateLock(cwd, task) {
1204
+ return withPathLock(`${cwd}\u0000prd-create`, task);
1205
+ }
1206
+
1145
1207
  /**
1146
1208
  * Create several PRDs all-or-nothing. Every entry goes through createPrd's own
1147
1209
  * validation (dry run: no NN, no file); `dependsOn` may also name other entries
@@ -1228,37 +1290,98 @@ async function createPrdBatch(inputs, remote, opts = {}) {
1228
1290
  } catch (e) { console.warn(`[prdCreate] batch rollback could not remove ${w.filenameSlug}: ${e?.message ?? e}`); }
1229
1291
  }
1230
1292
  };
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;
1293
+ const projectCwd = prepared[0].input.cwd;
1294
+ const committed = await withProjectCreateLock(projectCwd, async () => {
1295
+ // Commit-time re-check on a FRESH listing, inside the lock: the validation pass
1296
+ // read its listing 15-25 s ago on a busy machine, and another Epic's create may
1297
+ // have written the same bare slug since. A read failure skips the re-check
1298
+ // (never a write outage).
1299
+ let freshListing = null;
1246
1300
  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 });
1301
+ freshListing = await remote.listPrds({ cwd: projectCwd, fields: 'full', limit: Number.MAX_SAFE_INTEGER, fresh: true });
1257
1302
  } catch (e) {
1258
- await rollback();
1259
- return fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]);
1303
+ console.warn(`[prdCreate] batch fresh listPrds failed (commit-time duplicate + files-overlap re-checks skipped): ${e?.message ?? e}`);
1304
+ freshListing = null;
1260
1305
  }
1261
- }
1306
+ const overlapWarnings = prepared.map(() => []);
1307
+ if (freshListing) {
1308
+ const freshRows = freshListing.prds ?? [];
1309
+ // Same-Epic rows already in the validation snapshot were judged by the
1310
+ // validation pass's own-Epic directory scan; only rows written since then
1311
+ // (a concurrent create in this Epic) are refused here.
1312
+ let seenAtValidation = new Set();
1313
+ try {
1314
+ const v = listingCache.promise ? await listingCache.promise : null;
1315
+ seenAtValidation = new Set((v?.prds ?? []).map((r) => r?.slug));
1316
+ } catch { /* validation read failed — every same-Epic row counts as new */ }
1317
+ const refused = [];
1318
+ for (let i = 0; i < prepared.length; i++) {
1319
+ const p = prepared[i];
1320
+ const epicId = p.input.sourcePromptId ?? null;
1321
+ if (opts.internalMint !== true) {
1322
+ const dups = findCrossEpicDuplicates(p.slug, epicId, freshRows);
1323
+ if (dups.length) {
1324
+ const allowed = new Set(Array.isArray(p.input.allowDuplicateOf) ? p.input.allowDuplicateOf : []);
1325
+ if (!dups.every((r) => allowed.has(r.slug))) {
1326
+ refused.push({ index: i, slug: p.slug, error: crossEpicDuplicateError(p.slug, dups), status: 409 });
1327
+ continue;
1328
+ }
1329
+ p.duplicateAllowed = dups.map((r) => ({ slug: r.slug, epicId: r.epicId, status: r.status ?? null }));
1330
+ } else {
1331
+ p.duplicateAllowed = null;
1332
+ }
1333
+ }
1334
+ if (epicId != null && !isFixPlanSlug(`0-${p.slug}`)) {
1335
+ const target = bareSlug(p.slug);
1336
+ const same = freshRows.find((r) => r && typeof r.slug === 'string' && r.epicId === epicId
1337
+ && !seenAtValidation.has(r.slug) && bareSlug(r.slug) === target);
1338
+ if (same) {
1339
+ refused.push({ index: i, slug: p.slug, error: `slug "${p.slug}" already exists in this Epic as "${same.slug}"`, status: 409 });
1340
+ continue;
1341
+ }
1342
+ }
1343
+ if (p.filesList && p.filesList.length) {
1344
+ overlapWarnings[i] = await crossEpicFilesOverlapWarnings(p.filesList, epicId, freshRows, remote, projectCwd);
1345
+ }
1346
+ }
1347
+ if (refused.length) return { failed: fail(refused) };
1348
+ }
1349
+ // Allocate every NN before writing anything, so a dep on a LATER sibling can be
1350
+ // rewritten to that sibling's full `${nn}-${slug}` too. Burned numbers on an
1351
+ // allocation failure leave a gap, never an inconsistency.
1352
+ const nns = [];
1353
+ try {
1354
+ for (const p of prepared) nns.push(await remote.allocateParallelGroup(p.input.cwd));
1355
+ } catch (e) {
1356
+ return { failed: fail([{ index: nns.length, slug: prepared[nns.length]?.slug ?? null, error: `NN allocation failed: ${e?.message ?? e}` }]) };
1357
+ }
1358
+ const fullDeps = (deps) => (deps && deps.length
1359
+ ? Array.from(new Set(deps.map((d) => (firstIndex.has(d) ? `${nns[firstIndex.get(d)]}-${d}` : d))))
1360
+ : deps);
1361
+ for (let i = 0; i < prepared.length; i++) {
1362
+ const p = prepared[i];
1363
+ let nn; let filenameSlug;
1364
+ try {
1365
+ nn = nns[i];
1366
+ filenameSlug = `${nn}-${p.slug}`;
1367
+ const body = buildPrdBody({ ...p.input, dependsOn: fullDeps(p.input.dependsOn), planId, gate: p.gateCommands, files: p.filesList });
1368
+ // A validated preflight must reach the file (PRD 3805 ran unheld when one
1369
+ // was lost); a body without the line rolls the whole batch back.
1370
+ if (p.input.preflight && !/^preflight: /m.test(body)) throw new Error('preflight was not written to the PRD frontmatter');
1371
+ const w = await remote.writePrd(filenameSlug, body, p.input.cwd);
1372
+ if (!w?.ok) throw new Error(w?.error ?? 'write failed');
1373
+ written.push({ filenameSlug, path: w.path ?? null, cwd: p.input.cwd });
1374
+ results.push({ slug: p.slug, nn, filename: `${filenameSlug}.md`, preflight: p.input.preflight || null, warnings: [...p.warnings, ...overlapWarnings[i]] });
1375
+ } catch (e) {
1376
+ await rollback();
1377
+ return { failed: fail([{ index: i, slug: p.slug, error: `write failed (batch rolled back): ${e?.message ?? e}` }]) };
1378
+ }
1379
+ }
1380
+ return { failed: null };
1381
+ });
1382
+ // Audit rows, telemetry and the bounded reconcile wait run after the lock is
1383
+ // released, so a 2 s reconcile never holds other creates.
1384
+ if (committed.failed) return committed.failed;
1262
1385
 
1263
1386
  for (let i = 0; i < prepared.length; i++) {
1264
1387
  const p = prepared[i];