claude-code-session-manager 0.98.0 → 0.100.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 (431) 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-DCEgMTjH.js → DataModel-HdR0AxFq.js} +1 -1
  5. package/dist/assets/{History-Bfdoywlh.js → History-Dr4Jr_5z.js} +2 -2
  6. package/dist/assets/{Hooks-CKDJjTJV.js → Hooks-NhrvH3JP.js} +3 -3
  7. package/dist/assets/{Library-7akfgy67.js → Library-Dv_EtIMr.js} +1 -1
  8. package/dist/assets/{MarkdownEditor-DDesiqet.js → MarkdownEditor-DTKDWV_n.js} +1 -1
  9. package/dist/assets/{McpServers-D4lZtXof.js → McpServers-M034G9B3.js} +2 -2
  10. package/dist/assets/{Memory-CeI8G1w5.js → Memory-DzF1B4gx.js} +6 -6
  11. package/dist/assets/{Permissions-BGleLja4.js → Permissions-DrgbSGWl.js} +3 -3
  12. package/dist/assets/{Plugins-P4eCXy_S.js → Plugins-Bd3ef35w.js} +2 -2
  13. package/dist/assets/{ProvenanceBadge-BFczzI1B.js → ProvenanceBadge-DcBHT1Iy.js} +1 -1
  14. package/dist/assets/{SaveBar-l9jnEMES.js → SaveBar-rimJem-Y.js} +1 -1
  15. package/dist/assets/Scheduler-DjgFJl2w.js +16 -0
  16. package/dist/assets/{ScopeSwitcher-CjJi8ST5.js → ScopeSwitcher-CnAzTBrl.js} +1 -1
  17. package/dist/assets/Settings-Dc1F_sSg.js +3 -0
  18. package/dist/assets/{SkillReferenceGraph-CjbO01Sg.js → SkillReferenceGraph-B9aZDecM.js} +1 -1
  19. package/dist/assets/{Skills-BxZ9_fCR.js → Skills-DRXd18gu.js} +2 -2
  20. package/dist/assets/{SystemPrompt-D8vfFb8b.js → SystemPrompt-ahy5-Fwe.js} +1 -1
  21. package/dist/assets/{TagLibrary-2vzUo7YL.js → TagLibrary-C_tToDeL.js} +1 -1
  22. package/dist/assets/{TiptapBody-B8ZfbK90.js → TiptapBody-DvdefS6K.js} +1 -1
  23. package/dist/assets/{Toggle-BbW4nGGf.js → Toggle-6Jl5Njc6.js} +1 -1
  24. package/dist/assets/{index-CKH5Uxik.css → index-Bta-hwud.css} +1 -1
  25. package/dist/assets/{index-Cd98Q1lD.js → index-vx8O73l8.js} +497 -502
  26. package/dist/assets/{settingsSchema-IhUfucCF.js → settingsSchema-D6iRguNV.js} +1 -1
  27. package/dist/index.html +2 -2
  28. package/package.json +25 -29
  29. package/plugins/CLAUDE.md +6 -6
  30. package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +21 -19
  31. package/plugins/session-manager-dev/skills/builder/SKILL.md +3 -3
  32. package/plugins/session-manager-dev/skills/develop/SKILL.md +254 -510
  33. package/plugins/session-manager-dev/skills/develop/standards.md +17 -22
  34. package/scripts/README.md +3 -11
  35. package/scripts/audit-ops-hygiene.cjs +3 -3
  36. package/scripts/hooks/lib/guard-prd-writes-policy.cjs +1 -1
  37. package/scripts/hooks/lib/guard-self-schedule-policy.cjs +1 -1
  38. package/scripts/mint-epic.cjs +2 -3
  39. package/scripts/scheduler-mcp-server.cjs +36 -7
  40. package/src/main/agentLibrary.cjs +22 -2
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/config.cjs +41 -38
  43. package/src/main/docEdit.cjs +4 -1
  44. package/src/main/files.cjs +2 -5
  45. package/src/main/health.cjs +1 -1
  46. package/src/main/index.cjs +23 -10
  47. package/src/main/ipcSchemas.cjs +28 -35
  48. package/src/main/lib/agentPersonaSchema.cjs +13 -2
  49. package/src/main/lib/atomicFs.cjs +116 -0
  50. package/src/main/lib/branchSweep.cjs +13 -12
  51. package/src/main/lib/buildTarget.cjs +3 -3
  52. package/src/main/lib/claudeCliCaps.cjs +129 -0
  53. package/src/main/lib/credentials.cjs +2 -4
  54. package/src/main/lib/crossProjectFeedback.cjs +3 -3
  55. package/src/main/lib/cwdClassify.cjs +15 -3
  56. package/src/main/lib/definitionOfDone.cjs +207 -125
  57. package/src/main/lib/dodDrainHook.cjs +11 -5
  58. package/src/main/lib/epicMint.cjs +2 -4
  59. package/src/main/lib/epicStatusMirror.cjs +8 -10
  60. package/src/main/lib/epicWorktreeProjectConfig.cjs +2 -4
  61. package/src/main/lib/gateAuthority.cjs +96 -0
  62. package/src/main/lib/gitExec.cjs +69 -0
  63. package/src/main/lib/gitWorktree.cjs +656 -92
  64. package/src/main/lib/instanceLock.cjs +5 -8
  65. package/src/main/lib/launchFailure.cjs +2 -3
  66. package/src/main/lib/macroLibrary.cjs +386 -0
  67. package/src/main/lib/mcpToolCatalog.cjs +26 -17
  68. package/src/main/lib/needsReviewLedger.cjs +1 -1
  69. package/src/main/lib/opsErrorLog.cjs +11 -1
  70. package/src/main/lib/opsOwnership.cjs +0 -5
  71. package/src/main/lib/pidAlive.cjs +32 -0
  72. package/src/main/lib/prdCreate.cjs +121 -12
  73. package/src/main/lib/prdDisposition.cjs +2 -2
  74. package/src/main/lib/prdGateFiles.cjs +284 -0
  75. package/src/main/lib/prdLocations.cjs +61 -0
  76. package/src/main/lib/prdMigration.cjs +2 -3
  77. package/src/main/lib/prdSizing.cjs +2 -1
  78. package/src/main/lib/promptSessionSchema.cjs +10 -2
  79. package/src/main/lib/rcaReport.cjs +4 -6
  80. package/src/main/lib/reaperHelpers.cjs +8 -1
  81. package/src/main/lib/reservationExpiry.cjs +6 -1
  82. package/src/main/lib/reviewNotice.cjs +263 -0
  83. package/src/main/lib/runClaudeP.cjs +4 -1
  84. package/src/main/lib/schedulerPaths.cjs +22 -2
  85. package/src/main/lib/sessionSlots.cjs +2 -4
  86. package/src/main/lib/shippedPersonaSeeds.cjs +179 -0
  87. package/src/main/lib/timeoutShim.cjs +123 -0
  88. package/src/main/lib/timeoutShimScript.cjs +275 -0
  89. package/src/main/lib/upgradeDrain.cjs +4 -10
  90. package/src/main/lib/watchdogHelpers.cjs +12 -25
  91. package/src/main/lib/workTypeLibrary.cjs +7 -1
  92. package/src/main/promptSessionEvents.cjs +37 -13
  93. package/src/main/scheduler.cjs +910 -198
  94. package/src/main/seedAgentPersonas.cjs +278 -23
  95. package/src/main/supervisor.cjs +4 -1
  96. package/src/main/templates/PRD_AUTHORING.md +126 -406
  97. package/src/preload/__tests__/preload-surface.test.cjs +68 -0
  98. package/src/preload/api.d.ts +41 -94
  99. package/src/preload/index.cjs +14 -9
  100. package/src/seed/agents/architect.md +1 -0
  101. package/src/seed/agents/dev-lead.md +17 -18
  102. package/src/seed/agents/project-home-builder.md +1 -0
  103. package/src/seed/agents/validator.md +10 -4
  104. package/dist/assets/HostBilko-CDVHE0hT.js +0 -1
  105. package/dist/assets/Scheduler-C_phpeUS.js +0 -16
  106. package/dist/assets/Settings-BIwZ3FGQ.js +0 -3
  107. package/src/main/__tests__/activeIndexMerge.test.cjs +0 -235
  108. package/src/main/__tests__/agentEffortResolve.test.cjs +0 -117
  109. package/src/main/__tests__/agentLibrary.test.cjs +0 -276
  110. package/src/main/__tests__/agentModelResolve.test.cjs +0 -311
  111. package/src/main/__tests__/agentOverlayWrite.test.cjs +0 -95
  112. package/src/main/__tests__/bilkoHost-deriveSlug.test.cjs +0 -26
  113. package/src/main/__tests__/bilkoHost-integration.test.cjs +0 -118
  114. package/src/main/__tests__/bilkoHostCore.test.cjs +0 -72
  115. package/src/main/__tests__/broadcastCoalescer.test.cjs +0 -122
  116. package/src/main/__tests__/chat-cancel-terminal.test.cjs +0 -120
  117. package/src/main/__tests__/chat-dead-channels.test.cjs +0 -63
  118. package/src/main/__tests__/chat-exit-close-race.test.cjs +0 -146
  119. package/src/main/__tests__/chat-mcp-consent-notice.test.cjs +0 -139
  120. package/src/main/__tests__/chat-preamble-anchors.test.cjs +0 -100
  121. package/src/main/__tests__/chat-queue.test.cjs +0 -97
  122. package/src/main/__tests__/chat-stop-signal.test.cjs +0 -89
  123. package/src/main/__tests__/chatRunner-epic-worktree-execcwd.test.cjs +0 -125
  124. package/src/main/__tests__/chatRunner-session-flag-retry.test.cjs +0 -252
  125. package/src/main/__tests__/classifyPromptTicket.test.cjs +0 -101
  126. package/src/main/__tests__/classifyTranscriptLine.test.cjs +0 -201
  127. package/src/main/__tests__/computeDepHistorySatisfaction.test.cjs +0 -66
  128. package/src/main/__tests__/config-readText-bounded.test.cjs +0 -84
  129. package/src/main/__tests__/configWriteBoundaryOwners.test.cjs +0 -59
  130. package/src/main/__tests__/crossProjectFeedback.test.cjs +0 -334
  131. package/src/main/__tests__/crossProjectFeedbackRoutes.test.cjs +0 -161
  132. package/src/main/__tests__/dep-orphan-archive-health.test.cjs +0 -77
  133. package/src/main/__tests__/develop-skill-failure-modes.test.cjs +0 -70
  134. package/src/main/__tests__/docEdit.test.cjs +0 -244
  135. package/src/main/__tests__/dod-batchkey.test.cjs +0 -183
  136. package/src/main/__tests__/dod-drain-hook.test.cjs +0 -302
  137. package/src/main/__tests__/dod-report.test.cjs +0 -304
  138. package/src/main/__tests__/dod-reverify.test.cjs +0 -285
  139. package/src/main/__tests__/epicContextDigest.test.cjs +0 -174
  140. package/src/main/__tests__/epicMint.test.cjs +0 -332
  141. package/src/main/__tests__/epicMintTelemetryTap.test.cjs +0 -64
  142. package/src/main/__tests__/epicStatusMirror.test.cjs +0 -110
  143. package/src/main/__tests__/epicValidationHook.test.cjs +0 -291
  144. package/src/main/__tests__/exchanges.test.cjs +0 -122
  145. package/src/main/__tests__/exchangesPromptId.test.cjs +0 -61
  146. package/src/main/__tests__/extractJson.test.cjs +0 -51
  147. package/src/main/__tests__/files-reject-credentials.test.cjs +0 -40
  148. package/src/main/__tests__/fixtures/1218-fo-01-move-scripts-lib-into-src-main-lib.log +0 -556
  149. package/src/main/__tests__/flatPrdTickSweep.test.cjs +0 -110
  150. package/src/main/__tests__/health-build-freshness.test.cjs +0 -39
  151. package/src/main/__tests__/health-claude-md-budget.test.cjs +0 -57
  152. package/src/main/__tests__/health-credentials.test.cjs +0 -81
  153. package/src/main/__tests__/health-delegation-chain.test.cjs +0 -124
  154. package/src/main/__tests__/health-per-project-stall.test.cjs +0 -84
  155. package/src/main/__tests__/health-prd-migration.test.cjs +0 -37
  156. package/src/main/__tests__/health-queue-dispatch.test.cjs +0 -135
  157. package/src/main/__tests__/health-starve-escalation.test.cjs +0 -94
  158. package/src/main/__tests__/health-tick-liveness.test.cjs +0 -179
  159. package/src/main/__tests__/health-usage-poller.test.cjs +0 -144
  160. package/src/main/__tests__/health-worktree-cap-blocked.test.cjs +0 -65
  161. package/src/main/__tests__/heapSnapshot.test.cjs +0 -121
  162. package/src/main/__tests__/historyAggregatorIntraday.test.cjs +0 -313
  163. package/src/main/__tests__/historyDashboard.test.cjs +0 -163
  164. package/src/main/__tests__/historyRollup.test.cjs +0 -333
  165. package/src/main/__tests__/intradayRefresh.test.cjs +0 -39
  166. package/src/main/__tests__/ipcSchemas-dependsOn.test.cjs +0 -39
  167. package/src/main/__tests__/kg-augment.test.cjs +0 -195
  168. package/src/main/__tests__/loadGateDetailTick.test.cjs +0 -31
  169. package/src/main/__tests__/machineProfile.test.cjs +0 -152
  170. package/src/main/__tests__/mcpStatus.test.cjs +0 -61
  171. package/src/main/__tests__/memoryAggregate.test.cjs +0 -109
  172. package/src/main/__tests__/memoryStale.test.cjs +0 -88
  173. package/src/main/__tests__/needsReviewLedger.test.cjs +0 -162
  174. package/src/main/__tests__/openExternalApp-spawn-error.test.cjs +0 -25
  175. package/src/main/__tests__/opsErrorLog.test.cjs +0 -109
  176. package/src/main/__tests__/opsErrorLogTelemetryTap.test.cjs +0 -173
  177. package/src/main/__tests__/personaMerge.test.cjs +0 -169
  178. package/src/main/__tests__/planValidator.test.cjs +0 -125
  179. package/src/main/__tests__/pollLoop-dispatch-on-failure.test.cjs +0 -176
  180. package/src/main/__tests__/prd-group-allocator.test.cjs +0 -119
  181. package/src/main/__tests__/prdAdminRouteParity.test.cjs +0 -70
  182. package/src/main/__tests__/prdAdminRoutes.test.cjs +0 -718
  183. package/src/main/__tests__/prdAgentType.test.cjs +0 -103
  184. package/src/main/__tests__/prdAuthoringSeed.test.cjs +0 -39
  185. package/src/main/__tests__/prdCreate.test.cjs +0 -979
  186. package/src/main/__tests__/prdCreateAdoption.test.cjs +0 -205
  187. package/src/main/__tests__/prdCreateDisposition.test.cjs +0 -201
  188. package/src/main/__tests__/prdCreatePlanId.test.cjs +0 -132
  189. package/src/main/__tests__/prdFrontmatterAgentType.test.cjs +0 -117
  190. package/src/main/__tests__/prdFrontmatterDependsOn.test.cjs +0 -136
  191. package/src/main/__tests__/prdFrontmatterDisposition.test.cjs +0 -125
  192. package/src/main/__tests__/prdFrontmatterQuietMachine.test.cjs +0 -108
  193. package/src/main/__tests__/prdLocations.test.cjs +0 -195
  194. package/src/main/__tests__/prdLocationsArchived.test.cjs +0 -201
  195. package/src/main/__tests__/prdMigration.test.cjs +0 -349
  196. package/src/main/__tests__/prdMigrationLegacyAdopt.test.cjs +0 -91
  197. package/src/main/__tests__/prdParserHighWater.test.cjs +0 -74
  198. package/src/main/__tests__/prdParserSourcePromptId.test.cjs +0 -65
  199. package/src/main/__tests__/prdSetDisposition.test.cjs +0 -222
  200. package/src/main/__tests__/prdSizing.test.cjs +0 -106
  201. package/src/main/__tests__/prdSourcePromptIdBackfill.test.cjs +0 -118
  202. package/src/main/__tests__/prdUpdateDependsOn.test.cjs +0 -160
  203. package/src/main/__tests__/proc-role-env.test.cjs +0 -125
  204. package/src/main/__tests__/procname-claude-spawn-sites.test.cjs +0 -304
  205. package/src/main/__tests__/procname-sm-processes.test.cjs +0 -127
  206. package/src/main/__tests__/projectHomeAdminRoutes.test.cjs +0 -177
  207. package/src/main/__tests__/projectPages.test.cjs +0 -137
  208. package/src/main/__tests__/promptSessionEvents.test.cjs +0 -234
  209. package/src/main/__tests__/promptSessionSchema.test.cjs +0 -101
  210. package/src/main/__tests__/promptSessionTranscript.test.cjs +0 -0
  211. package/src/main/__tests__/promptSessionsCreateEpicHandler.test.cjs +0 -159
  212. package/src/main/__tests__/pty-epic-worktree-spawn-cwd.test.cjs +0 -282
  213. package/src/main/__tests__/pty-session-open-telemetry.test.cjs +0 -96
  214. package/src/main/__tests__/pty-write-result.test.cjs +0 -46
  215. package/src/main/__tests__/queue-health-verdict.test.cjs +0 -170
  216. package/src/main/__tests__/queue-starvation-dispatch-driver.test.cjs +0 -286
  217. package/src/main/__tests__/queue-starvation-per-project.test.cjs +0 -147
  218. package/src/main/__tests__/queueHistory.test.cjs +0 -355
  219. package/src/main/__tests__/queueOps-interactive-ac-lint.test.cjs +0 -65
  220. package/src/main/__tests__/queueOpsArchiveDestination.test.cjs +0 -65
  221. package/src/main/__tests__/queueOpsAutoArchive.test.cjs +0 -211
  222. package/src/main/__tests__/rateLimitPollerStreak.test.cjs +0 -128
  223. package/src/main/__tests__/rcaReport.test.cjs +0 -266
  224. package/src/main/__tests__/reconcileFlatPrdSweep.test.cjs +0 -119
  225. package/src/main/__tests__/reconcileTiming.test.cjs +0 -135
  226. package/src/main/__tests__/runLogRetention.test.cjs +0 -489
  227. package/src/main/__tests__/runVerify-atomic-verdicts.test.cjs +0 -26
  228. package/src/main/__tests__/runVerify-blocked-by-foreign-wip.test.cjs +0 -58
  229. package/src/main/__tests__/runVerify-landed-commit-outranks.test.cjs +0 -191
  230. package/src/main/__tests__/runVerify-policy-denial.test.cjs +0 -89
  231. package/src/main/__tests__/runVerify-transcript-commit-evidence.test.cjs +0 -225
  232. package/src/main/__tests__/runVerify.test.cjs +0 -1784
  233. package/src/main/__tests__/scheduleJobSchema.test.cjs +0 -127
  234. package/src/main/__tests__/scheduleJobStatusDrift.test.cjs +0 -65
  235. package/src/main/__tests__/scheduleJobTransitions.test.cjs +0 -277
  236. package/src/main/__tests__/scheduleJobTransitionsGrep.test.cjs +0 -59
  237. package/src/main/__tests__/scheduleJobTransitionsTelemetryTap.test.cjs +0 -72
  238. package/src/main/__tests__/scheduler-admin-routes.test.cjs +0 -199
  239. package/src/main/__tests__/scheduler-adopted-run-supervision.test.cjs +0 -143
  240. package/src/main/__tests__/scheduler-already-satisfied-on-main.test.cjs +0 -105
  241. package/src/main/__tests__/scheduler-archive-completed-prd.test.cjs +0 -102
  242. package/src/main/__tests__/scheduler-archived-twin-guard.test.cjs +0 -155
  243. package/src/main/__tests__/scheduler-autofix-outcome.test.cjs +0 -188
  244. package/src/main/__tests__/scheduler-autofix-select.test.cjs +0 -439
  245. package/src/main/__tests__/scheduler-autopromote.test.cjs +0 -51
  246. package/src/main/__tests__/scheduler-bash-timeout-env.test.cjs +0 -101
  247. package/src/main/__tests__/scheduler-blocked-by-foreign-wip.test.cjs +0 -107
  248. package/src/main/__tests__/scheduler-boot-orphans.test.cjs +0 -153
  249. package/src/main/__tests__/scheduler-broadcast-reconcile.test.cjs +0 -121
  250. package/src/main/__tests__/scheduler-clear-queue-history.test.cjs +0 -134
  251. package/src/main/__tests__/scheduler-commit-guard-noop.test.cjs +0 -244
  252. package/src/main/__tests__/scheduler-committed-in-window.test.cjs +0 -182
  253. package/src/main/__tests__/scheduler-cross-project-batch.test.cjs +0 -43
  254. package/src/main/__tests__/scheduler-default-eligible-heal.test.cjs +0 -168
  255. package/src/main/__tests__/scheduler-dispatch-loop.test.cjs +0 -58
  256. package/src/main/__tests__/scheduler-effective-concurrency.test.cjs +0 -81
  257. package/src/main/__tests__/scheduler-epic-digest.test.cjs +0 -227
  258. package/src/main/__tests__/scheduler-failed-autoreset.test.cjs +0 -121
  259. package/src/main/__tests__/scheduler-finalize-dispatch-guards.test.cjs +0 -229
  260. package/src/main/__tests__/scheduler-find-prd-dir.test.cjs +0 -75
  261. package/src/main/__tests__/scheduler-fix-plan-path.test.cjs +0 -119
  262. package/src/main/__tests__/scheduler-force-tick-outcome.test.cjs +0 -46
  263. package/src/main/__tests__/scheduler-foreign-wip-manifest.test.cjs +0 -78
  264. package/src/main/__tests__/scheduler-gate-shadow.test.cjs +0 -119
  265. package/src/main/__tests__/scheduler-guard-verdict-autoresolve.test.cjs +0 -390
  266. package/src/main/__tests__/scheduler-heal-refusal.test.cjs +0 -61
  267. package/src/main/__tests__/scheduler-heartbeat-payload.test.cjs +0 -80
  268. package/src/main/__tests__/scheduler-inplace-salvage.test.cjs +0 -323
  269. package/src/main/__tests__/scheduler-integration-failure-stamp.test.cjs +0 -41
  270. package/src/main/__tests__/scheduler-investigation-clean-skip.test.cjs +0 -63
  271. package/src/main/__tests__/scheduler-investigation-prompt.test.cjs +0 -123
  272. package/src/main/__tests__/scheduler-job-budget.test.cjs +0 -172
  273. package/src/main/__tests__/scheduler-job-overrun.test.cjs +0 -175
  274. package/src/main/__tests__/scheduler-launch-failure.test.cjs +0 -199
  275. package/src/main/__tests__/scheduler-leftover-fields.test.cjs +0 -52
  276. package/src/main/__tests__/scheduler-leftover-quarantine.test.cjs +0 -199
  277. package/src/main/__tests__/scheduler-looks-done.test.cjs +0 -537
  278. package/src/main/__tests__/scheduler-manual-pause.test.cjs +0 -118
  279. package/src/main/__tests__/scheduler-mechanical-recovery.test.cjs +0 -245
  280. package/src/main/__tests__/scheduler-meta-code-sha.test.cjs +0 -46
  281. package/src/main/__tests__/scheduler-mutate-reentrancy.test.cjs +0 -117
  282. package/src/main/__tests__/scheduler-needs-review-autoresolve.test.cjs +0 -197
  283. package/src/main/__tests__/scheduler-never-stop.test.cjs +0 -157
  284. package/src/main/__tests__/scheduler-no-dead-end-status.test.cjs +0 -152
  285. package/src/main/__tests__/scheduler-no-orphan-run-dir.test.cjs +0 -81
  286. package/src/main/__tests__/scheduler-notify-originating-tab-transcript.test.cjs +0 -87
  287. package/src/main/__tests__/scheduler-notify-originating-tab.test.cjs +0 -343
  288. package/src/main/__tests__/scheduler-periodic-reverify-guard.test.cjs +0 -217
  289. package/src/main/__tests__/scheduler-porcelain-rename.test.cjs +0 -164
  290. package/src/main/__tests__/scheduler-prd-missing-skip.test.cjs +0 -161
  291. package/src/main/__tests__/scheduler-prd-persona-spawn.test.cjs +0 -178
  292. package/src/main/__tests__/scheduler-quarantine-autoresolve.test.cjs +0 -165
  293. package/src/main/__tests__/scheduler-quiet-machine-lease.test.cjs +0 -257
  294. package/src/main/__tests__/scheduler-rate-limit-cooldown-freshness.test.cjs +0 -123
  295. package/src/main/__tests__/scheduler-rate-limit-pause.test.cjs +0 -152
  296. package/src/main/__tests__/scheduler-rate-limit-spin-guard.test.cjs +0 -156
  297. package/src/main/__tests__/scheduler-reap-dead-running-jobs.test.cjs +0 -754
  298. package/src/main/__tests__/scheduler-reaper-helpers-basics.test.cjs +0 -87
  299. package/src/main/__tests__/scheduler-reconcile-cwd-preserve.test.cjs +0 -100
  300. package/src/main/__tests__/scheduler-reconcile-history-backfill.test.cjs +0 -105
  301. package/src/main/__tests__/scheduler-reconcile-invalid-repair.test.cjs +0 -203
  302. package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +0 -247
  303. package/src/main/__tests__/scheduler-reset-job-fields-guard.test.cjs +0 -77
  304. package/src/main/__tests__/scheduler-resume-recovery.test.cjs +0 -254
  305. package/src/main/__tests__/scheduler-shard-quarantine.test.cjs +0 -115
  306. package/src/main/__tests__/scheduler-shared-tree-guard.test.cjs +0 -380
  307. package/src/main/__tests__/scheduler-sigterm-commit.test.cjs +0 -43
  308. package/src/main/__tests__/scheduler-stall-per-project.test.cjs +0 -126
  309. package/src/main/__tests__/scheduler-starve-escalation.test.cjs +0 -154
  310. package/src/main/__tests__/scheduler-stranded-autofix-park.test.cjs +0 -252
  311. package/src/main/__tests__/scheduler-stranded-investigation.test.cjs +0 -185
  312. package/src/main/__tests__/scheduler-stuck-failed-escalation.test.cjs +0 -136
  313. package/src/main/__tests__/scheduler-supervisor-record.test.cjs +0 -81
  314. package/src/main/__tests__/scheduler-tick-cancel-token.test.cjs +0 -54
  315. package/src/main/__tests__/scheduler-tick-wedge.test.cjs +0 -172
  316. package/src/main/__tests__/scheduler-transient-failure.test.cjs +0 -141
  317. package/src/main/__tests__/scheduler-unreadable-queue-guard.test.cjs +0 -62
  318. package/src/main/__tests__/scheduler-utilization-hold.test.cjs +0 -89
  319. package/src/main/__tests__/scheduler-verify-prd-path.test.cjs +0 -109
  320. package/src/main/__tests__/scheduler-worktree-cap-defer.test.cjs +0 -234
  321. package/src/main/__tests__/scheduler-worktree-exec-cwd.test.cjs +0 -120
  322. package/src/main/__tests__/scheduler-writeprd-epic-rollback.test.cjs +0 -105
  323. package/src/main/__tests__/schedulerBatchRootBlocker.test.cjs +0 -117
  324. package/src/main/__tests__/schedulerStateSidecarRestore.test.cjs +0 -110
  325. package/src/main/__tests__/seedAgentPersonas.test.cjs +0 -184
  326. package/src/main/__tests__/seedSchedulerMcp.test.cjs +0 -211
  327. package/src/main/__tests__/seedStatus.test.cjs +0 -100
  328. package/src/main/__tests__/seedValidatorPersona.test.cjs +0 -116
  329. package/src/main/__tests__/stop-signal-anchor.test.cjs +0 -75
  330. package/src/main/__tests__/telemetryClient.test.cjs +0 -1055
  331. package/src/main/__tests__/telemetryContract.test.cjs +0 -930
  332. package/src/main/__tests__/telemetrySettings.test.cjs +0 -210
  333. package/src/main/__tests__/transcripts-batch-flush.test.cjs +0 -249
  334. package/src/main/__tests__/transcripts-doFlush-array.test.cjs +0 -124
  335. package/src/main/__tests__/transcripts-paged-reads.test.cjs +0 -241
  336. package/src/main/__tests__/transcripts-worktree-epic-path.test.cjs +0 -154
  337. package/src/main/__tests__/transcriptsUsageFor.test.cjs +0 -206
  338. package/src/main/__tests__/uniquePrdNumbers.test.cjs +0 -153
  339. package/src/main/__tests__/usageSingleFlight.test.cjs +0 -169
  340. package/src/main/__tests__/validationSentinels.test.cjs +0 -84
  341. package/src/main/__tests__/workTypeLibrary.test.cjs +0 -89
  342. package/src/main/bilkoHost.cjs +0 -314
  343. package/src/main/bilkoHostCore.cjs +0 -89
  344. package/src/main/lib/__tests__/active-sessions.test.cjs +0 -251
  345. package/src/main/lib/__tests__/activeIndexRebuild.test.cjs +0 -179
  346. package/src/main/lib/__tests__/agentPersonaSchema.test.cjs +0 -67
  347. package/src/main/lib/__tests__/auditLog.test.cjs +0 -38
  348. package/src/main/lib/__tests__/bootSelfHeal.test.cjs +0 -107
  349. package/src/main/lib/__tests__/branchSweep.test.cjs +0 -164
  350. package/src/main/lib/__tests__/buildIdentity.test.cjs +0 -121
  351. package/src/main/lib/__tests__/buildTarget.test.cjs +0 -52
  352. package/src/main/lib/__tests__/childWithLog.test.cjs +0 -321
  353. package/src/main/lib/__tests__/coldBootPromptSessionsWrite.test.cjs +0 -87
  354. package/src/main/lib/__tests__/crashTelemetry.test.cjs +0 -103
  355. package/src/main/lib/__tests__/credentials-futile-refresh.test.cjs +0 -115
  356. package/src/main/lib/__tests__/cwdClassify.test.cjs +0 -111
  357. package/src/main/lib/__tests__/definitionOfDoneSequence.test.cjs +0 -95
  358. package/src/main/lib/__tests__/delegationReadiness.test.cjs +0 -1175
  359. package/src/main/lib/__tests__/dispatchLoop.test.cjs +0 -63
  360. package/src/main/lib/__tests__/effectiveModelInfo.test.cjs +0 -244
  361. package/src/main/lib/__tests__/ephemeralCwd.test.cjs +0 -91
  362. package/src/main/lib/__tests__/epicDelegationStats.test.cjs +0 -137
  363. package/src/main/lib/__tests__/epicSpawnCwd.test.cjs +0 -283
  364. package/src/main/lib/__tests__/epicSpawnPlan.test.cjs +0 -196
  365. package/src/main/lib/__tests__/epicTranscriptPath.test.cjs +0 -163
  366. package/src/main/lib/__tests__/epicWorktreeBoot.test.cjs +0 -136
  367. package/src/main/lib/__tests__/epicWorktreeMerge.test.cjs +0 -130
  368. package/src/main/lib/__tests__/epicWorktreeMint.test.cjs +0 -117
  369. package/src/main/lib/__tests__/epicWorktreeProjectConfig.test.cjs +0 -137
  370. package/src/main/lib/__tests__/fixChainDepth.test.cjs +0 -40
  371. package/src/main/lib/__tests__/fixtures/204-mercury-steam-horse.log.txt +0 -13
  372. package/src/main/lib/__tests__/fixtures/scheduler-machine.json.corrupt-1789147548 +0 -34
  373. package/src/main/lib/__tests__/gateFixtures.json +0 -20
  374. package/src/main/lib/__tests__/gitCacheBound.test.cjs +0 -69
  375. package/src/main/lib/__tests__/gitWorktree.test.cjs +0 -1478
  376. package/src/main/lib/__tests__/gitWorktreeSalvage.test.cjs +0 -107
  377. package/src/main/lib/__tests__/gitWorktreeSalvageDelta.test.cjs +0 -153
  378. package/src/main/lib/__tests__/guardShims.test.cjs +0 -158
  379. package/src/main/lib/__tests__/importReferences.spec.cjs +0 -56
  380. package/src/main/lib/__tests__/instanceLock.test.cjs +0 -173
  381. package/src/main/lib/__tests__/jobSupervisorRecord.test.cjs +0 -78
  382. package/src/main/lib/__tests__/jobWorktree.test.cjs +0 -199
  383. package/src/main/lib/__tests__/jobWorktreeBootLive.test.cjs +0 -82
  384. package/src/main/lib/__tests__/landedSinceRun.test.cjs +0 -133
  385. package/src/main/lib/__tests__/launchFailure.test.cjs +0 -220
  386. package/src/main/lib/__tests__/loadGate.test.cjs +0 -303
  387. package/src/main/lib/__tests__/localAdminHttp.test.cjs +0 -214
  388. package/src/main/lib/__tests__/loopDelay.test.cjs +0 -68
  389. package/src/main/lib/__tests__/mcpToolCatalog.test.cjs +0 -107
  390. package/src/main/lib/__tests__/modelCatalog.test.cjs +0 -202
  391. package/src/main/lib/__tests__/opsOwnership.test.cjs +0 -113
  392. package/src/main/lib/__tests__/opsRootAbsoluteCwd.test.cjs +0 -328
  393. package/src/main/lib/__tests__/opsRootNestedWrite.test.cjs +0 -51
  394. package/src/main/lib/__tests__/opsRootResolve.test.cjs +0 -149
  395. package/src/main/lib/__tests__/prdDeclaredPaths.test.cjs +0 -82
  396. package/src/main/lib/__tests__/prdDisposition.test.cjs +0 -224
  397. package/src/main/lib/__tests__/procIdentity.test.cjs +0 -119
  398. package/src/main/lib/__tests__/procName.test.cjs +0 -92
  399. package/src/main/lib/__tests__/projectBriefCore.test.cjs +0 -216
  400. package/src/main/lib/__tests__/projectRootResolve.test.cjs +0 -148
  401. package/src/main/lib/__tests__/queueHealth.test.cjs +0 -58
  402. package/src/main/lib/__tests__/queueStoreAtomicWrite.test.cjs +0 -88
  403. package/src/main/lib/__tests__/queueStoreMachineStateRecovery.test.cjs +0 -190
  404. package/src/main/lib/__tests__/quietMachineLease.test.cjs +0 -39
  405. package/src/main/lib/__tests__/rateLimitWindow.test.cjs +0 -88
  406. package/src/main/lib/__tests__/reaperHelpers.test.cjs +0 -577
  407. package/src/main/lib/__tests__/schedulerBatchDepends.test.cjs +0 -312
  408. package/src/main/lib/__tests__/schedulerBatchFairness.test.cjs +0 -213
  409. package/src/main/lib/__tests__/schedulerBatchLaunchHold.test.cjs +0 -125
  410. package/src/main/lib/__tests__/schedulerBatchProjectCap.test.cjs +0 -127
  411. package/src/main/lib/__tests__/schedulerBatchQuietMachine.test.cjs +0 -109
  412. package/src/main/lib/__tests__/schedulerMcpServerHeadlessRefusal.test.cjs +0 -71
  413. package/src/main/lib/__tests__/schedulerMcpServerHelp.test.cjs +0 -216
  414. package/src/main/lib/__tests__/schedulerMcpServerProjectHome.test.cjs +0 -183
  415. package/src/main/lib/__tests__/schedulerPaths.test.cjs +0 -226
  416. package/src/main/lib/__tests__/schedulerPathsWorktree.test.cjs +0 -133
  417. package/src/main/lib/__tests__/schedulerRuntimeState.test.cjs +0 -56
  418. package/src/main/lib/__tests__/sessionSlots.test.cjs +0 -144
  419. package/src/main/lib/__tests__/telemetryBacklog.test.cjs +0 -626
  420. package/src/main/lib/__tests__/telemetryBoot.test.cjs +0 -134
  421. package/src/main/lib/__tests__/telemetryConsent.test.cjs +0 -136
  422. package/src/main/lib/__tests__/telemetryCounters.test.cjs +0 -57
  423. package/src/main/lib/__tests__/telemetryCountersMetadataColumn.test.cjs +0 -98
  424. package/src/main/lib/__tests__/terminalRunOutcome.test.cjs +0 -200
  425. package/src/main/lib/__tests__/toolUseClassify.test.cjs +0 -53
  426. package/src/main/lib/__tests__/updateCheck.test.cjs +0 -63
  427. package/src/main/lib/__tests__/upgradeDrain.test.cjs +0 -130
  428. package/src/main/lib/__tests__/usageCircuit.test.cjs +0 -354
  429. package/src/main/lib/__tests__/watchdog-helpers.test.cjs +0 -441
  430. package/src/main/lib/__tests__/watchdog-relaunch.test.cjs +0 -266
  431. 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,386 @@
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
+
47
+ const ALL_PROJECTS = '*';
48
+ const STORE_VERSION = 1;
49
+
50
+ const MacroIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/, 'invalid macro id');
51
+ const MacroLabelSchema = z.string().trim().min(1).max(60);
52
+ const MacroAgentNameSchema = z.string().regex(PERSONA_NAME_RE, 'agent name must be lowercase, hyphenated (e.g. "my-agent")');
53
+ const MacroPromptSchema = z.string().trim().min(1).max(8000);
54
+ const AbsolutePathSchema = z.string().max(1024).refine(
55
+ (v) => !v.includes('\0') && path.isAbsolute(v),
56
+ 'must be an absolute path',
57
+ );
58
+ const MacroProjectEntrySchema = z.union([z.literal(ALL_PROJECTS), AbsolutePathSchema]);
59
+ const MacroProjectsSchema = z.array(MacroProjectEntrySchema).max(200);
60
+
61
+ const MacroSchema = z.object({
62
+ id: MacroIdSchema,
63
+ label: MacroLabelSchema,
64
+ agentName: MacroAgentNameSchema,
65
+ tag: EpicTagSchema,
66
+ prompt: MacroPromptSchema,
67
+ projects: MacroProjectsSchema,
68
+ createdAt: z.string().min(1).max(64),
69
+ updatedAt: z.string().min(1).max(64),
70
+ });
71
+
72
+ const MacroSaveSchema = z.object({
73
+ id: MacroIdSchema.optional(),
74
+ label: MacroLabelSchema,
75
+ agentName: MacroAgentNameSchema,
76
+ tag: EpicTagSchema,
77
+ prompt: MacroPromptSchema,
78
+ projects: MacroProjectsSchema.default([]),
79
+ });
80
+
81
+ const MacroDeleteSchema = z.object({ id: MacroIdSchema });
82
+
83
+ const MacroSetProjectSchema = z.object({
84
+ id: MacroIdSchema,
85
+ cwd: AbsolutePathSchema,
86
+ enabled: z.boolean(),
87
+ });
88
+
89
+ function defaultFilePath() {
90
+ return path.join(schedulerHome(), 'macros.json');
91
+ }
92
+
93
+ function resolvePath(opts) {
94
+ return (opts && opts.filePath) || defaultFilePath();
95
+ }
96
+
97
+ /**
98
+ * Canonical cwd form. MUST match the renderer's `normalizeCwd`
99
+ * (src/renderer/lib/knownProjectAggregate.ts): trim, collapse repeated `/`,
100
+ * strip trailing `/` (root stays `/`). '*' passes through.
101
+ */
102
+ function normalizeCwd(cwd) {
103
+ if (typeof cwd !== 'string' || cwd === ALL_PROJECTS) return cwd;
104
+ const collapsed = cwd.trim().replace(/\/{2,}/g, '/');
105
+ if (collapsed === '/') return '/';
106
+ return collapsed.replace(/\/+$/, '');
107
+ }
108
+
109
+ function normalizeProjects(projects) {
110
+ const out = [];
111
+ for (const p of projects || []) {
112
+ const n = normalizeCwd(p);
113
+ if (!out.includes(n)) out.push(n);
114
+ }
115
+ return out;
116
+ }
117
+
118
+ function slugify(label) {
119
+ const s = String(label).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48).replace(/-+$/g, '');
120
+ return s || 'macro';
121
+ }
122
+
123
+ function newId(label, taken) {
124
+ for (let i = 0; i < 20; i++) {
125
+ const id = `${slugify(label)}-${crypto.randomBytes(3).toString('hex')}`;
126
+ if (!taken.has(id)) return id;
127
+ }
128
+ return `${slugify(label)}-${crypto.randomUUID()}`.slice(0, 64);
129
+ }
130
+
131
+ // --- serialized writes ------------------------------------------------------
132
+
133
+ let writeChain = Promise.resolve();
134
+ function serialize(fn) {
135
+ const run = writeChain.then(fn, fn);
136
+ writeChain = run.then(() => undefined, () => undefined);
137
+ return run;
138
+ }
139
+
140
+ // --- read -------------------------------------------------------------------
141
+
142
+ /**
143
+ * Pure read. Returns `{ state: 'missing' | 'corrupt' | 'unreadable' | 'ok', macros }`.
144
+ * 'corrupt' = file exists but is not a JSON object; 'unreadable' = any other fs error.
145
+ */
146
+ async function readStore(filePath) {
147
+ let text;
148
+ try {
149
+ text = await fsp.readFile(filePath, 'utf8');
150
+ } catch (err) {
151
+ if (err && err.code === 'ENOENT') return { state: 'missing', macros: [] };
152
+ console.warn(`[macroLibrary] cannot read ${filePath}:`, err && err.message);
153
+ return { state: 'unreadable', macros: [] };
154
+ }
155
+ let raw;
156
+ try {
157
+ raw = JSON.parse(text);
158
+ } catch {
159
+ return { state: 'corrupt', macros: [] };
160
+ }
161
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { state: 'corrupt', macros: [] };
162
+ const list = Array.isArray(raw.macros) ? raw.macros : [];
163
+ const macros = [];
164
+ let dropped = 0;
165
+ const seen = new Set();
166
+ for (const entry of list) {
167
+ const normalized = entry && typeof entry === 'object' && Array.isArray(entry.projects)
168
+ ? { ...entry, projects: normalizeProjects(entry.projects) }
169
+ : entry;
170
+ const r = MacroSchema.safeParse(normalized);
171
+ if (r.success && !seen.has(r.data.id)) {
172
+ seen.add(r.data.id);
173
+ macros.push(r.data);
174
+ } else {
175
+ dropped++;
176
+ }
177
+ }
178
+ if (dropped > 0 || !Array.isArray(raw.macros)) {
179
+ console.warn(`[macroLibrary] dropped ${dropped} invalid macro entr${dropped === 1 ? 'y' : 'ies'} from ${filePath}`);
180
+ }
181
+ return { state: 'ok', macros };
182
+ }
183
+
184
+ async function writeStore(filePath, macros) {
185
+ await writeJsonAtomic(filePath, { version: STORE_VERSION, macros });
186
+ }
187
+
188
+ // --- migration --------------------------------------------------------------
189
+
190
+ function isValidProject(p) {
191
+ return p === ALL_PROJECTS || AbsolutePathSchema.safeParse(p).success;
192
+ }
193
+
194
+ function personasToMacros(personas, now) {
195
+ const macros = [];
196
+ const taken = new Set();
197
+ for (const p of personas || []) {
198
+ if (!p || typeof p.name !== 'string') continue;
199
+ const declared = Array.isArray(p.projects) ? p.projects.filter((x) => typeof x === 'string' && x.trim()) : [];
200
+ const normalized = normalizeProjects(declared);
201
+ const projects = normalized.filter(isValidProject);
202
+ const skipped = normalized.filter((x) => !isValidProject(x));
203
+ if (skipped.length > 0) {
204
+ console.warn(`[macroLibrary] persona "${p.name}": skipped non-absolute project entries: ${skipped.join(', ')}`);
205
+ }
206
+ const prompt = (p.action && String(p.action).trim()) || (p.description && String(p.description).trim()) || '';
207
+ if (projects.length === 0 || !prompt) continue;
208
+ // First persona tag in canonical TAG_LIBRARY order (WORK_TYPES mirrors it), else 'discussion'.
209
+ const personaTags = Array.isArray(p.tags) ? p.tags : [];
210
+ const tag = WORK_TYPES.find((t) => personaTags.includes(t)) || 'discussion';
211
+ const label = String(p.actionLabel || p.name).trim().slice(0, 60);
212
+ const candidate = {
213
+ id: newId(label, taken),
214
+ label,
215
+ agentName: p.name,
216
+ tag,
217
+ prompt: prompt.slice(0, 8000),
218
+ projects,
219
+ createdAt: now,
220
+ updatedAt: now,
221
+ };
222
+ const r = MacroSchema.safeParse(candidate);
223
+ if (!r.success) continue;
224
+ taken.add(r.data.id);
225
+ macros.push(r.data);
226
+ }
227
+ return macros;
228
+ }
229
+
230
+ /** Returns the migrated macros, or `null` on failure (caller must NOT write). */
231
+ async function migrateFromPersonas(opts) {
232
+ try {
233
+ const listPersonas = (opts && opts.listPersonas) || require('../agentLibrary.cjs').listPersonas;
234
+ const personas = await listPersonas();
235
+ return personasToMacros(personas, new Date().toISOString());
236
+ } catch (err) {
237
+ console.warn('[macroLibrary] persona migration failed; will retry on next call:', err && err.message);
238
+ return null;
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Load the store, repairing it as needed. MUST run inside `serialize`.
244
+ * Returns `{ macros, failed }`; `failed` means nothing was persisted and the
245
+ * caller must not write (migration failed / file unreadable / quarantine failed).
246
+ */
247
+ async function loadStore(filePath, opts) {
248
+ const cur = await readStore(filePath);
249
+ if (cur.state === 'ok') return { macros: cur.macros, failed: false };
250
+ if (cur.state === 'unreadable') return { macros: [], failed: true };
251
+ if (cur.state === 'corrupt') {
252
+ const quarantine = `${filePath}.corrupt-${Date.now()}`;
253
+ try {
254
+ await fsp.rename(filePath, quarantine);
255
+ } catch (err) {
256
+ console.warn(`[macroLibrary] ${filePath} is unparseable and could not be preserved:`, err && err.message);
257
+ return { macros: [], failed: true };
258
+ }
259
+ console.warn(`[macroLibrary] ${filePath} is unparseable; preserved as ${quarantine}, starting with an empty library`);
260
+ try {
261
+ await writeStore(filePath, []);
262
+ } catch (err) {
263
+ console.warn('[macroLibrary] could not write fresh macros.json:', err && err.message);
264
+ return { macros: [], failed: true };
265
+ }
266
+ return { macros: [], failed: false };
267
+ }
268
+ // missing: migrate once
269
+ const seeded = await migrateFromPersonas(opts);
270
+ if (seeded === null) return { macros: [], failed: true };
271
+ try {
272
+ await writeStore(filePath, seeded);
273
+ } catch (err) {
274
+ console.warn('[macroLibrary] could not write migrated macros.json:', err && err.message);
275
+ return { macros: seeded, failed: true };
276
+ }
277
+ return { macros: seeded, failed: false };
278
+ }
279
+
280
+ // --- public API -------------------------------------------------------------
281
+
282
+ /** @returns {Promise<Macro[]>} */
283
+ async function listMacros(opts = {}) {
284
+ const filePath = resolvePath(opts);
285
+ const first = await readStore(filePath);
286
+ if (first.state === 'ok') return first.macros;
287
+ // Missing/corrupt: repair inside the write chain so racing callers don't double-seed.
288
+ return serialize(async () => (await loadStore(filePath, opts)).macros);
289
+ }
290
+
291
+ /** Load for a write; refuse to write over a store that could not be loaded. */
292
+ async function loadForWrite(filePath, opts) {
293
+ const { macros, failed } = await loadStore(filePath, opts);
294
+ if (failed) throw new Error('macro library unavailable (migration or read failed); try again');
295
+ return macros;
296
+ }
297
+
298
+ /**
299
+ * Create (no id) or update (id) a macro. Returns the saved Macro.
300
+ * Throws on invalid input or unknown id.
301
+ */
302
+ async function saveMacro(input, opts = {}) {
303
+ const parsed = MacroSaveSchema.parse(input);
304
+ const filePath = resolvePath(opts);
305
+ return serialize(async () => {
306
+ const macros = await loadForWrite(filePath, opts);
307
+ const now = new Date().toISOString();
308
+ const projects = normalizeProjects(parsed.projects);
309
+ let saved;
310
+ if (parsed.id) {
311
+ const idx = macros.findIndex((m) => m.id === parsed.id);
312
+ if (idx === -1) throw new Error(`macro not found: ${parsed.id}`);
313
+ saved = { ...macros[idx], label: parsed.label, agentName: parsed.agentName, tag: parsed.tag, prompt: parsed.prompt, projects, updatedAt: now };
314
+ macros[idx] = saved;
315
+ } else {
316
+ saved = {
317
+ id: newId(parsed.label, new Set(macros.map((m) => m.id))),
318
+ label: parsed.label,
319
+ agentName: parsed.agentName,
320
+ tag: parsed.tag,
321
+ prompt: parsed.prompt,
322
+ projects,
323
+ createdAt: now,
324
+ updatedAt: now,
325
+ };
326
+ macros.push(saved);
327
+ }
328
+ await writeStore(filePath, macros);
329
+ return saved;
330
+ });
331
+ }
332
+
333
+ /** Idempotent: deleting an unknown id is still `{ ok: true }`. */
334
+ async function deleteMacro(input, opts = {}) {
335
+ const { id } = MacroDeleteSchema.parse(input);
336
+ const filePath = resolvePath(opts);
337
+ return serialize(async () => {
338
+ const macros = await loadForWrite(filePath, opts);
339
+ const next = macros.filter((m) => m.id !== id);
340
+ if (next.length !== macros.length) await writeStore(filePath, next);
341
+ return { ok: true };
342
+ });
343
+ }
344
+
345
+ /**
346
+ * Add/remove one project cwd on a macro. Returns `{ ok: true, macro }` or
347
+ * `{ ok: false, error }`. A macro with '*' is shown everywhere and cannot be
348
+ * narrowed here: `{ ok: false, error: 'macro is shown in every project' }`
349
+ * (enabled=true on a '*' macro is a no-op success).
350
+ */
351
+ async function setMacroProject(input, opts = {}) {
352
+ const { id, cwd, enabled } = MacroSetProjectSchema.parse(input);
353
+ const filePath = resolvePath(opts);
354
+ const target = normalizeCwd(cwd);
355
+ return serialize(async () => {
356
+ const macros = await loadForWrite(filePath, opts);
357
+ const idx = macros.findIndex((m) => m.id === id);
358
+ if (idx === -1) return { ok: false, error: `macro not found: ${id}` };
359
+ const macro = macros[idx];
360
+ if (macro.projects.includes(ALL_PROJECTS)) {
361
+ if (enabled) return { ok: true, macro };
362
+ return { ok: false, error: 'macro is shown in every project' };
363
+ }
364
+ const has = macro.projects.includes(target);
365
+ if (enabled === has) return { ok: true, macro };
366
+ const projects = enabled ? [...macro.projects, target] : macro.projects.filter((p) => p !== target);
367
+ if (projects.length > 200) return { ok: false, error: 'too many projects' };
368
+ const updated = { ...macro, projects, updatedAt: new Date().toISOString() };
369
+ macros[idx] = updated;
370
+ await writeStore(filePath, macros);
371
+ return { ok: true, macro: updated };
372
+ });
373
+ }
374
+
375
+ module.exports = {
376
+ ALL_PROJECTS,
377
+ MacroSchema,
378
+ MacroSaveSchema,
379
+ MacroDeleteSchema,
380
+ MacroSetProjectSchema,
381
+ listMacros,
382
+ saveMacro,
383
+ deleteMacro,
384
+ setMacroProject,
385
+ defaultFilePath,
386
+ };
@@ -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
  {
@@ -295,11 +304,11 @@ const MCP_RECIPES = [
295
304
  id: 'unstick-needs-review-job',
296
305
  title: 'Unstick a job stuck in needs_review',
297
306
  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.',
307
+ 'Call scheduler_list_prds with status:"needs_review" (or scheduler_list_jobs) to find the slug.',
308
+ 'Call scheduler_get_prd with that slug to read the PRD and why it parked.',
309
+ '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.',
310
+ '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.',
311
+ 'The next scheduler pass runs it again. Confirm with scheduler_list_jobs or scheduler_list_prds.',
303
312
  ],
304
313
  },
305
314
  {
@@ -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
@@ -126,9 +126,19 @@ function reportToTelemetry({ cwd, scope, level, tabId, epicId, tags, message })
126
126
  } catch { /* telemetry must never break the caller — this is the sole error funnel */ }
127
127
  }
128
128
 
129
+ // realpath of the deepest existing ancestor + the not-yet-existing tail, so a cwd that was
130
+ // never created still compares in the same spelling as a symlinked root (macOS /var -> /private/var).
129
131
  function realOrResolved(p) {
130
132
  const abs = path.resolve(p);
131
- try { return fs.realpathSync(abs); } catch { return abs; }
133
+ let head = abs;
134
+ const tail = [];
135
+ for (;;) {
136
+ try { return path.join(fs.realpathSync(head), ...tail.reverse()); } catch { /* walk up */ }
137
+ const up = path.dirname(head);
138
+ if (up === head) return abs;
139
+ tail.push(path.basename(head));
140
+ head = up;
141
+ }
132
142
  }
133
143
 
134
144
  function isInside(child, parent) {
@@ -55,11 +55,6 @@ const OWNERS = Object.freeze({
55
55
  'project-pages': 'project-home',
56
56
  // Structured per-tab error log lines (JSONL), tagged for tracing/analysis.
57
57
  'logs': 'logs',
58
- // Host on Bilko.run tab's deterministic bundle prep (dist/index.html +
59
- // dist/manifest.json only — publish-state.json and anything the
60
- // bilko-host-publisher Epic authors beyond dist/ is agent-Write-tool
61
- // output, same unenforceable-by-construction class as project-pages/output.
62
- 'bilko-host': 'bilko-host',
63
58
  // Memory Clusters owns its own regenerable per-project cache (PRD 1389) —
64
59
  // memoryAggregate.cjs's clustering result, rebuilt on any explicit
65
60
  // refresh:true. See memory-clusters/README.md.
@@ -0,0 +1,32 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * pidAlive.cjs — single source of truth for "is this pid alive" liveness.
5
+ *
6
+ * Four independent copies of this exact check had drifted apart:
7
+ * reaperHelpers.cjs's claudePidAlive (bug: caught EPERM and returned false,
8
+ * never crediting a pid it couldn't signal but which demonstrably exists),
9
+ * watchdogHelpers.cjs's isPidAlive, reservationExpiry.cjs's defaultPidAlive,
10
+ * and instanceLock.cjs's pidAlive (these three already treated EPERM as
11
+ * alive, but each reimplemented the same three lines). This module is now
12
+ * the one place the rule lives; the others re-export thin aliases so every
13
+ * existing import keeps working.
14
+ *
15
+ * Rule: an invalid pid (not an integer, or <= 1 — pid 1 is init/launchd,
16
+ * never a real target) is never alive. `process.kill(pid, 0)` (no signal
17
+ * sent) succeeding means the pid exists and we can signal it → alive. EPERM
18
+ * (pid exists, owned by another user — we just can't signal it) also counts
19
+ * as alive: the process demonstrably exists. Anything else (ESRCH — no such
20
+ * process) → dead.
21
+ */
22
+ function pidAlive(pid) {
23
+ if (!Number.isInteger(pid) || pid <= 1) return false;
24
+ try {
25
+ process.kill(pid, 0);
26
+ return true;
27
+ } catch (e) {
28
+ return e?.code === 'EPERM';
29
+ }
30
+ }
31
+
32
+ module.exports = { pidAlive };