claude-code-session-manager 0.98.0 → 0.101.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 (441) hide show
  1. package/README.md +3 -3
  2. package/bin/cli.cjs +16 -4
  3. package/bin/node-floor.cjs +41 -0
  4. package/dist/assets/DataModel-CXaH2GED.js +1 -0
  5. package/dist/assets/{History-Bfdoywlh.js → History-Cerii-HA.js} +2 -2
  6. package/dist/assets/{Hooks-CKDJjTJV.js → Hooks-aXMb5LDy.js} +3 -3
  7. package/dist/assets/{Library-7akfgy67.js → Library-WrJFKEOJ.js} +1 -1
  8. package/dist/assets/{MarkdownEditor-DDesiqet.js → MarkdownEditor-D1BMCXS7.js} +1 -1
  9. package/dist/assets/{McpServers-D4lZtXof.js → McpServers-Cf0davLd.js} +2 -2
  10. package/dist/assets/{Memory-CeI8G1w5.js → Memory-Dn6NHWPe.js} +6 -6
  11. package/dist/assets/Permissions-CTVuFPjg.js +3 -0
  12. package/dist/assets/{Plugins-P4eCXy_S.js → Plugins-C2TyF8Mn.js} +2 -2
  13. package/dist/assets/ProvenanceBadge-F_jwHSwE.js +1 -0
  14. package/dist/assets/{SaveBar-l9jnEMES.js → SaveBar-DA1KVJST.js} +1 -1
  15. package/dist/assets/Scheduler-Bm6Q_hlu.js +16 -0
  16. package/dist/assets/{ScopeSwitcher-CjJi8ST5.js → ScopeSwitcher-BygZlJca.js} +1 -1
  17. package/dist/assets/Settings-BYCiv5KV.js +3 -0
  18. package/dist/assets/{SkillReferenceGraph-CjbO01Sg.js → SkillReferenceGraph-CcLnl9np.js} +1 -1
  19. package/dist/assets/{Skills-BxZ9_fCR.js → Skills-ChffsdTD.js} +2 -2
  20. package/dist/assets/{SystemPrompt-D8vfFb8b.js → SystemPrompt-dNkfHE_M.js} +1 -1
  21. package/dist/assets/{TagLibrary-2vzUo7YL.js → TagLibrary-jVlEuB0m.js} +1 -1
  22. package/dist/assets/{TiptapBody-B8ZfbK90.js → TiptapBody-6_cdwcP0.js} +1 -1
  23. package/dist/assets/{Toggle-BbW4nGGf.js → Toggle-CVXqGpAP.js} +1 -1
  24. package/dist/assets/ViewTabs-DO1YVbpc.js +1 -0
  25. package/dist/assets/{index-CKH5Uxik.css → index-D89EUizB.css} +1 -1
  26. package/dist/assets/{index-Cd98Q1lD.js → index-DbCQPWWY.js} +747 -752
  27. package/dist/assets/{settingsSchema-IhUfucCF.js → settingsSchema-Wrvn-Yz1.js} +1 -1
  28. package/dist/index.html +2 -2
  29. package/package.json +25 -29
  30. package/plugins/CLAUDE.md +6 -6
  31. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +21 -19
  32. package/plugins/session-manager-dev/skills/builder/SKILL.md +3 -3
  33. package/plugins/session-manager-dev/skills/develop/SKILL.md +254 -510
  34. package/plugins/session-manager-dev/skills/develop/standards.md +17 -22
  35. package/scripts/README.md +3 -11
  36. package/scripts/audit-ops-hygiene.cjs +3 -3
  37. package/scripts/hooks/lib/guard-prd-writes-policy.cjs +1 -1
  38. package/scripts/hooks/lib/guard-self-schedule-policy.cjs +1 -1
  39. package/scripts/mint-epic.cjs +2 -3
  40. package/scripts/scheduler-mcp-server.cjs +64 -7
  41. package/src/main/agentLibrary.cjs +22 -2
  42. package/src/main/build-info.json +4 -4
  43. package/src/main/chatRunner.cjs +4 -3
  44. package/src/main/config.cjs +41 -38
  45. package/src/main/docEdit.cjs +4 -1
  46. package/src/main/files.cjs +2 -5
  47. package/src/main/health.cjs +1 -1
  48. package/src/main/index.cjs +40 -11
  49. package/src/main/ipcSchemas.cjs +35 -34
  50. package/src/main/lib/agentPersonaSchema.cjs +13 -2
  51. package/src/main/lib/atomicFs.cjs +116 -0
  52. package/src/main/lib/branchSweep.cjs +13 -12
  53. package/src/main/lib/buildTarget.cjs +3 -3
  54. package/src/main/lib/builtinMacros.cjs +39 -0
  55. package/src/main/lib/claudeCliCaps.cjs +129 -0
  56. package/src/main/lib/credentials.cjs +2 -4
  57. package/src/main/lib/crossProjectFeedback.cjs +3 -3
  58. package/src/main/lib/cwdClassify.cjs +15 -3
  59. package/src/main/lib/definitionOfDone.cjs +207 -125
  60. package/src/main/lib/dodDrainHook.cjs +11 -5
  61. package/src/main/lib/epicMint.cjs +2 -4
  62. package/src/main/lib/epicStatusMirror.cjs +8 -10
  63. package/src/main/lib/epicWorktreeProjectConfig.cjs +2 -4
  64. package/src/main/lib/gateAuthority.cjs +96 -0
  65. package/src/main/lib/gitExec.cjs +69 -0
  66. package/src/main/lib/gitWorktree.cjs +656 -92
  67. package/src/main/lib/instanceLock.cjs +5 -8
  68. package/src/main/lib/launchFailure.cjs +2 -3
  69. package/src/main/lib/macroLibrary.cjs +480 -0
  70. package/src/main/lib/mcpToolCatalog.cjs +49 -17
  71. package/src/main/lib/needsReviewLedger.cjs +1 -1
  72. package/src/main/lib/opsErrorLog.cjs +11 -1
  73. package/src/main/lib/opsOwnership.cjs +5 -9
  74. package/src/main/lib/pidAlive.cjs +32 -0
  75. package/src/main/lib/prdCreate.cjs +121 -12
  76. package/src/main/lib/prdDisposition.cjs +2 -2
  77. package/src/main/lib/prdGateFiles.cjs +284 -0
  78. package/src/main/lib/prdLocations.cjs +61 -0
  79. package/src/main/lib/prdMigration.cjs +2 -3
  80. package/src/main/lib/prdSizing.cjs +2 -1
  81. package/src/main/lib/projectHomeAdminRoutes.cjs +136 -21
  82. package/src/main/lib/promptSessionSchema.cjs +10 -2
  83. package/src/main/lib/rcaReport.cjs +4 -6
  84. package/src/main/lib/reaperHelpers.cjs +8 -1
  85. package/src/main/lib/reservationExpiry.cjs +6 -1
  86. package/src/main/lib/reviewNotice.cjs +263 -0
  87. package/src/main/lib/runClaudeP.cjs +4 -1
  88. package/src/main/lib/schedulerPaths.cjs +22 -2
  89. package/src/main/lib/sessionSlots.cjs +2 -4
  90. package/src/main/lib/shippedPersonaSeeds.cjs +226 -0
  91. package/src/main/lib/smfileHeaders.cjs +66 -0
  92. package/src/main/lib/timeoutShim.cjs +123 -0
  93. package/src/main/lib/timeoutShimScript.cjs +275 -0
  94. package/src/main/lib/upgradeDrain.cjs +4 -10
  95. package/src/main/lib/watchdogHelpers.cjs +12 -25
  96. package/src/main/lib/workTypeLibrary.cjs +7 -1
  97. package/src/main/projectPages.cjs +43 -13
  98. package/src/main/promptSessionEvents.cjs +37 -13
  99. package/src/main/scheduler.cjs +910 -198
  100. package/src/main/seedAgentPersonas.cjs +279 -24
  101. package/src/main/supervisor.cjs +4 -1
  102. package/src/main/templates/PRD_AUTHORING.md +126 -406
  103. package/src/preload/__tests__/preload-surface.test.cjs +68 -0
  104. package/src/preload/api.d.ts +53 -94
  105. package/src/preload/index.cjs +14 -9
  106. package/src/seed/agents/architect.md +2 -0
  107. package/src/seed/agents/demo-video-builder.md +84 -0
  108. package/src/seed/agents/dev-lead.md +18 -18
  109. package/src/seed/agents/project-home-builder.md +66 -35
  110. package/src/seed/agents/validator.md +10 -4
  111. package/dist/assets/DataModel-DCEgMTjH.js +0 -1
  112. package/dist/assets/HostBilko-CDVHE0hT.js +0 -1
  113. package/dist/assets/Permissions-BGleLja4.js +0 -3
  114. package/dist/assets/ProvenanceBadge-BFczzI1B.js +0 -1
  115. package/dist/assets/Scheduler-C_phpeUS.js +0 -16
  116. package/dist/assets/Settings-BIwZ3FGQ.js +0 -3
  117. package/src/main/__tests__/activeIndexMerge.test.cjs +0 -235
  118. package/src/main/__tests__/agentEffortResolve.test.cjs +0 -117
  119. package/src/main/__tests__/agentLibrary.test.cjs +0 -276
  120. package/src/main/__tests__/agentModelResolve.test.cjs +0 -311
  121. package/src/main/__tests__/agentOverlayWrite.test.cjs +0 -95
  122. package/src/main/__tests__/bilkoHost-deriveSlug.test.cjs +0 -26
  123. package/src/main/__tests__/bilkoHost-integration.test.cjs +0 -118
  124. package/src/main/__tests__/bilkoHostCore.test.cjs +0 -72
  125. package/src/main/__tests__/broadcastCoalescer.test.cjs +0 -122
  126. package/src/main/__tests__/chat-cancel-terminal.test.cjs +0 -120
  127. package/src/main/__tests__/chat-dead-channels.test.cjs +0 -63
  128. package/src/main/__tests__/chat-exit-close-race.test.cjs +0 -146
  129. package/src/main/__tests__/chat-mcp-consent-notice.test.cjs +0 -139
  130. package/src/main/__tests__/chat-preamble-anchors.test.cjs +0 -100
  131. package/src/main/__tests__/chat-queue.test.cjs +0 -97
  132. package/src/main/__tests__/chat-stop-signal.test.cjs +0 -89
  133. package/src/main/__tests__/chatRunner-epic-worktree-execcwd.test.cjs +0 -125
  134. package/src/main/__tests__/chatRunner-session-flag-retry.test.cjs +0 -252
  135. package/src/main/__tests__/classifyPromptTicket.test.cjs +0 -101
  136. package/src/main/__tests__/classifyTranscriptLine.test.cjs +0 -201
  137. package/src/main/__tests__/computeDepHistorySatisfaction.test.cjs +0 -66
  138. package/src/main/__tests__/config-readText-bounded.test.cjs +0 -84
  139. package/src/main/__tests__/configWriteBoundaryOwners.test.cjs +0 -59
  140. package/src/main/__tests__/crossProjectFeedback.test.cjs +0 -334
  141. package/src/main/__tests__/crossProjectFeedbackRoutes.test.cjs +0 -161
  142. package/src/main/__tests__/dep-orphan-archive-health.test.cjs +0 -77
  143. package/src/main/__tests__/develop-skill-failure-modes.test.cjs +0 -70
  144. package/src/main/__tests__/docEdit.test.cjs +0 -244
  145. package/src/main/__tests__/dod-batchkey.test.cjs +0 -183
  146. package/src/main/__tests__/dod-drain-hook.test.cjs +0 -302
  147. package/src/main/__tests__/dod-report.test.cjs +0 -304
  148. package/src/main/__tests__/dod-reverify.test.cjs +0 -285
  149. package/src/main/__tests__/epicContextDigest.test.cjs +0 -174
  150. package/src/main/__tests__/epicMint.test.cjs +0 -332
  151. package/src/main/__tests__/epicMintTelemetryTap.test.cjs +0 -64
  152. package/src/main/__tests__/epicStatusMirror.test.cjs +0 -110
  153. package/src/main/__tests__/epicValidationHook.test.cjs +0 -291
  154. package/src/main/__tests__/exchanges.test.cjs +0 -122
  155. package/src/main/__tests__/exchangesPromptId.test.cjs +0 -61
  156. package/src/main/__tests__/extractJson.test.cjs +0 -51
  157. package/src/main/__tests__/files-reject-credentials.test.cjs +0 -40
  158. package/src/main/__tests__/fixtures/1218-fo-01-move-scripts-lib-into-src-main-lib.log +0 -556
  159. package/src/main/__tests__/flatPrdTickSweep.test.cjs +0 -110
  160. package/src/main/__tests__/health-build-freshness.test.cjs +0 -39
  161. package/src/main/__tests__/health-claude-md-budget.test.cjs +0 -57
  162. package/src/main/__tests__/health-credentials.test.cjs +0 -81
  163. package/src/main/__tests__/health-delegation-chain.test.cjs +0 -124
  164. package/src/main/__tests__/health-per-project-stall.test.cjs +0 -84
  165. package/src/main/__tests__/health-prd-migration.test.cjs +0 -37
  166. package/src/main/__tests__/health-queue-dispatch.test.cjs +0 -135
  167. package/src/main/__tests__/health-starve-escalation.test.cjs +0 -94
  168. package/src/main/__tests__/health-tick-liveness.test.cjs +0 -179
  169. package/src/main/__tests__/health-usage-poller.test.cjs +0 -144
  170. package/src/main/__tests__/health-worktree-cap-blocked.test.cjs +0 -65
  171. package/src/main/__tests__/heapSnapshot.test.cjs +0 -121
  172. package/src/main/__tests__/historyAggregatorIntraday.test.cjs +0 -313
  173. package/src/main/__tests__/historyDashboard.test.cjs +0 -163
  174. package/src/main/__tests__/historyRollup.test.cjs +0 -333
  175. package/src/main/__tests__/intradayRefresh.test.cjs +0 -39
  176. package/src/main/__tests__/ipcSchemas-dependsOn.test.cjs +0 -39
  177. package/src/main/__tests__/kg-augment.test.cjs +0 -195
  178. package/src/main/__tests__/loadGateDetailTick.test.cjs +0 -31
  179. package/src/main/__tests__/machineProfile.test.cjs +0 -152
  180. package/src/main/__tests__/mcpStatus.test.cjs +0 -61
  181. package/src/main/__tests__/memoryAggregate.test.cjs +0 -109
  182. package/src/main/__tests__/memoryStale.test.cjs +0 -88
  183. package/src/main/__tests__/needsReviewLedger.test.cjs +0 -162
  184. package/src/main/__tests__/openExternalApp-spawn-error.test.cjs +0 -25
  185. package/src/main/__tests__/opsErrorLog.test.cjs +0 -109
  186. package/src/main/__tests__/opsErrorLogTelemetryTap.test.cjs +0 -173
  187. package/src/main/__tests__/personaMerge.test.cjs +0 -169
  188. package/src/main/__tests__/planValidator.test.cjs +0 -125
  189. package/src/main/__tests__/pollLoop-dispatch-on-failure.test.cjs +0 -176
  190. package/src/main/__tests__/prd-group-allocator.test.cjs +0 -119
  191. package/src/main/__tests__/prdAdminRouteParity.test.cjs +0 -70
  192. package/src/main/__tests__/prdAdminRoutes.test.cjs +0 -718
  193. package/src/main/__tests__/prdAgentType.test.cjs +0 -103
  194. package/src/main/__tests__/prdAuthoringSeed.test.cjs +0 -39
  195. package/src/main/__tests__/prdCreate.test.cjs +0 -979
  196. package/src/main/__tests__/prdCreateAdoption.test.cjs +0 -205
  197. package/src/main/__tests__/prdCreateDisposition.test.cjs +0 -201
  198. package/src/main/__tests__/prdCreatePlanId.test.cjs +0 -132
  199. package/src/main/__tests__/prdFrontmatterAgentType.test.cjs +0 -117
  200. package/src/main/__tests__/prdFrontmatterDependsOn.test.cjs +0 -136
  201. package/src/main/__tests__/prdFrontmatterDisposition.test.cjs +0 -125
  202. package/src/main/__tests__/prdFrontmatterQuietMachine.test.cjs +0 -108
  203. package/src/main/__tests__/prdLocations.test.cjs +0 -195
  204. package/src/main/__tests__/prdLocationsArchived.test.cjs +0 -201
  205. package/src/main/__tests__/prdMigration.test.cjs +0 -349
  206. package/src/main/__tests__/prdMigrationLegacyAdopt.test.cjs +0 -91
  207. package/src/main/__tests__/prdParserHighWater.test.cjs +0 -74
  208. package/src/main/__tests__/prdParserSourcePromptId.test.cjs +0 -65
  209. package/src/main/__tests__/prdSetDisposition.test.cjs +0 -222
  210. package/src/main/__tests__/prdSizing.test.cjs +0 -106
  211. package/src/main/__tests__/prdSourcePromptIdBackfill.test.cjs +0 -118
  212. package/src/main/__tests__/prdUpdateDependsOn.test.cjs +0 -160
  213. package/src/main/__tests__/proc-role-env.test.cjs +0 -125
  214. package/src/main/__tests__/procname-claude-spawn-sites.test.cjs +0 -304
  215. package/src/main/__tests__/procname-sm-processes.test.cjs +0 -127
  216. package/src/main/__tests__/projectHomeAdminRoutes.test.cjs +0 -177
  217. package/src/main/__tests__/projectPages.test.cjs +0 -137
  218. package/src/main/__tests__/promptSessionEvents.test.cjs +0 -234
  219. package/src/main/__tests__/promptSessionSchema.test.cjs +0 -101
  220. package/src/main/__tests__/promptSessionTranscript.test.cjs +0 -0
  221. package/src/main/__tests__/promptSessionsCreateEpicHandler.test.cjs +0 -159
  222. package/src/main/__tests__/pty-epic-worktree-spawn-cwd.test.cjs +0 -282
  223. package/src/main/__tests__/pty-session-open-telemetry.test.cjs +0 -96
  224. package/src/main/__tests__/pty-write-result.test.cjs +0 -46
  225. package/src/main/__tests__/queue-health-verdict.test.cjs +0 -170
  226. package/src/main/__tests__/queue-starvation-dispatch-driver.test.cjs +0 -286
  227. package/src/main/__tests__/queue-starvation-per-project.test.cjs +0 -147
  228. package/src/main/__tests__/queueHistory.test.cjs +0 -355
  229. package/src/main/__tests__/queueOps-interactive-ac-lint.test.cjs +0 -65
  230. package/src/main/__tests__/queueOpsArchiveDestination.test.cjs +0 -65
  231. package/src/main/__tests__/queueOpsAutoArchive.test.cjs +0 -211
  232. package/src/main/__tests__/rateLimitPollerStreak.test.cjs +0 -128
  233. package/src/main/__tests__/rcaReport.test.cjs +0 -266
  234. package/src/main/__tests__/reconcileFlatPrdSweep.test.cjs +0 -119
  235. package/src/main/__tests__/reconcileTiming.test.cjs +0 -135
  236. package/src/main/__tests__/runLogRetention.test.cjs +0 -489
  237. package/src/main/__tests__/runVerify-atomic-verdicts.test.cjs +0 -26
  238. package/src/main/__tests__/runVerify-blocked-by-foreign-wip.test.cjs +0 -58
  239. package/src/main/__tests__/runVerify-landed-commit-outranks.test.cjs +0 -191
  240. package/src/main/__tests__/runVerify-policy-denial.test.cjs +0 -89
  241. package/src/main/__tests__/runVerify-transcript-commit-evidence.test.cjs +0 -225
  242. package/src/main/__tests__/runVerify.test.cjs +0 -1784
  243. package/src/main/__tests__/scheduleJobSchema.test.cjs +0 -127
  244. package/src/main/__tests__/scheduleJobStatusDrift.test.cjs +0 -65
  245. package/src/main/__tests__/scheduleJobTransitions.test.cjs +0 -277
  246. package/src/main/__tests__/scheduleJobTransitionsGrep.test.cjs +0 -59
  247. package/src/main/__tests__/scheduleJobTransitionsTelemetryTap.test.cjs +0 -72
  248. package/src/main/__tests__/scheduler-admin-routes.test.cjs +0 -199
  249. package/src/main/__tests__/scheduler-adopted-run-supervision.test.cjs +0 -143
  250. package/src/main/__tests__/scheduler-already-satisfied-on-main.test.cjs +0 -105
  251. package/src/main/__tests__/scheduler-archive-completed-prd.test.cjs +0 -102
  252. package/src/main/__tests__/scheduler-archived-twin-guard.test.cjs +0 -155
  253. package/src/main/__tests__/scheduler-autofix-outcome.test.cjs +0 -188
  254. package/src/main/__tests__/scheduler-autofix-select.test.cjs +0 -439
  255. package/src/main/__tests__/scheduler-autopromote.test.cjs +0 -51
  256. package/src/main/__tests__/scheduler-bash-timeout-env.test.cjs +0 -101
  257. package/src/main/__tests__/scheduler-blocked-by-foreign-wip.test.cjs +0 -107
  258. package/src/main/__tests__/scheduler-boot-orphans.test.cjs +0 -153
  259. package/src/main/__tests__/scheduler-broadcast-reconcile.test.cjs +0 -121
  260. package/src/main/__tests__/scheduler-clear-queue-history.test.cjs +0 -134
  261. package/src/main/__tests__/scheduler-commit-guard-noop.test.cjs +0 -244
  262. package/src/main/__tests__/scheduler-committed-in-window.test.cjs +0 -182
  263. package/src/main/__tests__/scheduler-cross-project-batch.test.cjs +0 -43
  264. package/src/main/__tests__/scheduler-default-eligible-heal.test.cjs +0 -168
  265. package/src/main/__tests__/scheduler-dispatch-loop.test.cjs +0 -58
  266. package/src/main/__tests__/scheduler-effective-concurrency.test.cjs +0 -81
  267. package/src/main/__tests__/scheduler-epic-digest.test.cjs +0 -227
  268. package/src/main/__tests__/scheduler-failed-autoreset.test.cjs +0 -121
  269. package/src/main/__tests__/scheduler-finalize-dispatch-guards.test.cjs +0 -229
  270. package/src/main/__tests__/scheduler-find-prd-dir.test.cjs +0 -75
  271. package/src/main/__tests__/scheduler-fix-plan-path.test.cjs +0 -119
  272. package/src/main/__tests__/scheduler-force-tick-outcome.test.cjs +0 -46
  273. package/src/main/__tests__/scheduler-foreign-wip-manifest.test.cjs +0 -78
  274. package/src/main/__tests__/scheduler-gate-shadow.test.cjs +0 -119
  275. package/src/main/__tests__/scheduler-guard-verdict-autoresolve.test.cjs +0 -390
  276. package/src/main/__tests__/scheduler-heal-refusal.test.cjs +0 -61
  277. package/src/main/__tests__/scheduler-heartbeat-payload.test.cjs +0 -80
  278. package/src/main/__tests__/scheduler-inplace-salvage.test.cjs +0 -323
  279. package/src/main/__tests__/scheduler-integration-failure-stamp.test.cjs +0 -41
  280. package/src/main/__tests__/scheduler-investigation-clean-skip.test.cjs +0 -63
  281. package/src/main/__tests__/scheduler-investigation-prompt.test.cjs +0 -123
  282. package/src/main/__tests__/scheduler-job-budget.test.cjs +0 -172
  283. package/src/main/__tests__/scheduler-job-overrun.test.cjs +0 -175
  284. package/src/main/__tests__/scheduler-launch-failure.test.cjs +0 -199
  285. package/src/main/__tests__/scheduler-leftover-fields.test.cjs +0 -52
  286. package/src/main/__tests__/scheduler-leftover-quarantine.test.cjs +0 -199
  287. package/src/main/__tests__/scheduler-looks-done.test.cjs +0 -537
  288. package/src/main/__tests__/scheduler-manual-pause.test.cjs +0 -118
  289. package/src/main/__tests__/scheduler-mechanical-recovery.test.cjs +0 -245
  290. package/src/main/__tests__/scheduler-meta-code-sha.test.cjs +0 -46
  291. package/src/main/__tests__/scheduler-mutate-reentrancy.test.cjs +0 -117
  292. package/src/main/__tests__/scheduler-needs-review-autoresolve.test.cjs +0 -197
  293. package/src/main/__tests__/scheduler-never-stop.test.cjs +0 -157
  294. package/src/main/__tests__/scheduler-no-dead-end-status.test.cjs +0 -152
  295. package/src/main/__tests__/scheduler-no-orphan-run-dir.test.cjs +0 -81
  296. package/src/main/__tests__/scheduler-notify-originating-tab-transcript.test.cjs +0 -87
  297. package/src/main/__tests__/scheduler-notify-originating-tab.test.cjs +0 -343
  298. package/src/main/__tests__/scheduler-periodic-reverify-guard.test.cjs +0 -217
  299. package/src/main/__tests__/scheduler-porcelain-rename.test.cjs +0 -164
  300. package/src/main/__tests__/scheduler-prd-missing-skip.test.cjs +0 -161
  301. package/src/main/__tests__/scheduler-prd-persona-spawn.test.cjs +0 -178
  302. package/src/main/__tests__/scheduler-quarantine-autoresolve.test.cjs +0 -165
  303. package/src/main/__tests__/scheduler-quiet-machine-lease.test.cjs +0 -257
  304. package/src/main/__tests__/scheduler-rate-limit-cooldown-freshness.test.cjs +0 -123
  305. package/src/main/__tests__/scheduler-rate-limit-pause.test.cjs +0 -152
  306. package/src/main/__tests__/scheduler-rate-limit-spin-guard.test.cjs +0 -156
  307. package/src/main/__tests__/scheduler-reap-dead-running-jobs.test.cjs +0 -754
  308. package/src/main/__tests__/scheduler-reaper-helpers-basics.test.cjs +0 -87
  309. package/src/main/__tests__/scheduler-reconcile-cwd-preserve.test.cjs +0 -100
  310. package/src/main/__tests__/scheduler-reconcile-history-backfill.test.cjs +0 -105
  311. package/src/main/__tests__/scheduler-reconcile-invalid-repair.test.cjs +0 -203
  312. package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +0 -247
  313. package/src/main/__tests__/scheduler-reset-job-fields-guard.test.cjs +0 -77
  314. package/src/main/__tests__/scheduler-resume-recovery.test.cjs +0 -254
  315. package/src/main/__tests__/scheduler-shard-quarantine.test.cjs +0 -115
  316. package/src/main/__tests__/scheduler-shared-tree-guard.test.cjs +0 -380
  317. package/src/main/__tests__/scheduler-sigterm-commit.test.cjs +0 -43
  318. package/src/main/__tests__/scheduler-stall-per-project.test.cjs +0 -126
  319. package/src/main/__tests__/scheduler-starve-escalation.test.cjs +0 -154
  320. package/src/main/__tests__/scheduler-stranded-autofix-park.test.cjs +0 -252
  321. package/src/main/__tests__/scheduler-stranded-investigation.test.cjs +0 -185
  322. package/src/main/__tests__/scheduler-stuck-failed-escalation.test.cjs +0 -136
  323. package/src/main/__tests__/scheduler-supervisor-record.test.cjs +0 -81
  324. package/src/main/__tests__/scheduler-tick-cancel-token.test.cjs +0 -54
  325. package/src/main/__tests__/scheduler-tick-wedge.test.cjs +0 -172
  326. package/src/main/__tests__/scheduler-transient-failure.test.cjs +0 -141
  327. package/src/main/__tests__/scheduler-unreadable-queue-guard.test.cjs +0 -62
  328. package/src/main/__tests__/scheduler-utilization-hold.test.cjs +0 -89
  329. package/src/main/__tests__/scheduler-verify-prd-path.test.cjs +0 -109
  330. package/src/main/__tests__/scheduler-worktree-cap-defer.test.cjs +0 -234
  331. package/src/main/__tests__/scheduler-worktree-exec-cwd.test.cjs +0 -120
  332. package/src/main/__tests__/scheduler-writeprd-epic-rollback.test.cjs +0 -105
  333. package/src/main/__tests__/schedulerBatchRootBlocker.test.cjs +0 -117
  334. package/src/main/__tests__/schedulerStateSidecarRestore.test.cjs +0 -110
  335. package/src/main/__tests__/seedAgentPersonas.test.cjs +0 -184
  336. package/src/main/__tests__/seedSchedulerMcp.test.cjs +0 -211
  337. package/src/main/__tests__/seedStatus.test.cjs +0 -100
  338. package/src/main/__tests__/seedValidatorPersona.test.cjs +0 -116
  339. package/src/main/__tests__/stop-signal-anchor.test.cjs +0 -75
  340. package/src/main/__tests__/telemetryClient.test.cjs +0 -1055
  341. package/src/main/__tests__/telemetryContract.test.cjs +0 -930
  342. package/src/main/__tests__/telemetrySettings.test.cjs +0 -210
  343. package/src/main/__tests__/transcripts-batch-flush.test.cjs +0 -249
  344. package/src/main/__tests__/transcripts-doFlush-array.test.cjs +0 -124
  345. package/src/main/__tests__/transcripts-paged-reads.test.cjs +0 -241
  346. package/src/main/__tests__/transcripts-worktree-epic-path.test.cjs +0 -154
  347. package/src/main/__tests__/transcriptsUsageFor.test.cjs +0 -206
  348. package/src/main/__tests__/uniquePrdNumbers.test.cjs +0 -153
  349. package/src/main/__tests__/usageSingleFlight.test.cjs +0 -169
  350. package/src/main/__tests__/validationSentinels.test.cjs +0 -84
  351. package/src/main/__tests__/workTypeLibrary.test.cjs +0 -89
  352. package/src/main/bilkoHost.cjs +0 -314
  353. package/src/main/bilkoHostCore.cjs +0 -89
  354. package/src/main/lib/__tests__/active-sessions.test.cjs +0 -251
  355. package/src/main/lib/__tests__/activeIndexRebuild.test.cjs +0 -179
  356. package/src/main/lib/__tests__/agentPersonaSchema.test.cjs +0 -67
  357. package/src/main/lib/__tests__/auditLog.test.cjs +0 -38
  358. package/src/main/lib/__tests__/bootSelfHeal.test.cjs +0 -107
  359. package/src/main/lib/__tests__/branchSweep.test.cjs +0 -164
  360. package/src/main/lib/__tests__/buildIdentity.test.cjs +0 -121
  361. package/src/main/lib/__tests__/buildTarget.test.cjs +0 -52
  362. package/src/main/lib/__tests__/childWithLog.test.cjs +0 -321
  363. package/src/main/lib/__tests__/coldBootPromptSessionsWrite.test.cjs +0 -87
  364. package/src/main/lib/__tests__/crashTelemetry.test.cjs +0 -103
  365. package/src/main/lib/__tests__/credentials-futile-refresh.test.cjs +0 -115
  366. package/src/main/lib/__tests__/cwdClassify.test.cjs +0 -111
  367. package/src/main/lib/__tests__/definitionOfDoneSequence.test.cjs +0 -95
  368. package/src/main/lib/__tests__/delegationReadiness.test.cjs +0 -1175
  369. package/src/main/lib/__tests__/dispatchLoop.test.cjs +0 -63
  370. package/src/main/lib/__tests__/effectiveModelInfo.test.cjs +0 -244
  371. package/src/main/lib/__tests__/ephemeralCwd.test.cjs +0 -91
  372. package/src/main/lib/__tests__/epicDelegationStats.test.cjs +0 -137
  373. package/src/main/lib/__tests__/epicSpawnCwd.test.cjs +0 -283
  374. package/src/main/lib/__tests__/epicSpawnPlan.test.cjs +0 -196
  375. package/src/main/lib/__tests__/epicTranscriptPath.test.cjs +0 -163
  376. package/src/main/lib/__tests__/epicWorktreeBoot.test.cjs +0 -136
  377. package/src/main/lib/__tests__/epicWorktreeMerge.test.cjs +0 -130
  378. package/src/main/lib/__tests__/epicWorktreeMint.test.cjs +0 -117
  379. package/src/main/lib/__tests__/epicWorktreeProjectConfig.test.cjs +0 -137
  380. package/src/main/lib/__tests__/fixChainDepth.test.cjs +0 -40
  381. package/src/main/lib/__tests__/fixtures/204-mercury-steam-horse.log.txt +0 -13
  382. package/src/main/lib/__tests__/fixtures/scheduler-machine.json.corrupt-1789147548 +0 -34
  383. package/src/main/lib/__tests__/gateFixtures.json +0 -20
  384. package/src/main/lib/__tests__/gitCacheBound.test.cjs +0 -69
  385. package/src/main/lib/__tests__/gitWorktree.test.cjs +0 -1478
  386. package/src/main/lib/__tests__/gitWorktreeSalvage.test.cjs +0 -107
  387. package/src/main/lib/__tests__/gitWorktreeSalvageDelta.test.cjs +0 -153
  388. package/src/main/lib/__tests__/guardShims.test.cjs +0 -158
  389. package/src/main/lib/__tests__/importReferences.spec.cjs +0 -56
  390. package/src/main/lib/__tests__/instanceLock.test.cjs +0 -173
  391. package/src/main/lib/__tests__/jobSupervisorRecord.test.cjs +0 -78
  392. package/src/main/lib/__tests__/jobWorktree.test.cjs +0 -199
  393. package/src/main/lib/__tests__/jobWorktreeBootLive.test.cjs +0 -82
  394. package/src/main/lib/__tests__/landedSinceRun.test.cjs +0 -133
  395. package/src/main/lib/__tests__/launchFailure.test.cjs +0 -220
  396. package/src/main/lib/__tests__/loadGate.test.cjs +0 -303
  397. package/src/main/lib/__tests__/localAdminHttp.test.cjs +0 -214
  398. package/src/main/lib/__tests__/loopDelay.test.cjs +0 -68
  399. package/src/main/lib/__tests__/mcpToolCatalog.test.cjs +0 -107
  400. package/src/main/lib/__tests__/modelCatalog.test.cjs +0 -202
  401. package/src/main/lib/__tests__/opsOwnership.test.cjs +0 -113
  402. package/src/main/lib/__tests__/opsRootAbsoluteCwd.test.cjs +0 -328
  403. package/src/main/lib/__tests__/opsRootNestedWrite.test.cjs +0 -51
  404. package/src/main/lib/__tests__/opsRootResolve.test.cjs +0 -149
  405. package/src/main/lib/__tests__/prdDeclaredPaths.test.cjs +0 -82
  406. package/src/main/lib/__tests__/prdDisposition.test.cjs +0 -224
  407. package/src/main/lib/__tests__/procIdentity.test.cjs +0 -119
  408. package/src/main/lib/__tests__/procName.test.cjs +0 -92
  409. package/src/main/lib/__tests__/projectBriefCore.test.cjs +0 -216
  410. package/src/main/lib/__tests__/projectRootResolve.test.cjs +0 -148
  411. package/src/main/lib/__tests__/queueHealth.test.cjs +0 -58
  412. package/src/main/lib/__tests__/queueStoreAtomicWrite.test.cjs +0 -88
  413. package/src/main/lib/__tests__/queueStoreMachineStateRecovery.test.cjs +0 -190
  414. package/src/main/lib/__tests__/quietMachineLease.test.cjs +0 -39
  415. package/src/main/lib/__tests__/rateLimitWindow.test.cjs +0 -88
  416. package/src/main/lib/__tests__/reaperHelpers.test.cjs +0 -577
  417. package/src/main/lib/__tests__/schedulerBatchDepends.test.cjs +0 -312
  418. package/src/main/lib/__tests__/schedulerBatchFairness.test.cjs +0 -213
  419. package/src/main/lib/__tests__/schedulerBatchLaunchHold.test.cjs +0 -125
  420. package/src/main/lib/__tests__/schedulerBatchProjectCap.test.cjs +0 -127
  421. package/src/main/lib/__tests__/schedulerBatchQuietMachine.test.cjs +0 -109
  422. package/src/main/lib/__tests__/schedulerMcpServerHeadlessRefusal.test.cjs +0 -71
  423. package/src/main/lib/__tests__/schedulerMcpServerHelp.test.cjs +0 -216
  424. package/src/main/lib/__tests__/schedulerMcpServerProjectHome.test.cjs +0 -183
  425. package/src/main/lib/__tests__/schedulerPaths.test.cjs +0 -226
  426. package/src/main/lib/__tests__/schedulerPathsWorktree.test.cjs +0 -133
  427. package/src/main/lib/__tests__/schedulerRuntimeState.test.cjs +0 -56
  428. package/src/main/lib/__tests__/sessionSlots.test.cjs +0 -144
  429. package/src/main/lib/__tests__/telemetryBacklog.test.cjs +0 -626
  430. package/src/main/lib/__tests__/telemetryBoot.test.cjs +0 -134
  431. package/src/main/lib/__tests__/telemetryConsent.test.cjs +0 -136
  432. package/src/main/lib/__tests__/telemetryCounters.test.cjs +0 -57
  433. package/src/main/lib/__tests__/telemetryCountersMetadataColumn.test.cjs +0 -98
  434. package/src/main/lib/__tests__/terminalRunOutcome.test.cjs +0 -200
  435. package/src/main/lib/__tests__/toolUseClassify.test.cjs +0 -53
  436. package/src/main/lib/__tests__/updateCheck.test.cjs +0 -63
  437. package/src/main/lib/__tests__/upgradeDrain.test.cjs +0 -130
  438. package/src/main/lib/__tests__/usageCircuit.test.cjs +0 -354
  439. package/src/main/lib/__tests__/watchdog-helpers.test.cjs +0 -441
  440. package/src/main/lib/__tests__/watchdog-relaunch.test.cjs +0 -266
  441. package/src/main/lib/kgExchangePairing.cjs +0 -75
