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
@@ -1,1175 +0,0 @@
1
- /**
2
- * delegationReadiness.test.cjs — unit tests for the "can this project
3
- * actually delegate?" probe. Uses a temp HOME and a temp cwd so the real
4
- * ~/.claude and this repo's own config are never touched.
5
- *
6
- * Run: timeout 300 npx vitest run src/main/lib/__tests__/delegationReadiness.test.cjs
7
- */
8
-
9
- import { test, expect, afterEach, beforeEach } from 'vitest';
10
- const fs = require('node:fs');
11
- const fsp = require('node:fs/promises');
12
- const os = require('node:os');
13
- const path = require('node:path');
14
- const {
15
- checkDelegationReadiness,
16
- ensureGuardsInstalled,
17
- clearGuardsInstalledCache,
18
- installPrdWriteGuard,
19
- installDestructiveGitGuard,
20
- installInlineImplementationGuard,
21
- probeSchedulerMcpLive,
22
- clearLiveProbeCache,
23
- PRD_WRITE_GUARD_SCRIPT,
24
- DESTRUCTIVE_GIT_GUARD_SCRIPT,
25
- INLINE_IMPLEMENTATION_GUARD_SCRIPT,
26
- SELF_SCHEDULE_GUARD_SCRIPT,
27
- } = require('../delegationReadiness.cjs');
28
- const { todayFile: opsErrorLogTodayFile } = require('../opsErrorLog.cjs');
29
- const {
30
- writeGuardShims,
31
- shimPath: guardShimPath,
32
- hooksDir: guardHooksDir,
33
- pointerPath: guardPointerPath,
34
- APP_ROOT: GUARD_APP_ROOT,
35
- } = require('../guardShims.cjs');
36
-
37
- const REQUIRED_TOOLS = ['scheduler_create_prd', 'session_manager_help'];
38
-
39
- beforeEach(() => {
40
- clearLiveProbeCache();
41
- clearGuardsInstalledCache();
42
- });
43
-
44
- const tmpDirs = [];
45
- afterEach(async () => {
46
- clearLiveProbeCache();
47
- clearGuardsInstalledCache();
48
- while (tmpDirs.length) {
49
- const d = tmpDirs.pop();
50
- await fsp.rm(d, { recursive: true, force: true });
51
- }
52
- });
53
-
54
- async function mkTmp(prefix) {
55
- const d = await fsp.mkdtemp(path.join(os.tmpdir(), prefix));
56
- tmpDirs.push(d);
57
- return d;
58
- }
59
-
60
- async function writeJson(absPath, value) {
61
- await fsp.mkdir(path.dirname(absPath), { recursive: true });
62
- await fsp.writeFile(absPath, JSON.stringify(value), 'utf8');
63
- }
64
-
65
- /** A stub stdio MCP server: answers initialize + tools/list over stdin/stdout. */
66
- async function writeAnsweringStub(dir, { toolNames = REQUIRED_TOOLS, countFile = null } = {}) {
67
- const scriptPath = path.join(dir, 'stub-mcp-server.cjs');
68
- const body = `
69
- 'use strict';
70
- const readline = require('node:readline');
71
- ${countFile ? `require('node:fs').appendFileSync(${JSON.stringify(countFile)}, 'x\\n');` : ''}
72
- const rl = readline.createInterface({ input: process.stdin });
73
- rl.on('line', (line) => {
74
- let msg;
75
- try { msg = JSON.parse(line); } catch { return; }
76
- if (msg.id === 1) {
77
- process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { protocolVersion: '2024-11-05', capabilities: {}, serverInfo: { name: 'stub', version: '1' } } }) + '\\n');
78
- } else if (msg.id === 2) {
79
- const tools = ${JSON.stringify(toolNames)}.map((name) => ({ name }));
80
- process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: 2, result: { tools } }) + '\\n');
81
- }
82
- });
83
- `;
84
- await fsp.writeFile(scriptPath, body, 'utf8');
85
- return scriptPath;
86
- }
87
-
88
- /** A stub that never responds to anything — exercises the timeout path. */
89
- async function writeSilentStub(dir) {
90
- const scriptPath = path.join(dir, 'silent-mcp-server.cjs');
91
- await fsp.writeFile(scriptPath, 'process.stdin.resume();\n', 'utf8');
92
- return scriptPath;
93
- }
94
-
95
- async function makeGreenFixtures() {
96
- const homeDir = await mkTmp('sm-delegation-home-');
97
- const cwd = await mkTmp('sm-delegation-cwd-');
98
-
99
- const scriptPath = await writeAnsweringStub(homeDir);
100
- await writeJson(path.join(homeDir, '.claude.json'), {
101
- mcpServers: { 'session-manager-scheduler': { type: 'stdio', command: 'node', args: [scriptPath] } },
102
- });
103
- await writeJson(path.join(homeDir, '.claude', 'settings.json'), {
104
- enabledPlugins: { 'session-manager-dev@session-manager': true },
105
- });
106
- await fsp.mkdir(path.join(homeDir, '.claude', 'agents'), { recursive: true });
107
- await fsp.writeFile(path.join(homeDir, '.claude', 'agents', 'dev-lead.md'), '# dev-lead', 'utf8');
108
- // The canonical, sanctioned form: an ABSOLUTE path to session-manager's own
109
- // guard script (installPrdWriteGuard's "reference, never vendor" decision).
110
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
111
- hooks: {
112
- PreToolUse: [
113
- {
114
- matcher: 'Write|Edit|NotebookEdit',
115
- hooks: [
116
- { type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` },
117
- { type: 'command', command: `node ${INLINE_IMPLEMENTATION_GUARD_SCRIPT}` },
118
- ],
119
- },
120
- {
121
- matcher: 'Bash',
122
- hooks: [{ type: 'command', command: `node ${DESTRUCTIVE_GIT_GUARD_SCRIPT}` }],
123
- },
124
- {
125
- matcher: 'ScheduleWakeup|CronCreate|Task|Agent',
126
- hooks: [{ type: 'command', command: `node ${SELF_SCHEDULE_GUARD_SCRIPT}` }],
127
- },
128
- ],
129
- },
130
- });
131
-
132
- return { homeDir, cwd, scriptPath };
133
- }
134
-
135
- test('all nine checks pass on a fully-configured project', async () => {
136
- const { homeDir, cwd } = await makeGreenFixtures();
137
- const result = await checkDelegationReadiness({ cwd, homeDir });
138
-
139
- expect(result.ok).toBe(true);
140
- expect(result.checks).toHaveLength(9);
141
- expect(result.checks.every((c) => c.ok)).toBe(true);
142
- expect(result.checks.map((c) => c.id)).toEqual([
143
- 'scheduler-mcp',
144
- 'scheduler-mcp-live',
145
- 'scheduler-mcp-project-duplicate',
146
- 'dev-plugin',
147
- 'agent-personas',
148
- 'prd-write-guard',
149
- 'destructive-git-guard',
150
- 'inline-implementation-guard',
151
- 'self-schedule-guard',
152
- ]);
153
- }, 15_000);
154
-
155
- test('scheduler-mcp: passes via project-scope .mcp.json even without user scope', async () => {
156
- const { homeDir, cwd } = await makeGreenFixtures();
157
- await writeJson(path.join(homeDir, '.claude.json'), { mcpServers: {} });
158
- await writeJson(path.join(cwd, '.mcp.json'), {
159
- mcpServers: { 'session-manager-scheduler': { command: 'node', args: [] } },
160
- });
161
-
162
- const result = await checkDelegationReadiness({ cwd, homeDir });
163
- const check = result.checks.find((c) => c.id === 'scheduler-mcp');
164
- expect(check.ok).toBe(true);
165
- }, 15_000);
166
-
167
- test('scheduler-mcp: fails with a runnable fix when absent from both scopes', async () => {
168
- const { homeDir, cwd } = await makeGreenFixtures();
169
- await writeJson(path.join(homeDir, '.claude.json'), { mcpServers: {} });
170
-
171
- const result = await checkDelegationReadiness({ cwd, homeDir });
172
- const check = result.checks.find((c) => c.id === 'scheduler-mcp');
173
- expect(check.ok).toBe(false);
174
- expect(result.ok).toBe(false);
175
- expect(check.fix).toMatch(/^claude mcp add session-manager-scheduler --scope user/);
176
- expect(check.fix).toContain('scheduler-mcp-server.cjs');
177
- }, 15_000);
178
-
179
- test('scheduler-mcp: fails when the user-scope script path is RELATIVE', async () => {
180
- const { homeDir, cwd } = await makeGreenFixtures();
181
- await writeJson(path.join(homeDir, '.claude.json'), {
182
- mcpServers: { 'session-manager-scheduler': { command: 'node', args: ['scripts/scheduler-mcp-server.cjs'] } },
183
- });
184
-
185
- const result = await checkDelegationReadiness({ cwd, homeDir });
186
- const check = result.checks.find((c) => c.id === 'scheduler-mcp');
187
- expect(check.ok).toBe(false);
188
- expect(check.detail).toMatch(/non-absolute/);
189
- expect(check.fix).toMatch(/^claude mcp add session-manager-scheduler --scope user/);
190
- // Live probe has nothing runnable to trust, so it must not report ready either.
191
- expect(result.checks.find((c) => c.id === 'scheduler-mcp-live').skipped).toBe(true);
192
- }, 15_000);
193
-
194
- test('scheduler-mcp: fails when the user-scope script path is absolute but MISSING', async () => {
195
- const { homeDir, cwd } = await makeGreenFixtures();
196
- await writeJson(path.join(homeDir, '.claude.json'), {
197
- mcpServers: { 'session-manager-scheduler': { command: 'node', args: [path.join(homeDir, 'does-not-exist.cjs')] } },
198
- });
199
-
200
- const result = await checkDelegationReadiness({ cwd, homeDir });
201
- const check = result.checks.find((c) => c.id === 'scheduler-mcp');
202
- expect(check.ok).toBe(false);
203
- expect(check.detail).toMatch(/no longer exists/);
204
- }, 15_000);
205
-
206
- test('dev-plugin: fails independently when enabledPlugins is missing the key', async () => {
207
- const { homeDir, cwd } = await makeGreenFixtures();
208
- await writeJson(path.join(homeDir, '.claude', 'settings.json'), { enabledPlugins: {} });
209
-
210
- const result = await checkDelegationReadiness({ cwd, homeDir });
211
- const check = result.checks.find((c) => c.id === 'dev-plugin');
212
- expect(check.ok).toBe(false);
213
- expect(result.ok).toBe(false);
214
- expect(check.fix).toBeTruthy();
215
- // the other checks still pass independently
216
- expect(result.checks.filter((c) => c.id !== 'dev-plugin').every((c) => c.ok)).toBe(true);
217
- }, 15_000);
218
-
219
- test('agent-personas: fails independently when ~/.claude/agents has no personas', async () => {
220
- const { homeDir, cwd } = await makeGreenFixtures();
221
- await fsp.rm(path.join(homeDir, '.claude', 'agents', 'dev-lead.md'));
222
-
223
- const result = await checkDelegationReadiness({ cwd, homeDir });
224
- const check = result.checks.find((c) => c.id === 'agent-personas');
225
- expect(check.ok).toBe(false);
226
- expect(result.ok).toBe(false);
227
- }, 15_000);
228
-
229
- test('agent-personas: passes via project-scope .claude/agents/ even without global personas', async () => {
230
- const { homeDir, cwd } = await makeGreenFixtures();
231
- await fsp.rm(path.join(homeDir, '.claude', 'agents'), { recursive: true, force: true });
232
- await fsp.mkdir(path.join(cwd, '.claude', 'agents'), { recursive: true });
233
- await fsp.writeFile(path.join(cwd, '.claude', 'agents', 'builder.md'), '# builder', 'utf8');
234
-
235
- const result = await checkDelegationReadiness({ cwd, homeDir });
236
- const check = result.checks.find((c) => c.id === 'agent-personas');
237
- expect(check.ok).toBe(true);
238
- }, 15_000);
239
-
240
- test('prd-write-guard: fails independently when the hook is missing', async () => {
241
- const { homeDir, cwd } = await makeGreenFixtures();
242
- await writeJson(path.join(cwd, '.claude', 'settings.json'), { hooks: { PreToolUse: [] } });
243
-
244
- const result = await checkDelegationReadiness({ cwd, homeDir });
245
- const check = result.checks.find((c) => c.id === 'prd-write-guard');
246
- expect(check.ok).toBe(false);
247
- expect(result.ok).toBe(false);
248
- }, 15_000);
249
-
250
- test('unparseable JSON files yield ok:false with a detail, never a throw', async () => {
251
- const { homeDir, cwd } = await makeGreenFixtures();
252
- await fs.promises.writeFile(path.join(homeDir, '.claude.json'), '{ not valid json', 'utf8');
253
- await fs.promises.writeFile(path.join(homeDir, '.claude', 'settings.json'), '{ not valid json', 'utf8');
254
- await fs.promises.writeFile(path.join(cwd, '.claude', 'settings.json'), '{ not valid json', 'utf8');
255
-
256
- await expect(checkDelegationReadiness({ cwd, homeDir })).resolves.toBeTruthy();
257
- const result = await checkDelegationReadiness({ cwd, homeDir });
258
-
259
- const scheduler = result.checks.find((c) => c.id === 'scheduler-mcp');
260
- const devPlugin = result.checks.find((c) => c.id === 'dev-plugin');
261
- const guard = result.checks.find((c) => c.id === 'prd-write-guard');
262
- expect(scheduler.ok).toBe(false);
263
- expect(scheduler.detail).toBeTruthy();
264
- expect(devPlugin.ok).toBe(false);
265
- expect(devPlugin.detail).toBeTruthy();
266
- expect(guard.ok).toBe(false);
267
- expect(guard.detail).toBeTruthy();
268
- expect(result.ok).toBe(false);
269
- }, 15_000);
270
-
271
- // ─────────────────────────────── scheduler-mcp-project-duplicate
272
-
273
- test('scheduler-mcp-project-duplicate: warns when both scopes register the server', async () => {
274
- const { homeDir, cwd } = await makeGreenFixtures();
275
- await writeJson(path.join(cwd, '.mcp.json'), {
276
- mcpServers: { 'session-manager-scheduler': { command: 'node', args: ['scripts/scheduler-mcp-server.cjs'] } },
277
- });
278
-
279
- const result = await checkDelegationReadiness({ cwd, homeDir });
280
- const check = result.checks.find((c) => c.id === 'scheduler-mcp-project-duplicate');
281
- expect(check.ok).toBe(true);
282
- expect(check.warn).toBe(true);
283
- expect(check.detail).toMatch(/user scope is canonical/);
284
- // A warning never fails the overall gate.
285
- expect(result.ok).toBe(true);
286
- }, 15_000);
287
-
288
- test('scheduler-mcp-project-duplicate: no warning when only user scope is registered', async () => {
289
- const { homeDir, cwd } = await makeGreenFixtures();
290
-
291
- const result = await checkDelegationReadiness({ cwd, homeDir });
292
- const check = result.checks.find((c) => c.id === 'scheduler-mcp-project-duplicate');
293
- expect(check.ok).toBe(true);
294
- expect(check.warn).toBe(false);
295
- }, 15_000);
296
-
297
- // ─────────────────────────────── scheduler-mcp-live
298
-
299
- test('scheduler-mcp-live: ok when the server answers tools/list with both required tools', async () => {
300
- const dir = await mkTmp('sm-live-probe-');
301
- const scriptPath = await writeAnsweringStub(dir);
302
-
303
- const result = await probeSchedulerMcpLive({ command: 'node', args: [scriptPath], env: {} });
304
- expect(result.ok).toBe(true);
305
- expect(result.detail).toContain('scheduler_create_prd');
306
- }, 15_000);
307
-
308
- test('scheduler-mcp-live: fails naming the missing tool when the server answers WITHOUT it', async () => {
309
- const dir = await mkTmp('sm-live-probe-');
310
- const scriptPath = await writeAnsweringStub(dir, { toolNames: ['scheduler_create_prd'] });
311
-
312
- const result = await probeSchedulerMcpLive({ command: 'node', args: [scriptPath], env: {} });
313
- expect(result.ok).toBe(false);
314
- expect(result.detail).toContain('session_manager_help');
315
- }, 15_000);
316
-
317
- test('scheduler-mcp-live: times out (bounded) against a server that never answers, and kills the child', async () => {
318
- const dir = await mkTmp('sm-live-probe-');
319
- const scriptPath = await writeSilentStub(dir);
320
-
321
- const start = Date.now();
322
- const result = await probeSchedulerMcpLive({ command: 'node', args: [scriptPath], env: {} });
323
- const elapsed = Date.now() - start;
324
-
325
- expect(result.ok).toBe(false);
326
- expect(result.detail).toBe('timeout');
327
- expect(elapsed).toBeLessThan(15_000);
328
- }, 20_000);
329
-
330
- test('scheduler-mcp-live: is skipped, not failed, when scheduler-mcp already failed', async () => {
331
- const { homeDir, cwd } = await makeGreenFixtures();
332
- await writeJson(path.join(homeDir, '.claude.json'), { mcpServers: {} });
333
-
334
- const result = await checkDelegationReadiness({ cwd, homeDir });
335
- const live = result.checks.find((c) => c.id === 'scheduler-mcp-live');
336
- expect(live.ok).toBe(true);
337
- expect(live.skipped).toBe(true);
338
- // One red row for the registration failure, not two.
339
- expect(result.checks.filter((c) => !c.ok)).toHaveLength(1);
340
- }, 15_000);
341
-
342
- test('scheduler-mcp-live: memoizes the probe per registration signature within the TTL', async () => {
343
- const dir = await mkTmp('sm-live-probe-');
344
- const countFile = path.join(dir, 'spawn-count.txt');
345
- const scriptPath = await writeAnsweringStub(dir, { countFile });
346
-
347
- const { homeDir, cwd } = await makeGreenFixtures();
348
- await writeJson(path.join(homeDir, '.claude.json'), {
349
- mcpServers: { 'session-manager-scheduler': { type: 'stdio', command: 'node', args: [scriptPath] } },
350
- });
351
-
352
- await checkDelegationReadiness({ cwd, homeDir });
353
- await checkDelegationReadiness({ cwd, homeDir });
354
-
355
- const spawnCount = (await fsp.readFile(countFile, 'utf8')).trim().split('\n').filter(Boolean).length;
356
- expect(spawnCount).toBe(1);
357
- }, 15_000);
358
-
359
- // ─────────────────────────────── installPrdWriteGuard (unchanged behavior)
360
-
361
- test('installPrdWriteGuard: writes the canonical STABLE-SHIM-path entry and turns the check green', async () => {
362
- const { homeDir, cwd } = await makeGreenFixtures();
363
- await fsp.rm(path.join(cwd, '.claude', 'settings.json'));
364
-
365
- const r = await installPrdWriteGuard({ cwd, homeDir });
366
- expect(r.ok).toBe(true);
367
- expect(r.action).toBe('installed');
368
- const shimCommand = `node ${guardShimPath('guard-prd-writes.cjs', homeDir)}`;
369
- expect(r.command).toBe(shimCommand);
370
- // The shim path survives app upgrades; it must never be the raw app-root script.
371
- expect(r.command).not.toBe(`node ${PRD_WRITE_GUARD_SCRIPT}`);
372
-
373
- const written = JSON.parse(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8'));
374
- expect(written.hooks.PreToolUse).toEqual([
375
- { matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: shimCommand }] },
376
- ]);
377
- const result = await checkDelegationReadiness({ cwd, homeDir });
378
- expect(result.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
379
- }, 15_000);
380
-
381
- test('installPrdWriteGuard: is idempotent — a healthy guard is a no-op', async () => {
382
- const { homeDir, cwd } = await makeGreenFixtures();
383
- await installPrdWriteGuard({ cwd, homeDir });
384
- const before = fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8');
385
-
386
- const again = await installPrdWriteGuard({ cwd, homeDir });
387
- expect(again.action).toBe('already-installed');
388
- expect(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8')).toBe(before);
389
- });
390
-
391
- test('installPrdWriteGuard: refuses on unparseable settings rather than discarding them', async () => {
392
- const { homeDir, cwd } = await makeGreenFixtures();
393
- await fsp.writeFile(path.join(cwd, '.claude', 'settings.json'), '{ not valid json', 'utf8');
394
-
395
- const r = await installPrdWriteGuard({ cwd, homeDir });
396
- expect(r.ok).toBe(false);
397
- expect(r.action).toBe('error');
398
- expect(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8')).toBe('{ not valid json');
399
- });
400
-
401
- // ─────────────────────────────── stable-shim indirection (guardShims.cjs)
402
-
403
- test('installPrdWriteGuard: repairs a hook pointing at a dead ephemeral _npx cache path to the stable shim path', async () => {
404
- const { homeDir, cwd } = await makeGreenFixtures();
405
- // Shaped exactly like the decay this PRD closes: an absolute path under a
406
- // version-scoped npx cache dir that no longer exists on this machine.
407
- const deadNpxPath = path.join(
408
- homeDir, '.npm', '_npx', '5346543b21849140', 'node_modules',
409
- 'claude-code-session-manager', 'scripts', 'hooks', 'guard-prd-writes.cjs',
410
- );
411
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
412
- hooks: { PreToolUse: [{ matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${deadNpxPath}` }] }] },
413
- });
414
-
415
- const before = await checkDelegationReadiness({ cwd, homeDir });
416
- expect(before.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(false);
417
-
418
- const r = await installPrdWriteGuard({ cwd, homeDir });
419
- expect(r.ok).toBe(true);
420
- expect(r.action).toBe('repaired');
421
- const shimCommand = `node ${guardShimPath('guard-prd-writes.cjs', homeDir)}`;
422
- expect(r.command).toBe(shimCommand);
423
-
424
- const written = JSON.parse(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8'));
425
- const writeMatchers = written.hooks.PreToolUse.filter((m) => m.matcher === 'Write|Edit|NotebookEdit');
426
- expect(writeMatchers).toHaveLength(1);
427
- expect(writeMatchers[0].hooks).toEqual([{ type: 'command', command: shimCommand }]);
428
-
429
- const after = await checkDelegationReadiness({ cwd, homeDir });
430
- expect(after.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
431
- }, 15_000);
432
-
433
- test('checkPrdWriteGuard: reports red — not a false green — when an installed shim\'s pointer has decayed (one hop downstream of the hook command)', async () => {
434
- const { homeDir, cwd } = await makeGreenFixtures();
435
- // makeGreenFixtures seeds a hook pointing DIRECTLY at the app-root script —
436
- // already healthy, so installPrdWriteGuard would short-circuit as
437
- // 'already-installed' without ever switching the command to the shim.
438
- // Remove it first so the install genuinely writes the shim-path command.
439
- await fsp.rm(path.join(cwd, '.claude', 'settings.json'));
440
- const r = await installPrdWriteGuard({ cwd, homeDir });
441
- expect(r.ok).toBe(true);
442
- expect(r.command).toBe(`node ${guardShimPath('guard-prd-writes.cjs', homeDir)}`);
443
- const healthy = await checkDelegationReadiness({ cwd, homeDir });
444
- expect(healthy.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
445
-
446
- // Corrupt ONLY the pointer — the shim FILE at the hook's command path never
447
- // moves, which is exactly why checking just its existence isn't enough.
448
- await writeJson(guardPointerPath(homeDir), { appRoot: path.join(homeDir, 'deleted-app-root') });
449
-
450
- const decayed = await checkDelegationReadiness({ cwd, homeDir });
451
- const check = decayed.checks.find((c) => c.id === 'prd-write-guard');
452
- expect(check.ok).toBe(false);
453
- expect(check.detail).toMatch(/pointer has decayed/);
454
- }, 15_000);
455
-
456
- test('checkPrdWriteGuard: accepts BOTH a direct app-root path and the stable shim path as healthy', async () => {
457
- const { homeDir, cwd } = await makeGreenFixtures(); // direct app-root path, already healthy
458
- const directResult = await checkDelegationReadiness({ cwd, homeDir });
459
- expect(directResult.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
460
-
461
- const shimResult = await writeGuardShims({ homeDir });
462
- expect(shimResult.ok).toBe(true);
463
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
464
- hooks: { PreToolUse: [{ matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${guardShimPath('guard-prd-writes.cjs', homeDir)}` }] }] },
465
- });
466
- const viaShim = await checkDelegationReadiness({ cwd, homeDir });
467
- expect(viaShim.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
468
- }, 15_000);
469
-
470
- test('installPrdWriteGuard: refuses with ok:false/action:error when the guard shim cannot be written, never writing a hook pointing at a missing shim', async () => {
471
- const { cwd } = await makeGreenFixtures();
472
- await fsp.rm(path.join(cwd, '.claude', 'settings.json'));
473
- const base = await mkTmp('sm-delegation-unwritable-');
474
- const blocker = path.join(base, 'blocker-file');
475
- await fsp.writeFile(blocker, 'x', 'utf8');
476
- const unwritableHomeDir = path.join(blocker, 'home'); // parent segment is a FILE -> mkdir fails
477
-
478
- const r = await installPrdWriteGuard({ cwd, homeDir: unwritableHomeDir });
479
- expect(r.ok).toBe(false);
480
- expect(r.action).toBe('error');
481
- expect(r.error).toBeTruthy();
482
- expect(fs.existsSync(path.join(cwd, '.claude', 'settings.json'))).toBe(false);
483
- }, 15_000);
484
-
485
- // The guard script is not just referenced — it is EXERCISED here, so the
486
- // "certifies a config that has never been proven to run" gap is closed by a
487
- // real end-to-end run of the exact command installPrdWriteGuard writes.
488
- test('the installed command actually DENIES a scheduler PRD write and allows a normal one', async () => {
489
- const { cwd } = await makeGreenFixtures();
490
- const { execFileSync } = require('node:child_process');
491
-
492
- const run = (toolInput) => JSON.parse(execFileSync('node', [PRD_WRITE_GUARD_SCRIPT], {
493
- input: JSON.stringify({ tool_name: 'Write', tool_input: toolInput, cwd }),
494
- encoding: 'utf8',
495
- }));
496
-
497
- const denied = run({ file_path: path.join(cwd, 'session-manager-operations', 'scheduler', 'prds', '1234-x.md'), content: '# x' });
498
- expect(denied.hookSpecificOutput?.permissionDecision).toBe('deny');
499
-
500
- const allowed = run({ file_path: path.join(cwd, 'src', 'x.ts'), content: 'x' });
501
- expect(allowed.hookSpecificOutput?.permissionDecision).not.toBe('deny');
502
- });
503
-
504
- // ─────────────────────────────── destructive-git-guard / installDestructiveGitGuard
505
-
506
- test('destructive-git-guard: fails independently when the hook is missing', async () => {
507
- const { homeDir, cwd } = await makeGreenFixtures();
508
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
509
- hooks: {
510
- PreToolUse: [
511
- {
512
- matcher: 'Write|Edit|NotebookEdit',
513
- hooks: [
514
- { type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` },
515
- { type: 'command', command: `node ${INLINE_IMPLEMENTATION_GUARD_SCRIPT}` },
516
- ],
517
- },
518
- {
519
- matcher: 'ScheduleWakeup|CronCreate|Task|Agent',
520
- hooks: [{ type: 'command', command: `node ${SELF_SCHEDULE_GUARD_SCRIPT}` }],
521
- },
522
- ],
523
- },
524
- });
525
-
526
- const result = await checkDelegationReadiness({ cwd, homeDir });
527
- const check = result.checks.find((c) => c.id === 'destructive-git-guard');
528
- expect(check.ok).toBe(false);
529
- expect(result.ok).toBe(false);
530
- // the other checks still pass independently
531
- expect(result.checks.filter((c) => c.id !== 'destructive-git-guard').every((c) => c.ok)).toBe(true);
532
- }, 15_000);
533
-
534
- test('destructive-git-guard: fails when the hook names a script that does not exist', async () => {
535
- const { homeDir, cwd } = await makeGreenFixtures();
536
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
537
- hooks: {
538
- PreToolUse: [
539
- {
540
- matcher: 'Write|Edit|NotebookEdit',
541
- hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }],
542
- },
543
- {
544
- matcher: 'Bash',
545
- hooks: [{ type: 'command', command: 'node /does/not/exist/guard-destructive-git.cjs' }],
546
- },
547
- ],
548
- },
549
- });
550
-
551
- const result = await checkDelegationReadiness({ cwd, homeDir });
552
- const check = result.checks.find((c) => c.id === 'destructive-git-guard');
553
- expect(check.ok).toBe(false);
554
- expect(check.detail).toMatch(/does not exist/);
555
- }, 15_000);
556
-
557
- test('installDestructiveGitGuard: writes the canonical STABLE-SHIM-path entry and turns the check green', async () => {
558
- const { homeDir, cwd } = await makeGreenFixtures();
559
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
560
- hooks: {
561
- PreToolUse: [
562
- {
563
- matcher: 'Write|Edit|NotebookEdit',
564
- hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }],
565
- },
566
- ],
567
- },
568
- });
569
-
570
- const r = await installDestructiveGitGuard({ cwd, homeDir });
571
- expect(r.ok).toBe(true);
572
- expect(r.action).toBe('installed');
573
- const shimCommand = `node ${guardShimPath('guard-destructive-git.cjs', homeDir)}`;
574
- expect(r.command).toBe(shimCommand);
575
- expect(r.command).not.toBe(`node ${DESTRUCTIVE_GIT_GUARD_SCRIPT}`);
576
-
577
- const written = JSON.parse(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8'));
578
- // The pre-existing Write|Edit|NotebookEdit matcher (and its hook) survives untouched.
579
- expect(written.hooks.PreToolUse).toContainEqual(
580
- { matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }] },
581
- );
582
- expect(written.hooks.PreToolUse).toContainEqual(
583
- { matcher: 'Bash', hooks: [{ type: 'command', command: shimCommand }] },
584
- );
585
-
586
- const result = await checkDelegationReadiness({ cwd, homeDir });
587
- expect(result.checks.find((c) => c.id === 'destructive-git-guard').ok).toBe(true);
588
- expect(result.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
589
- }, 15_000);
590
-
591
- // The scenario app:install-destructive-git-guard (index.cjs) serves: a project
592
- // that got the first guard via the New Session "Fix it" button and never the
593
- // second (the starry-night-ships reproduction). The handler is a pass-through
594
- // to this function under the shared { cwd } schema, so this is its contract.
595
- test('installDestructiveGitGuard: flips destructive-git-guard FAIL -> PASS on a cwd seeded with only the prd-write-guard hook, by reference, idempotently', async () => {
596
- const { homeDir, cwd } = await makeGreenFixtures();
597
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
598
- await writeJson(settingsPath, {
599
- hooks: {
600
- PreToolUse: [
601
- { matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }] },
602
- ],
603
- },
604
- });
605
-
606
- const before = await checkDelegationReadiness({ cwd, homeDir });
607
- expect(before.checks.find((c) => c.id === 'destructive-git-guard')).toMatchObject({
608
- ok: false,
609
- fixAction: 'install-destructive-git-guard',
610
- detail: `no guard-destructive-git PreToolUse hook in ${cwd}/.claude/settings.json`,
611
- });
612
-
613
- const first = await installDestructiveGitGuard({ cwd, homeDir });
614
- expect(first).toMatchObject({ ok: true, action: 'installed', settingsPath });
615
-
616
- const written = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
617
- const bash = written.hooks.PreToolUse.filter((m) => m.matcher === 'Bash');
618
- expect(bash).toHaveLength(1);
619
- // By reference to the stable shim — never a copy inside the target cwd.
620
- const shimCommand = `node ${guardShimPath('guard-destructive-git.cjs', homeDir)}`;
621
- expect(bash[0].hooks).toEqual([{ type: 'command', command: shimCommand }]);
622
- expect(path.isAbsolute(DESTRUCTIVE_GIT_GUARD_SCRIPT)).toBe(true);
623
- expect(DESTRUCTIVE_GIT_GUARD_SCRIPT.startsWith(cwd + path.sep)).toBe(false);
624
- expect(fs.existsSync(path.join(cwd, 'scripts'))).toBe(false);
625
-
626
- const after = await checkDelegationReadiness({ cwd, homeDir });
627
- expect(after.checks.find((c) => c.id === 'destructive-git-guard').ok).toBe(true);
628
- expect(after.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
629
-
630
- // Second press: no-op, byte-identical file.
631
- const snapshot = fs.readFileSync(settingsPath, 'utf8');
632
- const second = await installDestructiveGitGuard({ cwd, homeDir });
633
- expect(second).toMatchObject({ ok: true, action: 'already-installed', settingsPath });
634
- expect(fs.readFileSync(settingsPath, 'utf8')).toBe(snapshot);
635
- }, 15_000);
636
-
637
- test('installDestructiveGitGuard: is idempotent — a healthy guard is a no-op', async () => {
638
- const { homeDir, cwd } = await makeGreenFixtures();
639
- const before = fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8');
640
-
641
- const again = await installDestructiveGitGuard({ cwd, homeDir });
642
- expect(again.action).toBe('already-installed');
643
- expect(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8')).toBe(before);
644
- });
645
-
646
- test('installDestructiveGitGuard: repairs a broken entry in place rather than duplicating it', async () => {
647
- const { homeDir, cwd } = await makeGreenFixtures();
648
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
649
- hooks: {
650
- PreToolUse: [
651
- {
652
- matcher: 'Write|Edit|NotebookEdit',
653
- hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }],
654
- },
655
- {
656
- matcher: 'Bash',
657
- hooks: [{ type: 'command', command: 'node /does/not/exist/guard-destructive-git.cjs' }],
658
- },
659
- ],
660
- },
661
- });
662
-
663
- const r = await installDestructiveGitGuard({ cwd, homeDir });
664
- expect(r.action).toBe('repaired');
665
-
666
- const written = JSON.parse(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8'));
667
- const bashMatchers = written.hooks.PreToolUse.filter((m) => m.matcher === 'Bash');
668
- expect(bashMatchers).toHaveLength(1);
669
- expect(bashMatchers[0].hooks).toEqual([{ type: 'command', command: `node ${guardShimPath('guard-destructive-git.cjs', homeDir)}` }]);
670
- });
671
-
672
- test('installDestructiveGitGuard: refuses on unparseable settings rather than discarding them', async () => {
673
- const { homeDir, cwd } = await makeGreenFixtures();
674
- await fsp.writeFile(path.join(cwd, '.claude', 'settings.json'), '{ not valid json', 'utf8');
675
-
676
- const r = await installDestructiveGitGuard({ cwd, homeDir });
677
- expect(r.ok).toBe(false);
678
- expect(r.action).toBe('error');
679
- expect(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8')).toBe('{ not valid json');
680
- });
681
-
682
- // The guard script is EXERCISED here too, same rationale as the
683
- // installPrdWriteGuard end-to-end test above.
684
- test('the installed destructive-git command actually DENIES a shared-tree stash and allows it inside an sm-job/ worktree', async () => {
685
- const { cwd } = await makeGreenFixtures();
686
- const { execFileSync } = require('node:child_process');
687
- const os2 = require('node:os');
688
-
689
- const run = (command, runCwd) => JSON.parse(execFileSync('node', [DESTRUCTIVE_GIT_GUARD_SCRIPT], {
690
- input: JSON.stringify({ tool_name: 'Bash', tool_input: { command }, cwd: runCwd }),
691
- encoding: 'utf8',
692
- }));
693
-
694
- const denied = run('git stash', cwd);
695
- expect(denied.hookSpecificOutput?.permissionDecision).toBe('deny');
696
-
697
- const worktreeCwd = path.join(process.env.SM_WORKTREE_ROOT || os2.tmpdir(), 'session-manager-job-worktrees', 'somehash', 'some-slug');
698
- const allowed = run('git stash', worktreeCwd);
699
- expect(allowed.hookSpecificOutput?.permissionDecision).not.toBe('deny');
700
- });
701
-
702
- // ─────────────────────────────── inline-implementation-guard / installInlineImplementationGuard
703
-
704
- test('inline-implementation-guard: fails independently when the hook is missing (not-installed detail)', async () => {
705
- const { homeDir, cwd } = await makeGreenFixtures();
706
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
707
- hooks: {
708
- PreToolUse: [
709
- {
710
- matcher: 'Write|Edit|NotebookEdit',
711
- hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }],
712
- },
713
- {
714
- matcher: 'Bash',
715
- hooks: [{ type: 'command', command: `node ${DESTRUCTIVE_GIT_GUARD_SCRIPT}` }],
716
- },
717
- {
718
- matcher: 'ScheduleWakeup|CronCreate|Task|Agent',
719
- hooks: [{ type: 'command', command: `node ${SELF_SCHEDULE_GUARD_SCRIPT}` }],
720
- },
721
- ],
722
- },
723
- });
724
-
725
- const result = await checkDelegationReadiness({ cwd, homeDir });
726
- const check = result.checks.find((c) => c.id === 'inline-implementation-guard');
727
- expect(check.ok).toBe(false);
728
- expect(check.fixAction).toBe('install-inline-implementation-guard');
729
- expect(check.detail).toBe(`no guard-inline-implementation PreToolUse hook in ${cwd}/.claude/settings.json — this is a nudge, not a hard gate`);
730
- expect(result.ok).toBe(false);
731
- // the other checks still pass independently
732
- expect(result.checks.filter((c) => c.id !== 'inline-implementation-guard').every((c) => c.ok)).toBe(true);
733
- }, 15_000);
734
-
735
- test('inline-implementation-guard: fails with the "would silently guard nothing" detail when the hook names a script that does not exist', async () => {
736
- const { homeDir, cwd } = await makeGreenFixtures();
737
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
738
- hooks: {
739
- PreToolUse: [
740
- {
741
- matcher: 'Write|Edit|NotebookEdit',
742
- hooks: [
743
- { type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` },
744
- { type: 'command', command: 'node /does/not/exist/guard-inline-implementation.cjs' },
745
- ],
746
- },
747
- {
748
- matcher: 'Bash',
749
- hooks: [{ type: 'command', command: `node ${DESTRUCTIVE_GIT_GUARD_SCRIPT}` }],
750
- },
751
- ],
752
- },
753
- });
754
-
755
- const result = await checkDelegationReadiness({ cwd, homeDir });
756
- const check = result.checks.find((c) => c.id === 'inline-implementation-guard');
757
- expect(check.ok).toBe(false);
758
- expect(check.detail).toBe(`guard-inline-implementation PreToolUse hook in ${cwd}/.claude/settings.json names a script that does not exist — it would silently guard nothing`);
759
- }, 15_000);
760
-
761
- test('inline-implementation-guard: ok when the hook resolves to an existing script file', async () => {
762
- const { homeDir, cwd } = await makeGreenFixtures();
763
- const result = await checkDelegationReadiness({ cwd, homeDir });
764
- const check = result.checks.find((c) => c.id === 'inline-implementation-guard');
765
- expect(check.ok).toBe(true);
766
- expect(check.fixAction).toBeNull();
767
- expect(check.detail).toBe(`guard-inline-implementation PreToolUse hook found in ${cwd}/.claude/settings.json, resolving to ${INLINE_IMPLEMENTATION_GUARD_SCRIPT}`);
768
- }, 15_000);
769
-
770
- // installInlineImplementationGuard shares installPrdWriteGuard's matcher
771
- // (Write|Edit|NotebookEdit), so its interesting merge path is APPENDING into
772
- // an existing matcher's hooks array — the branch destructive-git-guard's own
773
- // installer (a different matcher, Bash) never exercises. This is the scenario
774
- // a project that adopted only the PRD-write guard hits.
775
- test('installInlineImplementationGuard: appends into the EXISTING Write|Edit|NotebookEdit matcher rather than pushing a new one, preserving unrelated keys byte-for-byte', async () => {
776
- const { homeDir, cwd } = await makeGreenFixtures();
777
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
778
- const seeded = {
779
- someUnrelatedTopLevelKey: { nested: [1, 2, 3], note: 'do not touch' },
780
- hooks: {
781
- PreToolUse: [
782
- { matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }] },
783
- { matcher: 'Bash', hooks: [{ type: 'command', command: `node ${DESTRUCTIVE_GIT_GUARD_SCRIPT}` }] },
784
- ],
785
- },
786
- };
787
- await writeJson(settingsPath, seeded);
788
-
789
- const before = await checkDelegationReadiness({ cwd, homeDir });
790
- expect(before.checks.find((c) => c.id === 'inline-implementation-guard')).toMatchObject({
791
- ok: false,
792
- fixAction: 'install-inline-implementation-guard',
793
- });
794
-
795
- const r = await installInlineImplementationGuard({ cwd, homeDir });
796
- const inlineShimCommand = `node ${guardShimPath('guard-inline-implementation.cjs', homeDir)}`;
797
- expect(r).toMatchObject({ ok: true, action: 'installed', settingsPath, command: inlineShimCommand });
798
-
799
- const written = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
800
- // Exactly ONE Write|Edit|NotebookEdit matcher entry, now carrying BOTH commands.
801
- const writeMatchers = written.hooks.PreToolUse.filter((m) => m.matcher === 'Write|Edit|NotebookEdit');
802
- expect(writeMatchers).toHaveLength(1);
803
- expect(writeMatchers[0].hooks).toEqual([
804
- { type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` },
805
- { type: 'command', command: inlineShimCommand },
806
- ]);
807
- // The unrelated Bash matcher and every unrelated top-level key survive untouched.
808
- expect(written.hooks.PreToolUse).toContainEqual(
809
- { matcher: 'Bash', hooks: [{ type: 'command', command: `node ${DESTRUCTIVE_GIT_GUARD_SCRIPT}` }] },
810
- );
811
- expect(written.someUnrelatedTopLevelKey).toEqual(seeded.someUnrelatedTopLevelKey);
812
-
813
- const after = await checkDelegationReadiness({ cwd, homeDir });
814
- expect(after.checks.find((c) => c.id === 'inline-implementation-guard').ok).toBe(true);
815
- expect(after.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
816
- expect(after.checks.find((c) => c.id === 'destructive-git-guard').ok).toBe(true);
817
- }, 15_000);
818
-
819
- test('installInlineImplementationGuard: is idempotent — running it twice leaves exactly one entry, byte-identical file on the second press', async () => {
820
- const { homeDir, cwd } = await makeGreenFixtures();
821
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
822
- hooks: {
823
- PreToolUse: [
824
- { matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }] },
825
- ],
826
- },
827
- });
828
-
829
- const first = await installInlineImplementationGuard({ cwd, homeDir });
830
- expect(first.action).toBe('installed');
831
- const snapshot = fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8');
832
-
833
- const second = await installInlineImplementationGuard({ cwd, homeDir });
834
- expect(second.action).toBe('already-installed');
835
- expect(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8')).toBe(snapshot);
836
-
837
- const written = JSON.parse(snapshot);
838
- const writeMatchers = written.hooks.PreToolUse.filter((m) => m.matcher === 'Write|Edit|NotebookEdit');
839
- expect(writeMatchers).toHaveLength(1);
840
- expect(writeMatchers[0].hooks.filter((h) => h.command.includes('guard-inline-implementation'))).toHaveLength(1);
841
- });
842
-
843
- test('installInlineImplementationGuard: repairs an entry pointing at a now-nonexistent path in place rather than appending a duplicate', async () => {
844
- const { homeDir, cwd } = await makeGreenFixtures();
845
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
846
- await writeJson(settingsPath, {
847
- hooks: {
848
- PreToolUse: [
849
- {
850
- matcher: 'Write|Edit|NotebookEdit',
851
- hooks: [
852
- { type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` },
853
- { type: 'command', command: 'node /does/not/exist/guard-inline-implementation.cjs' },
854
- ],
855
- },
856
- ],
857
- },
858
- });
859
-
860
- const r = await installInlineImplementationGuard({ cwd, homeDir });
861
- expect(r.action).toBe('repaired');
862
-
863
- const written = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
864
- const writeMatchers = written.hooks.PreToolUse.filter((m) => m.matcher === 'Write|Edit|NotebookEdit');
865
- expect(writeMatchers).toHaveLength(1);
866
- const inlineHooks = writeMatchers[0].hooks.filter((h) => h.command.includes('guard-inline-implementation'));
867
- expect(inlineHooks).toHaveLength(1);
868
- expect(inlineHooks[0].command).toBe(`node ${guardShimPath('guard-inline-implementation.cjs', homeDir)}`);
869
- });
870
-
871
- test('installInlineImplementationGuard: refuses on unparseable settings rather than discarding them', async () => {
872
- const { homeDir, cwd } = await makeGreenFixtures();
873
- await fsp.writeFile(path.join(cwd, '.claude', 'settings.json'), '{ not valid json', 'utf8');
874
-
875
- const r = await installInlineImplementationGuard({ cwd, homeDir });
876
- expect(r.ok).toBe(false);
877
- expect(r.action).toBe('error');
878
- expect(fs.readFileSync(path.join(cwd, '.claude', 'settings.json'), 'utf8')).toBe('{ not valid json');
879
- });
880
-
881
- // ─────────────────────────────── missing-guard-script refusal (no lying success)
882
-
883
- // Renames the real guard script aside for the duration of `fn`, then restores
884
- // it — never deletes a real guard script from the working tree.
885
- async function withGuardScriptMissing(scriptPath, fn) {
886
- const movedTo = `${scriptPath}.moved-for-test`;
887
- await fsp.rename(scriptPath, movedTo);
888
- try {
889
- await fn();
890
- } finally {
891
- await fsp.rename(movedTo, scriptPath);
892
- }
893
- }
894
-
895
- test('all three *_GUARD_SCRIPT constants name a script that exists in this repo', () => {
896
- expect(fs.existsSync(PRD_WRITE_GUARD_SCRIPT)).toBe(true);
897
- expect(fs.existsSync(DESTRUCTIVE_GIT_GUARD_SCRIPT)).toBe(true);
898
- expect(fs.existsSync(INLINE_IMPLEMENTATION_GUARD_SCRIPT)).toBe(true);
899
- });
900
-
901
- test('installPrdWriteGuard: refuses when its guard script is missing, and leaves settings.json byte-identical', async () => {
902
- const { cwd } = await makeGreenFixtures();
903
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
904
- await fsp.rm(settingsPath);
905
-
906
- await withGuardScriptMissing(PRD_WRITE_GUARD_SCRIPT, async () => {
907
- const r = await installPrdWriteGuard({ cwd });
908
- expect(r.ok).toBe(false);
909
- expect(r.action).toBe('error');
910
- expect(r.error).toContain(PRD_WRITE_GUARD_SCRIPT);
911
- // Nothing was written — the file must still not exist.
912
- expect(fs.existsSync(settingsPath)).toBe(false);
913
- });
914
- });
915
-
916
- test('installPrdWriteGuard: refuses when its guard script is missing, leaving an EXISTING settings.json byte-identical', async () => {
917
- const { cwd } = await makeGreenFixtures();
918
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
919
- const before = fs.readFileSync(settingsPath);
920
-
921
- await withGuardScriptMissing(PRD_WRITE_GUARD_SCRIPT, async () => {
922
- const r = await installPrdWriteGuard({ cwd });
923
- expect(r.ok).toBe(false);
924
- expect(r.action).toBe('error');
925
- expect(fs.readFileSync(settingsPath).equals(before)).toBe(true);
926
- });
927
- });
928
-
929
- test('installDestructiveGitGuard: refuses when its guard script is missing, and leaves settings.json byte-identical', async () => {
930
- const { cwd } = await makeGreenFixtures();
931
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
932
- await fsp.rm(settingsPath);
933
-
934
- await withGuardScriptMissing(DESTRUCTIVE_GIT_GUARD_SCRIPT, async () => {
935
- const r = await installDestructiveGitGuard({ cwd });
936
- expect(r.ok).toBe(false);
937
- expect(r.action).toBe('error');
938
- expect(r.error).toContain(DESTRUCTIVE_GIT_GUARD_SCRIPT);
939
- expect(fs.existsSync(settingsPath)).toBe(false);
940
- });
941
- });
942
-
943
- test('installDestructiveGitGuard: refuses when its guard script is missing, leaving an EXISTING settings.json byte-identical', async () => {
944
- const { cwd } = await makeGreenFixtures();
945
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
946
- const before = fs.readFileSync(settingsPath);
947
-
948
- await withGuardScriptMissing(DESTRUCTIVE_GIT_GUARD_SCRIPT, async () => {
949
- const r = await installDestructiveGitGuard({ cwd });
950
- expect(r.ok).toBe(false);
951
- expect(r.action).toBe('error');
952
- expect(fs.readFileSync(settingsPath).equals(before)).toBe(true);
953
- });
954
- });
955
-
956
- test('installInlineImplementationGuard: refuses when its guard script is missing, and leaves settings.json byte-identical', async () => {
957
- const { cwd } = await makeGreenFixtures();
958
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
959
- await fsp.rm(settingsPath);
960
-
961
- await withGuardScriptMissing(INLINE_IMPLEMENTATION_GUARD_SCRIPT, async () => {
962
- const r = await installInlineImplementationGuard({ cwd });
963
- expect(r.ok).toBe(false);
964
- expect(r.action).toBe('error');
965
- expect(r.error).toContain(INLINE_IMPLEMENTATION_GUARD_SCRIPT);
966
- expect(fs.existsSync(settingsPath)).toBe(false);
967
- });
968
- });
969
-
970
- test('installInlineImplementationGuard: refuses when its guard script is missing, leaving an EXISTING settings.json byte-identical', async () => {
971
- const { cwd } = await makeGreenFixtures();
972
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
973
- const before = fs.readFileSync(settingsPath);
974
-
975
- await withGuardScriptMissing(INLINE_IMPLEMENTATION_GUARD_SCRIPT, async () => {
976
- const r = await installInlineImplementationGuard({ cwd });
977
- expect(r.ok).toBe(false);
978
- expect(r.action).toBe('error');
979
- expect(fs.readFileSync(settingsPath).equals(before)).toBe(true);
980
- });
981
- });
982
-
983
- test('installInlineImplementationGuard: uses the ABSOLUTE stable-shim path, never a vendored copy — and the shim itself resolves by REFERENCE, not a copy', async () => {
984
- const { homeDir, cwd } = await makeGreenFixtures();
985
- await writeJson(path.join(cwd, '.claude', 'settings.json'), {
986
- hooks: { PreToolUse: [{ matcher: 'Write|Edit|NotebookEdit', hooks: [{ type: 'command', command: `node ${PRD_WRITE_GUARD_SCRIPT}` }] }] },
987
- });
988
-
989
- const r = await installInlineImplementationGuard({ cwd, homeDir });
990
- const shimFile = guardShimPath('guard-inline-implementation.cjs', homeDir);
991
- expect(path.isAbsolute(shimFile)).toBe(true);
992
- expect(r.command).toBe(`node ${shimFile}`);
993
- expect(shimFile.startsWith(cwd + path.sep)).toBe(false);
994
- expect(fs.existsSync(path.join(cwd, 'scripts'))).toBe(false);
995
-
996
- // The shim is not a vendored copy of the real guard — it's a pointer-file
997
- // indirection that names the real script's absolute path, which still
998
- // lives only inside this repo.
999
- const pointer = JSON.parse(fs.readFileSync(guardPointerPath(homeDir), 'utf8'));
1000
- expect(pointer.appRoot).toBe(GUARD_APP_ROOT);
1001
- const shimSource = fs.readFileSync(shimFile, 'utf8');
1002
- expect(shimSource).toContain('guard-inline-implementation.cjs');
1003
- expect(shimSource).not.toContain(INLINE_IMPLEMENTATION_GUARD_SCRIPT);
1004
- });
1005
-
1006
- // ─────────────────────────────── ensureGuardsInstalled (self-heal — PRD: guards-auto-install)
1007
- //
1008
- // The "Fix It does nothing" incident: installPrdWriteGuard/installDestructiveGitGuard/
1009
- // installInlineImplementationGuard above were only ever reachable from a human
1010
- // pressing the New Session card's Fix It button, so every project started red
1011
- // forever. ensureGuardsInstalled is the self-heal entry point invoked from the
1012
- // app:delegation-readiness IPC handler BEFORE checkDelegationReadiness runs.
1013
-
1014
- /** Fabricates a linked git worktree pointing at `main`, without shelling out to git. */
1015
- async function makeLinkedWorktreeFixture(mk) {
1016
- const main = await mk('sm-ensure-guards-main-');
1017
- fs.mkdirSync(path.join(main, '.git'), { recursive: true });
1018
- const worktree = await mk('sm-ensure-guards-worktree-');
1019
- const worktreeName = 'sm-epic-testfixture';
1020
- const worktreeGitFile = path.join(worktree, '.git');
1021
- const adminDir = path.join(main, '.git', 'worktrees', worktreeName);
1022
- fs.mkdirSync(adminDir, { recursive: true });
1023
- // Round-trip back-reference real `git worktree add` writes — required by
1024
- // worktreeMainRootOf's verification (see opsRootAbsoluteCwd.test.cjs).
1025
- fs.writeFileSync(path.join(adminDir, 'gitdir'), `${worktreeGitFile}\n`, 'utf8');
1026
- fs.writeFileSync(worktreeGitFile, `gitdir: ${adminDir}\n`, 'utf8');
1027
- return { main, worktree };
1028
- }
1029
-
1030
- test('ensureGuardsInstalled: installs all four guards into a fresh project with no .claude/settings.json', async () => {
1031
- const cwd = await mkTmp('sm-ensure-guards-fresh-');
1032
- const homeDir = await mkTmp('sm-ensure-guards-fresh-home-');
1033
-
1034
- const result = await ensureGuardsInstalled(cwd, { homeDir });
1035
- expect(result.ok).toBe(true);
1036
- expect(result.root).toBe(cwd);
1037
- expect(result.guards['prd-write-guard'].action).toBe('installed');
1038
- expect(result.guards['destructive-git-guard'].action).toBe('installed');
1039
- expect(result.guards['inline-implementation-guard'].action).toBe('installed');
1040
- expect(result.guards['self-schedule-guard'].action).toBe('installed');
1041
-
1042
- const readiness = await checkDelegationReadiness({ cwd, homeDir });
1043
- expect(readiness.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
1044
- expect(readiness.checks.find((c) => c.id === 'destructive-git-guard').ok).toBe(true);
1045
- expect(readiness.checks.find((c) => c.id === 'inline-implementation-guard').ok).toBe(true);
1046
- expect(readiness.checks.find((c) => c.id === 'self-schedule-guard').ok).toBe(true);
1047
- }, 15_000);
1048
-
1049
- test('ensureGuardsInstalled: a second call against an already-healthy project performs no write (memoized per cwd)', async () => {
1050
- const cwd = await mkTmp('sm-ensure-guards-idempotent-');
1051
- const homeDir = await mkTmp('sm-ensure-guards-idempotent-home-');
1052
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
1053
-
1054
- const first = await ensureGuardsInstalled(cwd, { homeDir });
1055
- expect(first.ok).toBe(true);
1056
- const before = fs.statSync(settingsPath).mtimeMs;
1057
-
1058
- const second = await ensureGuardsInstalled(cwd, { homeDir });
1059
- expect(second).toBe(first); // memoized — same resolved outcome, no re-run
1060
- const after = fs.statSync(settingsPath).mtimeMs;
1061
- expect(after).toBe(before);
1062
- }, 15_000);
1063
-
1064
- test('ensureGuardsInstalled: malformed settings.json does not throw and leaves the guard row red with its manual fixAction intact', async () => {
1065
- const cwd = await mkTmp('sm-ensure-guards-malformed-');
1066
- const homeDir = await mkTmp('sm-ensure-guards-malformed-home-');
1067
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
1068
- await fsp.mkdir(path.dirname(settingsPath), { recursive: true });
1069
- await fsp.writeFile(settingsPath, '{ not valid json', 'utf8');
1070
-
1071
- const result = await ensureGuardsInstalled(cwd, { homeDir });
1072
- expect(result.ok).toBe(false);
1073
- expect(result.guards['prd-write-guard']).toMatchObject({ ok: false, action: 'error' });
1074
- // never silently discarded the human's unparseable file
1075
- expect(fs.readFileSync(settingsPath, 'utf8')).toBe('{ not valid json');
1076
-
1077
- const readiness = await checkDelegationReadiness({ cwd, homeDir });
1078
- const check = readiness.checks.find((c) => c.id === 'prd-write-guard');
1079
- expect(check.ok).toBe(false);
1080
- expect(check.fixAction).toBe('install-prd-write-guard');
1081
- }, 15_000);
1082
-
1083
- test('ensureGuardsInstalled: a failed attempt is NOT permanently cached — a later call retries once the underlying problem is fixed', async () => {
1084
- const cwd = await mkTmp('sm-ensure-guards-retry-');
1085
- const homeDir = await mkTmp('sm-ensure-guards-retry-home-');
1086
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
1087
- await fsp.mkdir(path.dirname(settingsPath), { recursive: true });
1088
- await fsp.writeFile(settingsPath, '{ not valid json', 'utf8');
1089
-
1090
- const first = await ensureGuardsInstalled(cwd, { homeDir });
1091
- expect(first.ok).toBe(false);
1092
-
1093
- // Fixed by hand, WITHOUT an app restart / cache clear.
1094
- await fsp.writeFile(settingsPath, '{}', 'utf8');
1095
-
1096
- const second = await ensureGuardsInstalled(cwd, { homeDir });
1097
- expect(second.ok).toBe(true);
1098
- expect(second.guards['prd-write-guard'].action).toBe('installed');
1099
- }, 15_000);
1100
-
1101
- test('ensureGuardsInstalled: a nonexistent cwd never throws, is reported ok:false, and never resurrects the deleted folder', async () => {
1102
- const homeDir = await mkTmp('sm-ensure-guards-missing-home-');
1103
- const missingCwd = path.join(os.tmpdir(), `sm-ensure-guards-does-not-exist-${Date.now()}`, 'nested', 'project');
1104
-
1105
- const result = await ensureGuardsInstalled(missingCwd, { homeDir });
1106
- expect(result.ok).toBe(false);
1107
- expect(result.error).toMatch(/does not exist on disk/);
1108
- // Never `mkdir -p`s a deleted project back into existence as a side effect.
1109
- expect(fs.existsSync(missingCwd)).toBe(false);
1110
- }, 15_000);
1111
-
1112
- test('ensureGuardsInstalled: preserves a pre-existing unrelated PreToolUse matcher and hook', async () => {
1113
- const cwd = await mkTmp('sm-ensure-guards-unrelated-');
1114
- const homeDir = await mkTmp('sm-ensure-guards-unrelated-home-');
1115
- const settingsPath = path.join(cwd, '.claude', 'settings.json');
1116
- const unrelatedMatcher = { matcher: 'SomeOtherTool', hooks: [{ type: 'command', command: 'node /some/unrelated-hook.cjs' }] };
1117
- await writeJson(settingsPath, { someUnrelatedTopLevelKey: 'keep-me', hooks: { PreToolUse: [unrelatedMatcher] } });
1118
-
1119
- const result = await ensureGuardsInstalled(cwd, { homeDir });
1120
- expect(result.ok).toBe(true);
1121
-
1122
- const written = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
1123
- expect(written.someUnrelatedTopLevelKey).toBe('keep-me');
1124
- expect(written.hooks.PreToolUse).toContainEqual(unrelatedMatcher);
1125
- }, 15_000);
1126
-
1127
- test('ensureGuardsInstalled: a worktree cwd installs into the MAIN tree root, never the ephemeral worktree', async () => {
1128
- const { main, worktree } = await makeLinkedWorktreeFixture(mkTmp);
1129
- const homeDir = await mkTmp('sm-ensure-guards-worktree-home-');
1130
-
1131
- const result = await ensureGuardsInstalled(worktree, { homeDir });
1132
- expect(result.ok).toBe(true);
1133
- expect(result.root).toBe(main);
1134
-
1135
- expect(fs.existsSync(path.join(main, '.claude', 'settings.json'))).toBe(true);
1136
- expect(fs.existsSync(path.join(worktree, '.claude', 'settings.json'))).toBe(false);
1137
-
1138
- const readiness = await checkDelegationReadiness({ cwd: main, homeDir });
1139
- expect(readiness.checks.find((c) => c.id === 'prd-write-guard').ok).toBe(true);
1140
- }, 15_000);
1141
-
1142
- test('ensureGuardsInstalled: records every auto-install attempt in the ops error log under scope "delegationReadiness"', async () => {
1143
- const cwd = await mkTmp('sm-ensure-guards-logged-');
1144
- const homeDir = await mkTmp('sm-ensure-guards-logged-home-');
1145
-
1146
- await ensureGuardsInstalled(cwd, { homeDir });
1147
-
1148
- const logFile = opsErrorLogTodayFile(cwd);
1149
- const lines = fs.readFileSync(logFile, 'utf8').trim().split('\n').map((l) => JSON.parse(l));
1150
- const delegationLines = lines.filter((l) => l.scope === 'delegationReadiness');
1151
- expect(delegationLines.map((l) => l.meta?.guard)).toEqual(
1152
- expect.arrayContaining(['prd-write-guard', 'destructive-git-guard', 'inline-implementation-guard', 'self-schedule-guard']),
1153
- );
1154
- expect(delegationLines.every((l) => l.level === 'info')).toBe(true);
1155
- expect(delegationLines.every((l) => l.meta?.action === 'installed')).toBe(true);
1156
- }, 15_000);
1157
-
1158
- test('ensureGuardsInstalled: an already-installed re-run writes no new ops error-log rows', async () => {
1159
- const cwd = await mkTmp('sm-ensure-guards-noop-');
1160
- const homeDir = await mkTmp('sm-ensure-guards-noop-home-');
1161
-
1162
- await ensureGuardsInstalled(cwd, { homeDir });
1163
- const logFile = opsErrorLogTodayFile(cwd);
1164
- const before = fs.readFileSync(logFile, 'utf8');
1165
-
1166
- clearGuardsInstalledCache();
1167
- const again = await ensureGuardsInstalled(cwd, { homeDir });
1168
- expect(Object.values(again.guards).every((g) => g.action === 'already-installed')).toBe(true);
1169
- expect(fs.readFileSync(logFile, 'utf8')).toBe(before);
1170
- }, 15_000);
1171
-
1172
- test('delegationReadiness.cjs source contains no raw NUL byte', () => {
1173
- const src = fs.readFileSync(path.join(__dirname, '..', 'delegationReadiness.cjs'));
1174
- expect(src.includes(0)).toBe(false);
1175
- });