@@ -30,6 +30,7 @@ const path = require('node:path');
30
30
  const { identity, isDifferentProcess } = require('./procIdentity.cjs');
31
31
  const { instanceLockPath } = require('./schedulerPaths.cjs');
32
32
  const { appendAuditEvent } = require('./auditLog.cjs');
33
+ const { pidAlive: pidAliveCore } = require('./pidAlive.cjs');
33
34
 
34
35
  // Env override is for unit tests only (isolates the lock from the real
35
36
  // ~/.claude of the machine running the suite).
@@ -38,15 +39,11 @@ function lockPath() {
38
39
  || instanceLockPath();
39
40
  }
40
41
 
42
+ // Thin alias over pidAlive.cjs's shared pidAlive() — kept as its own named
43
+ // export (rather than inlining the require at every call site) so existing
44
+ // imports of `pidAlive` from this module keep working unchanged.
41
45
  function pidAlive(pid) {
42
- if (!Number.isInteger(pid) || pid <= 0) return false;
43
- try {
44
- process.kill(pid, 0);
45
- return true;
46
- } catch (e) {
47
- // EPERM = alive but not ours; ESRCH = dead.
48
- return e && e.code === 'EPERM';
49
- }
46
+ return pidAliveCore(pid);
50
47
  }
51
48
 
52
49
  function readLock() {
@@ -40,6 +40,7 @@
40
40
  const fs = require('node:fs');
41
41
  const path = require('node:path');
42
42
  const { readTail } = require('./fileTail.cjs');
43
+ const atomicFs = require('./atomicFs.cjs');
43
44
 
44
45
  const LAUNCH_FAILURE_KINDS = Object.freeze({
45
46
  /** HTTP 400 naming a thinking/effort/config parameter the model rejects — the issue-#11 signature. */
@@ -329,9 +330,7 @@ function writeOutcomeSidecar(runDir, slug, outcome) {
329
330
  if (!runDir || !slug) return null;
330
331
  const p = path.join(runDir, `${slug}.outcome.json`);
331
332
  try {
332
- const tmp = `${p}.tmp`;
333
- fs.writeFileSync(tmp, JSON.stringify({ slug, writtenAt: new Date().toISOString(), ...outcome }, null, 2));
334
- fs.renameSync(tmp, p);
333
+ atomicFs.writeJsonAtomicSync(p, { slug, writtenAt: new Date().toISOString(), ...outcome }, { newline: false });
335
334
  return p;
336
335
  } catch {
337
336
  return null;
@@ -0,0 +1,480 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * macroLibrary.cjs — the global, machine-local Macro library.
5
+ *
6
+ * A Macro is a one-click sidebar "HOT KEYS" button that starts a new session
7
+ * with a preset Agent + Tag + Initial Prompt (e.g. label "Build the Project",
8
+ * agent `builder`, tag `build`, prompt "Build and publish this project").
9
+ * Each macro lists which projects show it.
10
+ *
11
+ * Store: `~/.claude/session-manager/macros.json`, `{ version: 1, macros: Macro[] }`.
12
+ * The path is fixed; every exported function accepts an optional
13
+ * `{ filePath }` ONLY so tests can inject a temp file — IPC handlers never
14
+ * forward renderer input as a path.
15
+ *
16
+ * Reads are tolerant: invalid entries are dropped individually (one
17
+ * console.warn per read). A missing file triggers the one-time migration. An
18
+ * UNPARSEABLE file is never treated as missing: it is renamed to
19
+ * `macros.json.corrupt-<timestamp>` (kept for recovery), a warning is logged,
20
+ * and a fresh empty store is written WITHOUT re-running migration.
21
+ * Writes go through writeJsonAtomic and are serialized by an in-module
22
+ * promise chain so concurrent saves never clobber each other.
23
+ *
24
+ * One-time migration: when macros.json does not exist, listMacros seeds it
25
+ * from the retired Agent Library persona frontmatter (`action:`,
26
+ * `actionLabel:`, `projects:`). On success the file is written (even with
27
+ * `macros: []`) so migration never reruns; if listing personas throws, nothing
28
+ * is written and the next call retries.
29
+ *
30
+ * `projects` entries are absolute project cwds or the literal '*' (every
31
+ * project). setMacroProject cannot narrow a '*' macro: it returns
32
+ * `{ ok: false, error: 'macro is shown in every project' }`.
33
+ *
34
+ * Plain Node, no Electron imports.
35
+ */
36
+
37
+ const fsp = require('node:fs/promises');
38
+ const path = require('node:path');
39
+ const crypto = require('node:crypto');
40
+ const { z } = require('zod');
41
+ const { writeJsonAtomic } = require('./atomicFs.cjs');
42
+ const { EpicTagSchema } = require('./promptSessionSchema.cjs');
43
+ const { WORK_TYPES } = require('./workTypeLibrary.cjs');
44
+ const { PERSONA_NAME_RE } = require('./personaMerge.cjs');
45
+ const { schedulerHome } = require('./schedulerPaths.cjs');
46
+ const { BUILTIN_MACROS } = require('./builtinMacros.cjs');
47
+
48
+ const ALL_PROJECTS = '*';
49
+ const STORE_VERSION = 1;
50
+
51
+ const MacroIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/, 'invalid macro id');
52
+ const MacroLabelSchema = z.string().trim().min(1).max(60);
53
+ const MacroAgentNameSchema = z.string().regex(PERSONA_NAME_RE, 'agent name must be lowercase, hyphenated (e.g. "my-agent")');
54
+ const MacroPromptSchema = z.string().trim().min(1).max(8000);
55
+ const AbsolutePathSchema = z.string().max(1024).refine(
56
+ (v) => !v.includes('\0') && path.isAbsolute(v),
57
+ 'must be an absolute path',
58
+ );
59
+ const MacroProjectEntrySchema = z.union([z.literal(ALL_PROJECTS), AbsolutePathSchema]);
60
+ const MacroProjectsSchema = z.array(MacroProjectEntrySchema).max(200);
61
+ const MacroSurfaceSchema = z.enum(['sessions', 'project-home']);
62
+
63
+ const MacroSchema = z.object({
64
+ id: MacroIdSchema,
65
+ label: MacroLabelSchema,
66
+ agentName: MacroAgentNameSchema,
67
+ tag: EpicTagSchema,
68
+ prompt: MacroPromptSchema,
69
+ projects: MacroProjectsSchema,
70
+ surface: MacroSurfaceSchema.default('sessions'),
71
+ builtin: z.boolean().optional(),
72
+ builtinVersion: z.number().int().optional(),
73
+ createdAt: z.string().min(1).max(64),
74
+ updatedAt: z.string().min(1).max(64),
75
+ });
76
+
77
+ const MacroSaveSchema = z.object({
78
+ id: MacroIdSchema.optional(),
79
+ label: MacroLabelSchema,
80
+ agentName: MacroAgentNameSchema,
81
+ tag: EpicTagSchema,
82
+ prompt: MacroPromptSchema,
83
+ // Omitted (not merely `[]`) means "leave projects unchanged" on update, so a
84
+ // label/prompt-only edit of a macro (builtin or otherwise) can't silently
85
+ // wipe its visibility back to no projects. `undefined` on create means [].
86
+ projects: MacroProjectsSchema.optional(),
87
+ surface: MacroSurfaceSchema.optional(),
88
+ });
89
+
90
+ const MacroDeleteSchema = z.object({ id: MacroIdSchema });
91
+
92
+ const MacroSetProjectSchema = z.object({
93
+ id: MacroIdSchema,
94
+ cwd: AbsolutePathSchema,
95
+ enabled: z.boolean(),
96
+ });
97
+
98
+ function defaultFilePath() {
99
+ return path.join(schedulerHome(), 'macros.json');
100
+ }
101
+
102
+ function resolvePath(opts) {
103
+ return (opts && opts.filePath) || defaultFilePath();
104
+ }
105
+
106
+ /**
107
+ * Canonical cwd form. MUST match the renderer's `normalizeCwd`
108
+ * (src/renderer/lib/knownProjectAggregate.ts): trim, collapse repeated `/`,
109
+ * strip trailing `/` (root stays `/`). '*' passes through.
110
+ */
111
+ function normalizeCwd(cwd) {
112
+ if (typeof cwd !== 'string' || cwd === ALL_PROJECTS) return cwd;
113
+ const collapsed = cwd.trim().replace(/\/{2,}/g, '/');
114
+ if (collapsed === '/') return '/';
115
+ return collapsed.replace(/\/+$/, '');
116
+ }
117
+
118
+ function normalizeProjects(projects) {
119
+ const out = [];
120
+ for (const p of projects || []) {
121
+ const n = normalizeCwd(p);
122
+ if (!out.includes(n)) out.push(n);
123
+ }
124
+ return out;
125
+ }
126
+
127
+ function slugify(label) {
128
+ const s = String(label).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48).replace(/-+$/g, '');
129
+ return s || 'macro';
130
+ }
131
+
132
+ function newId(label, taken) {
133
+ for (let i = 0; i < 20; i++) {
134
+ const id = `${slugify(label)}-${crypto.randomBytes(3).toString('hex')}`;
135
+ if (!taken.has(id)) return id;
136
+ }
137
+ return `${slugify(label)}-${crypto.randomUUID()}`.slice(0, 64);
138
+ }
139
+
140
+ // --- serialized writes ------------------------------------------------------
141
+
142
+ let writeChain = Promise.resolve();
143
+ function serialize(fn) {
144
+ const run = writeChain.then(fn, fn);
145
+ writeChain = run.then(() => undefined, () => undefined);
146
+ return run;
147
+ }
148
+
149
+ // --- read -------------------------------------------------------------------
150
+
151
+ /**
152
+ * Pure read. Returns `{ state: 'missing' | 'corrupt' | 'unreadable' | 'ok', macros }`.
153
+ * 'corrupt' = file exists but is not a JSON object; 'unreadable' = any other fs error.
154
+ */
155
+ async function readStore(filePath) {
156
+ let text;
157
+ try {
158
+ text = await fsp.readFile(filePath, 'utf8');
159
+ } catch (err) {
160
+ if (err && err.code === 'ENOENT') return { state: 'missing', macros: [] };
161
+ console.warn(`[macroLibrary] cannot read ${filePath}:`, err && err.message);
162
+ return { state: 'unreadable', macros: [] };
163
+ }
164
+ let raw;
165
+ try {
166
+ raw = JSON.parse(text);
167
+ } catch {
168
+ return { state: 'corrupt', macros: [] };
169
+ }
170
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { state: 'corrupt', macros: [] };
171
+ const list = Array.isArray(raw.macros) ? raw.macros : [];
172
+ const macros = [];
173
+ let dropped = 0;
174
+ const seen = new Set();
175
+ for (const entry of list) {
176
+ const normalized = entry && typeof entry === 'object' && Array.isArray(entry.projects)
177
+ ? { ...entry, projects: normalizeProjects(entry.projects) }
178
+ : entry;
179
+ const r = MacroSchema.safeParse(normalized);
180
+ if (r.success && !seen.has(r.data.id)) {
181
+ seen.add(r.data.id);
182
+ macros.push(r.data);
183
+ } else {
184
+ dropped++;
185
+ }
186
+ }
187
+ if (dropped > 0 || !Array.isArray(raw.macros)) {
188
+ console.warn(`[macroLibrary] dropped ${dropped} invalid macro entr${dropped === 1 ? 'y' : 'ies'} from ${filePath}`);
189
+ }
190
+ return { state: 'ok', macros };
191
+ }
192
+
193
+ async function writeStore(filePath, macros) {
194
+ await writeJsonAtomic(filePath, { version: STORE_VERSION, macros });
195
+ }
196
+
197
+ function resolveBuiltins(opts) {
198
+ return opts && Object.prototype.hasOwnProperty.call(opts, 'builtins') ? opts.builtins : BUILTIN_MACROS;
199
+ }
200
+
201
+ /**
202
+ * Pure. Seeds any `builtins` entry missing from `macros` (as `builtin: true`),
203
+ * and upgrades a stored built-in that is behind the shipped `builtinVersion`
204
+ * AND was never user-edited (`updatedAt === createdAt`). A user-edited
205
+ * built-in is left untouched. Returns `{ macros, changed }`.
206
+ */
207
+ function ensureBuiltins(macros, builtins) {
208
+ if (!builtins || builtins.length === 0) return { macros, changed: false };
209
+ let changed = false;
210
+ const next = macros.slice();
211
+ const now = new Date().toISOString();
212
+ for (const b of builtins) {
213
+ const idx = next.findIndex((m) => m.id === b.id);
214
+ if (idx === -1) {
215
+ next.push({
216
+ id: b.id,
217
+ label: b.label,
218
+ agentName: b.agentName,
219
+ tag: b.tag,
220
+ prompt: b.prompt,
221
+ projects: b.projects.slice(),
222
+ surface: b.surface,
223
+ builtin: true,
224
+ builtinVersion: b.builtinVersion,
225
+ createdAt: now,
226
+ updatedAt: now,
227
+ });
228
+ changed = true;
229
+ continue;
230
+ }
231
+ const stored = next[idx];
232
+ const storedVersion = stored.builtinVersion || 0;
233
+ const neverEdited = stored.updatedAt === stored.createdAt;
234
+ if (storedVersion < b.builtinVersion && neverEdited) {
235
+ next[idx] = {
236
+ ...stored,
237
+ label: b.label,
238
+ agentName: b.agentName,
239
+ tag: b.tag,
240
+ prompt: b.prompt,
241
+ surface: b.surface,
242
+ builtinVersion: b.builtinVersion,
243
+ updatedAt: stored.createdAt,
244
+ };
245
+ changed = true;
246
+ }
247
+ }
248
+ return { macros: next, changed };
249
+ }
250
+
251
+ /** Apply builtin seeding/upgrades, writing only when something changed. */
252
+ async function applyBuiltins(filePath, macros, opts) {
253
+ const { macros: next, changed } = ensureBuiltins(macros, resolveBuiltins(opts));
254
+ if (!changed) return { macros, failed: false };
255
+ try {
256
+ await writeStore(filePath, next);
257
+ } catch (err) {
258
+ console.warn('[macroLibrary] could not persist built-in macro seeding:', err && err.message);
259
+ return { macros, failed: false };
260
+ }
261
+ return { macros: next, failed: false };
262
+ }
263
+
264
+ // --- migration --------------------------------------------------------------
265
+
266
+ function isValidProject(p) {
267
+ return p === ALL_PROJECTS || AbsolutePathSchema.safeParse(p).success;
268
+ }
269
+
270
+ function personasToMacros(personas, now) {
271
+ const macros = [];
272
+ const taken = new Set();
273
+ for (const p of personas || []) {
274
+ if (!p || typeof p.name !== 'string') continue;
275
+ const declared = Array.isArray(p.projects) ? p.projects.filter((x) => typeof x === 'string' && x.trim()) : [];
276
+ const normalized = normalizeProjects(declared);
277
+ const projects = normalized.filter(isValidProject);
278
+ const skipped = normalized.filter((x) => !isValidProject(x));
279
+ if (skipped.length > 0) {
280
+ console.warn(`[macroLibrary] persona "${p.name}": skipped non-absolute project entries: ${skipped.join(', ')}`);
281
+ }
282
+ const prompt = (p.action && String(p.action).trim()) || (p.description && String(p.description).trim()) || '';
283
+ if (projects.length === 0 || !prompt) continue;
284
+ // First persona tag in canonical TAG_LIBRARY order (WORK_TYPES mirrors it), else 'discussion'.
285
+ const personaTags = Array.isArray(p.tags) ? p.tags : [];
286
+ const tag = WORK_TYPES.find((t) => personaTags.includes(t)) || 'discussion';
287
+ const label = String(p.actionLabel || p.name).trim().slice(0, 60);
288
+ const candidate = {
289
+ id: newId(label, taken),
290
+ label,
291
+ agentName: p.name,
292
+ tag,
293
+ prompt: prompt.slice(0, 8000),
294
+ projects,
295
+ createdAt: now,
296
+ updatedAt: now,
297
+ };
298
+ const r = MacroSchema.safeParse(candidate);
299
+ if (!r.success) continue;
300
+ taken.add(r.data.id);
301
+ macros.push(r.data);
302
+ }
303
+ return macros;
304
+ }
305
+
306
+ /** Returns the migrated macros, or `null` on failure (caller must NOT write). */
307
+ async function migrateFromPersonas(opts) {
308
+ try {
309
+ const listPersonas = (opts && opts.listPersonas) || require('../agentLibrary.cjs').listPersonas;
310
+ const personas = await listPersonas();
311
+ return personasToMacros(personas, new Date().toISOString());
312
+ } catch (err) {
313
+ console.warn('[macroLibrary] persona migration failed; will retry on next call:', err && err.message);
314
+ return null;
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Load the store, repairing it as needed. MUST run inside `serialize`.
320
+ * Returns `{ macros, failed }`; `failed` means nothing was persisted and the
321
+ * caller must not write (migration failed / file unreadable / quarantine failed).
322
+ */
323
+ async function loadStore(filePath, opts) {
324
+ const cur = await readStore(filePath);
325
+ if (cur.state === 'ok') return applyBuiltins(filePath, cur.macros, opts);
326
+ if (cur.state === 'unreadable') return { macros: [], failed: true };
327
+ if (cur.state === 'corrupt') {
328
+ const quarantine = `${filePath}.corrupt-${Date.now()}`;
329
+ try {
330
+ await fsp.rename(filePath, quarantine);
331
+ } catch (err) {
332
+ console.warn(`[macroLibrary] ${filePath} is unparseable and could not be preserved:`, err && err.message);
333
+ return { macros: [], failed: true };
334
+ }
335
+ console.warn(`[macroLibrary] ${filePath} is unparseable; preserved as ${quarantine}, starting with an empty library`);
336
+ try {
337
+ await writeStore(filePath, []);
338
+ } catch (err) {
339
+ console.warn('[macroLibrary] could not write fresh macros.json:', err && err.message);
340
+ return { macros: [], failed: true };
341
+ }
342
+ return applyBuiltins(filePath, [], opts);
343
+ }
344
+ // missing: migrate once
345
+ const seeded = await migrateFromPersonas(opts);
346
+ if (seeded === null) return { macros: [], failed: true };
347
+ try {
348
+ await writeStore(filePath, seeded);
349
+ } catch (err) {
350
+ console.warn('[macroLibrary] could not write migrated macros.json:', err && err.message);
351
+ return { macros: seeded, failed: true };
352
+ }
353
+ return applyBuiltins(filePath, seeded, opts);
354
+ }
355
+
356
+ // --- public API -------------------------------------------------------------
357
+
358
+ /** @returns {Promise<Macro[]>} */
359
+ async function listMacros(opts = {}) {
360
+ const filePath = resolvePath(opts);
361
+ const first = await readStore(filePath);
362
+ if (first.state === 'ok') {
363
+ const { changed } = ensureBuiltins(first.macros, resolveBuiltins(opts));
364
+ if (!changed) return first.macros;
365
+ }
366
+ // Missing/corrupt/needs-seeding: repair inside the write chain so racing callers don't double-seed.
367
+ return serialize(async () => (await loadStore(filePath, opts)).macros);
368
+ }
369
+
370
+ /** Load for a write; refuse to write over a store that could not be loaded. */
371
+ async function loadForWrite(filePath, opts) {
372
+ const { macros, failed } = await loadStore(filePath, opts);
373
+ if (failed) throw new Error('macro library unavailable (migration or read failed); try again');
374
+ return macros;
375
+ }
376
+
377
+ /**
378
+ * Create (no id) or update (id) a macro. Returns the saved Macro.
379
+ * Throws on invalid input or unknown id.
380
+ */
381
+ async function saveMacro(input, opts = {}) {
382
+ const parsed = MacroSaveSchema.parse(input);
383
+ const filePath = resolvePath(opts);
384
+ return serialize(async () => {
385
+ const macros = await loadForWrite(filePath, opts);
386
+ const now = new Date().toISOString();
387
+ let saved;
388
+ if (parsed.id) {
389
+ const idx = macros.findIndex((m) => m.id === parsed.id);
390
+ if (idx === -1) throw new Error(`macro not found: ${parsed.id}`);
391
+ const projects = parsed.projects !== undefined ? normalizeProjects(parsed.projects) : macros[idx].projects;
392
+ saved = {
393
+ ...macros[idx],
394
+ label: parsed.label,
395
+ agentName: parsed.agentName,
396
+ tag: parsed.tag,
397
+ prompt: parsed.prompt,
398
+ projects,
399
+ surface: parsed.surface ?? macros[idx].surface,
400
+ updatedAt: now,
401
+ };
402
+ macros[idx] = saved;
403
+ } else {
404
+ const projects = parsed.projects !== undefined ? normalizeProjects(parsed.projects) : [];
405
+ saved = {
406
+ id: newId(parsed.label, new Set(macros.map((m) => m.id))),
407
+ label: parsed.label,
408
+ agentName: parsed.agentName,
409
+ tag: parsed.tag,
410
+ prompt: parsed.prompt,
411
+ projects,
412
+ surface: parsed.surface ?? 'sessions',
413
+ createdAt: now,
414
+ updatedAt: now,
415
+ };
416
+ macros.push(saved);
417
+ }
418
+ await writeStore(filePath, macros);
419
+ return saved;
420
+ });
421
+ }
422
+
423
+ /** Idempotent: deleting an unknown id is still `{ ok: true }`. */
424
+ async function deleteMacro(input, opts = {}) {
425
+ const { id } = MacroDeleteSchema.parse(input);
426
+ const filePath = resolvePath(opts);
427
+ return serialize(async () => {
428
+ const macros = await loadForWrite(filePath, opts);
429
+ const target = macros.find((m) => m.id === id);
430
+ if (target && target.builtin) throw new Error('built-in macros cannot be deleted');
431
+ const next = macros.filter((m) => m.id !== id);
432
+ if (next.length !== macros.length) await writeStore(filePath, next);
433
+ return { ok: true };
434
+ });
435
+ }
436
+
437
+ /**
438
+ * Add/remove one project cwd on a macro. Returns `{ ok: true, macro }` or
439
+ * `{ ok: false, error }`. A macro with '*' is shown everywhere and cannot be
440
+ * narrowed here: `{ ok: false, error: 'macro is shown in every project' }`
441
+ * (enabled=true on a '*' macro is a no-op success).
442
+ */
443
+ async function setMacroProject(input, opts = {}) {
444
+ const { id, cwd, enabled } = MacroSetProjectSchema.parse(input);
445
+ const filePath = resolvePath(opts);
446
+ const target = normalizeCwd(cwd);
447
+ return serialize(async () => {
448
+ const macros = await loadForWrite(filePath, opts);
449
+ const idx = macros.findIndex((m) => m.id === id);
450
+ if (idx === -1) return { ok: false, error: `macro not found: ${id}` };
451
+ const macro = macros[idx];
452
+ if (macro.projects.includes(ALL_PROJECTS)) {
453
+ if (enabled) return { ok: true, macro };
454
+ return { ok: false, error: 'macro is shown in every project' };
455
+ }
456
+ if (macro.builtin && !enabled) return { ok: false, error: 'built-in macro visibility cannot be narrowed' };
457
+ const has = macro.projects.includes(target);
458
+ if (enabled === has) return { ok: true, macro };
459
+ const projects = enabled ? [...macro.projects, target] : macro.projects.filter((p) => p !== target);
460
+ if (projects.length > 200) return { ok: false, error: 'too many projects' };
461
+ const updated = { ...macro, projects, updatedAt: new Date().toISOString() };
462
+ macros[idx] = updated;
463
+ await writeStore(filePath, macros);
464
+ return { ok: true, macro: updated };
465
+ });
466
+ }
467
+
468
+ module.exports = {
469
+ ALL_PROJECTS,
470
+ MacroSchema,
471
+ MacroSaveSchema,
472
+ MacroDeleteSchema,
473
+ MacroSetProjectSchema,
474
+ listMacros,
475
+ saveMacro,
476
+ deleteMacro,
477
+ setMacroProject,
478
+ defaultFilePath,
479
+ ensureBuiltins,
480
+ };
@@ -45,7 +45,7 @@ const MCP_TOOL_CATALOG = [
45
45
  whenToUse: 'Use after diagnosing why a job is stuck (e.g. via scheduler_get_prd/scheduler_list_jobs) and deciding it should re-run from pending.',
46
46
  whenNotToUse: 'Do not use as a first move on a "needs_review" job without reading it first — reset just clears status, it does not answer the question the job raised.',
47
47
  exampleArgs: { slug: 'add-mcp-tool-catalog', force: false },
48
- notes: 'Refuses a job whose status is already "completed" unless force:true is passed — resetting a completed job re-executes already-shipped work.',
48
+ notes: 'force:true is needed to reset a job whose status is already "completed" or "skipped" — resetting a completed job re-executes already-shipped work; resetting a skipped job overrides the scheduler\'s (or a human\'s) choice not to run it.',
49
49
  },
50
50
  {
51
51
  name: 'scheduler_pause',
@@ -101,7 +101,14 @@ const MCP_TOOL_CATALOG = [
101
101
  + 'files this PRD produces that are NOT meant to be committed (git-excluded), they are stat-checked on '
102
102
  + 'disk by the verifier, and declaring them is the ONLY way an artifact-only PRD can pass the finish '
103
103
  + 'protocol without a commit. Each requires the other (the write is refused if only one is given), and '
104
- + 'no path may contain "..".',
104
+ + 'no path may contain "..". '
105
+ + '`gate` and `files` are REQUIRED on every call — the tool refuses a call missing either. `gate` lists '
106
+ + '1-10 commands that prove this PRD is done (each starting with `timeout <seconds>`, joined with `&&`, '
107
+ + 'no shell metacharacters), or exactly `["none"]` for a PRD with no runnable check; the scheduler '
108
+ + 're-runs these commands and reads them back from the rendered `# Gate` section verbatim, so a stray '
109
+ + '```gate fence anywhere else in the PRD text is rejected. `files` lists the 1-50 repo-relative files '
110
+ + 'or folders this PRD may change; PRDs that can run at the same time must not share a file — chain '
111
+ + 'them with `dependsOn` instead.',
105
112
  whenToUse: 'Use whenever new work should be queued into an already-approved Epic — this is the /develop path.',
106
113
  whenNotToUse: 'TWO DISTINCT FAILURE MODES if this tool is not usable — do not conflate them: '
107
114
  + '(a) this tool call is PRESENT in your tool list but ERRORS as app-not-running / admin '
@@ -120,10 +127,12 @@ const MCP_TOOL_CATALOG = [
120
127
  exampleArgs: {
121
128
  title: 'Add unit tests for the retry backoff helper',
122
129
  cwd: '/home/bilko/Projects/session-manager',
123
- estimateMinutes: 30,
130
+ estimateMinutes: 10,
124
131
  goal: 'Cover retryWithBackoff.cjs edge cases (zero retries, max-delay clamp) that currently have no test.',
125
- acceptanceCriteria: ['New test file exercises zero-retry and max-delay-clamp cases', 'timeout 300 npm run typecheck passes', 'timeout 600 npm run test:unit passes'],
132
+ acceptanceCriteria: ['New test file exercises zero-retry and max-delay-clamp cases', 'Typecheck passes', 'Unit tests pass'],
126
133
  implementationNotes: 'See src/main/lib/retryWithBackoff.cjs and its existing __tests__ sibling for the pattern to extend.',
134
+ gate: ['timeout 300 npm run typecheck', 'timeout 600 npm run test:unit'],
135
+ files: ['src/main/lib/retryWithBackoff.cjs', 'src/main/lib/__tests__/retryWithBackoff.test.cjs'],
127
136
  sourcePromptId: 'epic-id-of-an-already-approved-session',
128
137
  },
129
138
  notes: 'See /develop.',
@@ -155,17 +164,17 @@ const MCP_TOOL_CATALOG = [
155
164
  {
156
165
  name: 'scheduler_update_prd',
157
166
  group: 'scheduler',
158
- purpose: "THE ONLY SUPPORTED WAY to edit a NOT-yet-running PRD's frontmatter and/or body via the session-manager "
159
- + 'app\'s admin API. Refuses once a queue row exists for the slug and its status is anything but "pending" '
160
- + '(running/completed/failed/needs_review) — editing the spec under a live or already-finished executor is refused, '
161
- + 'not silently applied. Only recognized frontmatter keys (title, cwd, estimateMinutes, parallelGroup, '
167
+ purpose: "THE ONLY SUPPORTED WAY to edit a PRD's frontmatter and/or body. Works while the job is pending, "
168
+ + 'quarantined, needs_review, failed or skipped, or has no queue row yet. Refuses a running job (wait, or '
169
+ + 'cancel it first) and a completed one (queue a new PRD). '
170
+ + 'Only recognized frontmatter keys (title, cwd, estimateMinutes, parallelGroup, '
162
171
  + 'sourcePromptId, sourceTabId, tag, dependsOn) may be patched; unrecognized keys round-trip unchanged. '
163
172
  + 'Patching dependsOn to a non-empty array replaces it wholesale (validated against existing PRD slugs, '
164
173
  + 'same resolver scheduler_create_prd uses); patching it to an explicit empty array CLEARS the dependency — '
165
174
  + 'the safe way to fix a wrong dependsOn without archiving (which marks the PRD completed and wrongly frees its dependents).',
166
- whenToUse: 'Use to correct a PRD scope/estimate/tag before it starts running — e.g. before resetting a needs_review job whose spec needs to change.',
167
- whenNotToUse: 'Do not use once the job is running or terminal (completed/failed/needs_review) without first resetting it back to pending — the route refuses the edit.',
168
- exampleArgs: { slug: 'add-mcp-tool-catalog', frontmatter: { estimateMinutes: 45 } },
175
+ whenToUse: 'Use to fix a PRD\'s spec before it runs, or to fix a parked (needs_review or failed) or skipped PRD before you reset it with scheduler_reset_job.',
176
+ whenNotToUse: 'Do not use on a running or completed job. Do not reset first and edit second: the reset job can start before the edit lands.',
177
+ exampleArgs: { slug: 'add-mcp-tool-catalog', frontmatter: { estimateMinutes: 8 } },
169
178
  notes: null,
170
179
  },
171
180
  {
@@ -197,7 +206,7 @@ const MCP_TOOL_CATALOG = [
197
206
  + "parallelGroup changes, its NN- filename prefix) via the session-manager app's admin API.",
198
207
  whenToUse: 'Use to correct an estimate or renumber a PRD file after it was created.',
199
208
  whenNotToUse: 'Do not use parallelGroup as an ordering/dependency barrier — it is only a unique-per-PRD display hint; use dependsOn on scheduler_create_prd/scheduler_update_prd for real ordering.',
200
- exampleArgs: { items: [{ slug: 'add-mcp-tool-catalog', estimateMinutes: 30 }] },
209
+ exampleArgs: { items: [{ slug: 'add-mcp-tool-catalog', estimateMinutes: 10 }] },
201
210
  notes: null,
202
211
  },
203
212
  {
@@ -261,6 +270,29 @@ const MCP_TOOL_CATALOG = [
261
270
  exampleArgs: { cwd: '/home/bilko/Projects/session-manager', html: '<!DOCTYPE html><html><body><h1>Example</h1></body></html>' },
262
271
  notes: "cwd is optional — defaults to the calling session's own project root (SM_PROJECT_ROOT or process.cwd()) when omitted.",
263
272
  },
273
+ {
274
+ name: 'project_demo_video_write',
275
+ group: 'project-home',
276
+ purpose: "Write this project's 30-second demo video — ONE self-contained HTML/JS document — to "
277
+ + "session-manager-operations/project-pages/demo-video/index.html via the session-manager app's admin API. "
278
+ + 'The only write path for the demo video.',
279
+ whenToUse: 'Use when asked to generate or refresh the demo video. Compose the whole document yourself '
280
+ + '(inline <style>/<script>, data: URIs for assets, CSS/JS-driven animation) from what is really true about '
281
+ + 'the project, declare its length with <meta name="sm-demo-duration" content="N"> (5-30 seconds), then '
282
+ + 'pass the full document as `html`.',
283
+ whenNotToUse: 'Never fabricate content — every claim must trace to something concrete in the project. The '
284
+ + 'document must be self-contained and non-network-capable: the call is rejected for empty input, more than '
285
+ + '2MB, any <script src>, <link href="http…">, @import, or url(http…) (no remote references); any '
286
+ + 'fetch/XMLHttpRequest/WebSocket/EventSource/sendBeacon/dynamic import/importScripts/<iframe>/<object>/'
287
+ + '<embed>/window.open/http(s)-pointing src or href (no network-capable APIs); or a missing/out-of-range '
288
+ + 'sm-demo-duration meta tag.',
289
+ exampleArgs: {
290
+ cwd: '/home/bilko/Projects/session-manager',
291
+ html: '<!DOCTYPE html><html><head><meta name="sm-demo-duration" content="30"></head><body><h1>Example</h1></body></html>',
292
+ },
293
+ notes: "cwd is optional — defaults to the calling session's own project root (SM_PROJECT_ROOT or process.cwd()) when omitted. "
294
+ + 'The document is CSP-stamped after it is written, so the viewer sandbox is the real network fence — these checks are defence in depth.',
295
+ },
264
296
  {
265
297
  name: 'session_manager_help',
266
298
  group: 'help',
@@ -295,11 +327,11 @@ const MCP_RECIPES = [
295
327
  id: 'unstick-needs-review-job',
296
328
  title: 'Unstick a job stuck in needs_review',
297
329
  steps: [
298
- 'Call scheduler_list_prds with status:"needs_review" (or scheduler_list_jobs) to find the stuck slug.',
299
- 'Call scheduler_get_prd with that slug to read its full frontmatter + body and understand the question it raised.',
300
- 'If the PRD spec needs to change, call scheduler_update_prd with the slug and a frontmatter/body patch — this is only accepted while the job is not yet running or terminal.',
301
- 'Call scheduler_reset_job with { slug } to clear the needs_review status back to pending — force is only required if the job had already reached "completed".',
302
- 'The next scheduler reconcile pass re-queues the job; confirm with scheduler_list_jobs or scheduler_list_prds.',
330
+ 'Call scheduler_list_prds with status:"needs_review" (or scheduler_list_jobs) to find the slug.',
331
+ 'Call scheduler_get_prd with that slug to read the PRD and why it parked.',
332
+ 'If the spec is wrong, call scheduler_update_prd with the slug and a frontmatter/body patch. It works while the job is pending, quarantined, needs_review, failed or skipped.',
333
+ 'Then call scheduler_reset_job with { slug } to set the job back to pending. Pass force:true when the job is skipped. Always edit first, then reset: a reset job can start on the next tick.',
334
+ 'The next scheduler pass runs it again. Confirm with scheduler_list_jobs or scheduler_list_prds.',
303
335
  ],
304
336
  },
305
337
  {
@@ -60,7 +60,7 @@ function classifyLadderRung({ source, reason } = {}) {
60
60
  if (s === 'spawnInvestigation:start' || s === 'spawnJob:auto-promote' || s === 'reverifyNeedsReview:auto-promote') {
61
61
  return 'auto-fix';
62
62
  }
63
- if (s === 'reverifyNeedsReview:heal' || s === 'needsReviewAutoResolve') return 'reverify';
63
+ if (s === 'reverifyNeedsReview:heal' || s === 'needsReviewAutoResolve' || s === 'gateAuthoritative') return 'reverify';
64
64
  // No transitionJob call site resolves needs_review with a 'quarantine'
65
65
  // source today (performLeftoverQuarantine cleans up leftover paths without
66
66
  // itself changing job.status — the row stays needs_review until a later