claude-code-session-manager 0.87.0 → 0.88.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 (290) hide show
  1. package/README.md +26 -53
  2. package/dist/assets/{AgentLibrary-DyLWzZDf.js → AgentLibrary-BZ6IY2g1.js} +1 -1
  3. package/dist/assets/{DataModel--mISIJ6h.js → DataModel-dAoGAODX.js} +1 -1
  4. package/dist/assets/{History-C2ahUXTg.js → History-CF157HyX.js} +1 -1
  5. package/dist/assets/{Hooks-BiC6oyR2.js → Hooks-CCPPipBk.js} +1 -1
  6. package/dist/assets/{HostBilko-BPleEOld.js → HostBilko-Dlmz2m06.js} +1 -1
  7. package/dist/assets/{Library-Dc8Qst1R.js → Library-BaXcboWX.js} +1 -1
  8. package/dist/assets/{ListDetail-DIXh-OLX.js → ListDetail-CoUCzG5S.js} +1 -1
  9. package/dist/assets/{MarkdownEditor-C90bkLXK.js → MarkdownEditor-DTg3JlOT.js} +1 -1
  10. package/dist/assets/{McpServers-DqcbLOLZ.js → McpServers-DdjY1sA3.js} +1 -1
  11. package/dist/assets/{Memory-CW62MXlh.js → Memory-BJ3Jlw0C.js} +1 -1
  12. package/dist/assets/{Panel-Bw1FhRuF.js → Panel-ygRSgc41.js} +1 -1
  13. package/dist/assets/{Permissions-BcUC-5y8.js → Permissions-m0KAnccF.js} +1 -1
  14. package/dist/assets/{Plugins-BnKx9flD.js → Plugins-CJRl6B3Q.js} +2 -2
  15. package/dist/assets/{ProvenanceBadge-Bw5vNVPT.js → ProvenanceBadge-w8cnlVvW.js} +1 -1
  16. package/dist/assets/{SaveBar-CWr0O_w-.js → SaveBar-BpyPcUIk.js} +1 -1
  17. package/dist/assets/{Scheduler-DYdLuUqq.js → Scheduler-D2ppxSfy.js} +7 -7
  18. package/dist/assets/{ScopeSwitcher-CrBLbg8s.js → ScopeSwitcher-EyuIwt-j.js} +1 -1
  19. package/dist/assets/{Settings-DluB-vN1.js → Settings-BHSGGFEc.js} +1 -1
  20. package/dist/assets/{SkillReferenceGraph-CHLSseay.js → SkillReferenceGraph-BNaZ2JCF.js} +1 -1
  21. package/dist/assets/{Skills-gNdo_HNK.js → Skills-Dl3q75QV.js} +1 -1
  22. package/dist/assets/{SystemPrompt-Cru05-Ia.js → SystemPrompt-Bg6F-Cyp.js} +1 -1
  23. package/dist/assets/{TagLibrary-DNHY0xou.js → TagLibrary-BSutflCy.js} +1 -1
  24. package/dist/assets/{TiptapBody-I4lmbCgP.js → TiptapBody-CXih4xrc.js} +1 -1
  25. package/dist/assets/{Toggle-bWMHjmRh.js → Toggle-2qtUHhA9.js} +1 -1
  26. package/dist/assets/{index-fc_JjdxL.js → index-B3emy2oI.js} +356 -356
  27. package/dist/assets/{index-DV3PorRY.css → index-BHTX4OTc.css} +1 -1
  28. package/dist/assets/{settingsSchema-BfhtZnGD.js → settingsSchema-CdzxaqwM.js} +1 -1
  29. package/dist/assets/{whisperWorker-Dbia1OpC.js → whisperWorker-C7ZGQwKg.js} +7 -7
  30. package/dist/index.html +2 -2
  31. package/dist/vad/ort-wasm-simd-threaded.asyncify.mjs +106 -110
  32. package/dist/vad/ort-wasm-simd-threaded.asyncify.wasm +0 -0
  33. package/dist/vad/ort-wasm-simd-threaded.jsep.mjs +98 -98
  34. package/dist/vad/ort-wasm-simd-threaded.jsep.wasm +0 -0
  35. package/dist/vad/ort-wasm-simd-threaded.jspi.mjs +99 -102
  36. package/dist/vad/ort-wasm-simd-threaded.jspi.wasm +0 -0
  37. package/dist/vad/ort-wasm-simd-threaded.mjs +46 -46
  38. package/dist/vad/ort-wasm-simd-threaded.wasm +0 -0
  39. package/package.json +10 -13
  40. package/scripts/README.md +59 -0
  41. package/scripts/audit-ops-hygiene.cjs +350 -0
  42. package/scripts/hooks/guard-destructive-git.cjs +10 -34
  43. package/scripts/hooks/guard-inline-implementation.cjs +14 -8
  44. package/scripts/hooks/guard-prd-writes.cjs +7 -36
  45. package/scripts/hooks/guard-self-schedule.cjs +175 -0
  46. package/scripts/ops-sweep.cjs +355 -0
  47. package/scripts/scheduler-mcp-server.cjs +28 -71
  48. package/src/main/__tests__/bilkoHost-integration.test.cjs +3 -3
  49. package/src/main/__tests__/chat-cancel-terminal.test.cjs +6 -9
  50. package/src/main/__tests__/chat-exit-close-race.test.cjs +3 -3
  51. package/src/main/__tests__/chat-mcp-consent-notice.test.cjs +4 -5
  52. package/src/main/__tests__/chat-queue.test.cjs +2 -2
  53. package/src/main/__tests__/chat-stop-signal.test.cjs +2 -2
  54. package/src/main/__tests__/dep-orphan-archive-health.test.cjs +77 -0
  55. package/src/main/__tests__/dod-batchkey.test.cjs +2 -2
  56. package/src/main/__tests__/dod-drain-hook.test.cjs +2 -2
  57. package/src/main/__tests__/dod-report.test.cjs +2 -2
  58. package/src/main/__tests__/dod-reverify.test.cjs +2 -2
  59. package/src/main/__tests__/epicMint.test.cjs +2 -2
  60. package/src/main/__tests__/exchanges.test.cjs +2 -2
  61. package/src/main/__tests__/extractJson.test.cjs +2 -2
  62. package/src/main/__tests__/files-reject-credentials.test.cjs +1 -1
  63. package/src/main/__tests__/fixtures/1218-fo-01-move-scripts-lib-into-src-main-lib.log +556 -0
  64. package/src/main/__tests__/health-build-freshness.test.cjs +39 -0
  65. package/src/main/__tests__/health-delegation-chain.test.cjs +15 -1
  66. package/src/main/__tests__/health-queue-dispatch.test.cjs +58 -7
  67. package/src/main/__tests__/health-tick-liveness.test.cjs +11 -3
  68. package/src/main/__tests__/health-usage-poller.test.cjs +70 -23
  69. package/src/main/__tests__/historyRollup.test.cjs +2 -2
  70. package/src/main/__tests__/kg-augment.test.cjs +2 -2
  71. package/src/main/__tests__/mcpStatus.test.cjs +2 -2
  72. package/src/main/__tests__/memoryAggregate.test.cjs +1 -1
  73. package/src/main/__tests__/memoryStale.test.cjs +1 -1
  74. package/src/main/__tests__/opsErrorLogTelemetryTap.test.cjs +25 -1
  75. package/src/main/__tests__/pollLoop-dispatch-on-failure.test.cjs +33 -3
  76. package/src/main/__tests__/prd-group-allocator.test.cjs +2 -2
  77. package/src/main/__tests__/prdAdminRouteParity.test.cjs +2 -0
  78. package/src/main/__tests__/prdAdminRoutes.test.cjs +14 -2
  79. package/src/main/__tests__/prdAuthoringSeed.test.cjs +39 -0
  80. package/src/main/__tests__/prdLocationsArchived.test.cjs +20 -13
  81. package/src/main/__tests__/proc-role-env.test.cjs +125 -0
  82. package/src/main/__tests__/procname-claude-spawn-sites.test.cjs +304 -0
  83. package/src/main/__tests__/procname-sm-processes.test.cjs +127 -0
  84. package/src/main/__tests__/projectHomeAdminRoutes.test.cjs +81 -401
  85. package/src/main/__tests__/projectPages.test.cjs +63 -149
  86. package/src/main/__tests__/queue-health-verdict.test.cjs +9 -9
  87. package/src/main/__tests__/queue-starvation-dispatch-driver.test.cjs +117 -20
  88. package/src/main/__tests__/queueHistory.test.cjs +2 -2
  89. package/src/main/__tests__/rateLimitPollerStreak.test.cjs +38 -3
  90. package/src/main/__tests__/runVerify-landed-commit-outranks.test.cjs +181 -0
  91. package/src/main/__tests__/runVerify.test.cjs +5 -5
  92. package/src/main/__tests__/scheduleJobStatusDrift.test.cjs +3 -3
  93. package/src/main/__tests__/scheduleJobTransitions.test.cjs +2 -2
  94. package/src/main/__tests__/scheduler-adopted-run-supervision.test.cjs +143 -0
  95. package/src/main/__tests__/scheduler-autofix-select.test.cjs +2 -2
  96. package/src/main/__tests__/scheduler-autopromote.test.cjs +2 -2
  97. package/src/main/__tests__/scheduler-bash-timeout-env.test.cjs +3 -5
  98. package/src/main/__tests__/scheduler-boot-orphans.test.cjs +78 -97
  99. package/src/main/__tests__/scheduler-default-eligible-heal.test.cjs +161 -0
  100. package/src/main/__tests__/scheduler-dispatch-loop.test.cjs +58 -0
  101. package/src/main/__tests__/scheduler-epic-digest.test.cjs +3 -5
  102. package/src/main/__tests__/scheduler-force-tick-outcome.test.cjs +2 -2
  103. package/src/main/__tests__/scheduler-gate-shadow.test.cjs +119 -0
  104. package/src/main/__tests__/scheduler-guard-verdict-autoresolve.test.cjs +46 -0
  105. package/src/main/__tests__/scheduler-heartbeat-payload.test.cjs +80 -0
  106. package/src/main/__tests__/scheduler-inplace-salvage.test.cjs +25 -18
  107. package/src/main/__tests__/scheduler-investigation-prompt.test.cjs +4 -4
  108. package/src/main/__tests__/scheduler-launch-failure.test.cjs +3 -5
  109. package/src/main/__tests__/scheduler-looks-done.test.cjs +26 -7
  110. package/src/main/__tests__/scheduler-manual-pause.test.cjs +118 -0
  111. package/src/main/__tests__/scheduler-meta-code-sha.test.cjs +26 -3
  112. package/src/main/__tests__/scheduler-prd-missing-skip.test.cjs +17 -2
  113. package/src/main/__tests__/scheduler-prd-persona-spawn.test.cjs +3 -5
  114. package/src/main/__tests__/scheduler-quiet-machine-lease.test.cjs +41 -6
  115. package/src/main/__tests__/scheduler-rate-limit-pause.test.cjs +62 -6
  116. package/src/main/__tests__/scheduler-rate-limit-spin-guard.test.cjs +3 -5
  117. package/src/main/__tests__/scheduler-reap-dead-running-jobs.test.cjs +23 -4
  118. package/src/main/__tests__/scheduler-reconcile-cwd-preserve.test.cjs +100 -0
  119. package/src/main/__tests__/scheduler-reconcile-invalid-repair.test.cjs +3 -3
  120. package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +4 -4
  121. package/src/main/__tests__/scheduler-shard-quarantine.test.cjs +110 -0
  122. package/src/main/__tests__/scheduler-shared-tree-guard.test.cjs +81 -1
  123. package/src/main/__tests__/scheduler-starve-escalation.test.cjs +4 -4
  124. package/src/main/__tests__/scheduler-stranded-autofix-park.test.cjs +245 -0
  125. package/src/main/__tests__/scheduler-supervisor-record.test.cjs +81 -0
  126. package/src/main/__tests__/scheduler-tick-cancel-token.test.cjs +2 -2
  127. package/src/main/__tests__/scheduler-tick-wedge.test.cjs +172 -0
  128. package/src/main/__tests__/scheduler-transient-failure.test.cjs +2 -2
  129. package/src/main/__tests__/scheduler-worktree-cap-defer.test.cjs +37 -11
  130. package/src/main/__tests__/scheduler-worktree-exec-cwd.test.cjs +3 -5
  131. package/src/main/__tests__/usageSingleFlight.test.cjs +157 -0
  132. package/src/main/__tests__/workTypeLibrary.test.cjs +1 -1
  133. package/src/main/bilkoHost.cjs +16 -7
  134. package/src/main/build-info.json +8 -0
  135. package/src/main/chatRunner.cjs +4 -2
  136. package/src/main/config.cjs +2 -3
  137. package/src/main/docEdit.cjs +4 -2
  138. package/src/main/health.cjs +267 -51
  139. package/src/main/heapSnapshot.cjs +2 -2
  140. package/src/main/historyAggregator.cjs +1 -1
  141. package/src/main/index.cjs +61 -10
  142. package/src/main/ipcSchemas.cjs +6 -17
  143. package/src/main/lib/__tests__/auditLog.test.cjs +38 -0
  144. package/src/main/lib/__tests__/buildIdentity.test.cjs +121 -0
  145. package/src/main/lib/__tests__/cwdClassify.test.cjs +111 -0
  146. package/src/main/lib/__tests__/definitionOfDoneSequence.test.cjs +95 -0
  147. package/src/main/lib/__tests__/delegationReadiness.test.cjs +1 -1
  148. package/src/main/lib/__tests__/dispatchLoop.test.cjs +63 -0
  149. package/src/main/lib/__tests__/gateFixtures.json +20 -0
  150. package/src/main/lib/__tests__/gitWorktree.test.cjs +8 -1
  151. package/src/main/lib/__tests__/instanceLock.test.cjs +93 -7
  152. package/src/main/lib/__tests__/jobSupervisorRecord.test.cjs +78 -0
  153. package/src/main/lib/__tests__/jobWorktreeBootLive.test.cjs +11 -0
  154. package/src/main/lib/__tests__/localAdminHttp.test.cjs +1 -1
  155. package/src/main/lib/__tests__/mcpToolCatalog.test.cjs +6 -1
  156. package/src/main/lib/__tests__/procIdentity.test.cjs +119 -0
  157. package/src/main/lib/__tests__/procName.test.cjs +92 -0
  158. package/src/main/lib/__tests__/queueStoreMachineStateRecovery.test.cjs +67 -0
  159. package/src/main/lib/__tests__/schedulerMcpServerHelp.test.cjs +6 -7
  160. package/src/main/lib/__tests__/schedulerMcpServerProjectHome.test.cjs +37 -204
  161. package/src/main/lib/__tests__/schedulerPaths.test.cjs +226 -0
  162. package/src/main/lib/__tests__/schedulerPathsWorktree.test.cjs +94 -0
  163. package/src/main/lib/__tests__/schedulerRuntimeState.test.cjs +56 -0
  164. package/src/main/lib/__tests__/sessionSlots.test.cjs +45 -0
  165. package/src/main/lib/__tests__/telemetryBacklog.test.cjs +1 -1
  166. package/src/main/lib/__tests__/upgradeDrain.test.cjs +130 -0
  167. package/src/main/lib/__tests__/usageCircuit.test.cjs +61 -0
  168. package/src/main/lib/__tests__/watchdog-helpers.test.cjs +63 -0
  169. package/src/main/lib/__tests__/watchdog-relaunch.test.cjs +73 -0
  170. package/src/main/lib/activeIndexRebuild.cjs +1 -3
  171. package/src/main/lib/activeSessions.cjs +20 -88
  172. package/src/main/lib/adoptedRunSupervisor.cjs +136 -0
  173. package/src/main/lib/agentModelResolve.cjs +33 -1
  174. package/src/main/lib/agentPersonaSchema.cjs +2 -2
  175. package/src/main/lib/auditLog.cjs +30 -5
  176. package/src/main/lib/buildIdentity.cjs +113 -0
  177. package/src/main/lib/classifyPromptTicket.cjs +3 -2
  178. package/src/main/lib/claudeBin.cjs +37 -2
  179. package/src/main/lib/cleanEnv.cjs +27 -1
  180. package/src/main/lib/credentials.cjs +4 -2
  181. package/src/main/lib/cwdClassify.cjs +185 -0
  182. package/src/main/lib/definitionOfDone.cjs +296 -52
  183. package/src/main/lib/dispatchLoop.cjs +40 -0
  184. package/src/main/lib/effectiveModelInfo.cjs +9 -10
  185. package/src/main/lib/ephemeralCwd.cjs +7 -28
  186. package/src/main/lib/gitWorktree.cjs +95 -8
  187. package/src/main/lib/guardShims.cjs +3 -3
  188. package/src/main/lib/historyRollup.cjs +6 -7
  189. package/src/main/lib/instanceLock.cjs +32 -5
  190. package/src/main/lib/jobSupervisorRecord.cjs +147 -0
  191. package/src/main/lib/jobWorktreeBootLive.cjs +9 -5
  192. package/src/main/lib/localAdminHttp.cjs +9 -27
  193. package/src/main/lib/mcpToolCatalog.cjs +29 -77
  194. package/src/main/lib/opsOwnership.cjs +27 -19
  195. package/src/main/lib/prdAuthoringSeed.cjs +36 -0
  196. package/src/main/lib/prdLocations.cjs +48 -1
  197. package/src/main/lib/procIdentity.cjs +126 -0
  198. package/src/main/lib/procName.cjs +98 -0
  199. package/src/main/lib/projectHomeAdminRoutes.cjs +56 -327
  200. package/src/main/lib/queueHistory.cjs +8 -7
  201. package/src/main/lib/queueStore.cjs +57 -37
  202. package/src/main/lib/quietMachineLease.cjs +19 -2
  203. package/src/main/lib/reservationExpiry.cjs +30 -0
  204. package/src/main/lib/runClaudeP.cjs +4 -2
  205. package/src/main/lib/runLogRetention.cjs +3 -2
  206. package/src/main/lib/scheduleJobSchema.cjs +2 -2
  207. package/src/main/lib/scheduleJobTransitions.cjs +29 -2
  208. package/src/main/lib/schedulerBatch.cjs +27 -2
  209. package/src/main/lib/schedulerPaths.cjs +175 -0
  210. package/src/main/lib/schedulerRuntimeState.cjs +59 -0
  211. package/src/main/lib/sessionSlots.cjs +47 -9
  212. package/src/main/lib/smProcNames.cjs +51 -0
  213. package/src/main/lib/upgradeDrain.cjs +188 -0
  214. package/src/main/lib/usageCircuit.cjs +53 -6
  215. package/src/main/lib/watchdogHelpers.cjs +70 -37
  216. package/src/main/lib/withTimeout.cjs +33 -0
  217. package/src/main/mcpStatus.cjs +4 -2
  218. package/src/main/pluginInstall.cjs +6 -2
  219. package/src/main/projectPages.cjs +41 -145
  220. package/src/main/pty.cjs +8 -1
  221. package/src/main/queueOps.cjs +10 -10
  222. package/src/main/runVerify.cjs +69 -3
  223. package/src/main/scheduler.cjs +1598 -381
  224. package/src/main/seedAgentPersonas.cjs +1 -1
  225. package/src/main/seedDevPlugin.cjs +1 -1
  226. package/src/main/seedSchedulerMcp.cjs +7 -6
  227. package/src/main/seedStatus.cjs +1 -1
  228. package/src/main/supervisor.cjs +5 -3
  229. package/src/main/usage.cjs +126 -62
  230. package/src/preload/api.d.ts +18 -64
  231. package/src/preload/index.cjs +2 -4
  232. package/src/seed/agents/project-home-builder.md +31 -48
  233. package/screenshots/.gitkeep +0 -0
  234. package/screenshots/README-screenshots.md +0 -13
  235. package/src/main/lib/projectPageSummarySchema.cjs +0 -181
  236. package/src/main/teams.cjs +0 -95
  237. package/src/main/templates/project-pages-catalog.json +0 -741
  238. package/src/main/templates/project-pages-default-home.html +0 -123
  239. package/src/main/templates/project-pages-pipeline.md +0 -417
  240. package/src/seed/prompts/code-review/ac-coverage-check.md +0 -8
  241. package/src/seed/prompts/code-review/correctness-only.md +0 -8
  242. package/src/seed/prompts/code-review/full-spectrum-high.md +0 -8
  243. package/src/seed/prompts/code-review/hallucination-check.md +0 -8
  244. package/src/seed/prompts/code-review/public-api-compat.md +0 -8
  245. package/src/seed/prompts/code-review/readability-naming.md +0 -8
  246. package/src/seed/prompts/debugging/bug-as-failing-test.md +0 -8
  247. package/src/seed/prompts/debugging/git-bisect-regression.md +0 -8
  248. package/src/seed/prompts/debugging/instrument-intermittent-bug.md +0 -8
  249. package/src/seed/prompts/debugging/localize-pipeline-failure.md +0 -8
  250. package/src/seed/prompts/debugging/reproduce-then-diagnose.md +0 -8
  251. package/src/seed/prompts/documentation/adr-from-change.md +0 -8
  252. package/src/seed/prompts/documentation/module-readme.md +0 -8
  253. package/src/seed/prompts/documentation/onboarding-plan.md +0 -8
  254. package/src/seed/prompts/documentation/refresh-claude-md.md +0 -8
  255. package/src/seed/prompts/documentation/tsdoc-public-exports.md +0 -8
  256. package/src/seed/prompts/git-pr/conventional-commit.md +0 -8
  257. package/src/seed/prompts/git-pr/draft-pr-title-body.md +0 -8
  258. package/src/seed/prompts/git-pr/pre-commit-safety-sweep.md +0 -8
  259. package/src/seed/prompts/git-pr/release-notes-block.md +0 -8
  260. package/src/seed/prompts/git-pr/split-large-pr.md +0 -8
  261. package/src/seed/prompts/performance/bundle-startup-audit.md +0 -8
  262. package/src/seed/prompts/performance/complexity-audit.md +0 -8
  263. package/src/seed/prompts/performance/cpu-profile-hot-path.md +0 -8
  264. package/src/seed/prompts/performance/db-query-plan-review.md +0 -8
  265. package/src/seed/prompts/performance/memory-leak-hunt.md +0 -8
  266. package/src/seed/prompts/qa/api-contract-tests.md +0 -8
  267. package/src/seed/prompts/qa/e2e-critical-path.md +0 -8
  268. package/src/seed/prompts/qa/failing-test-for-bug.md +0 -8
  269. package/src/seed/prompts/qa/find-missing-test-coverage.md +0 -8
  270. package/src/seed/prompts/qa/stabilize-flaky-test.md +0 -8
  271. package/src/seed/prompts/qa/tdd-red-first.md +0 -8
  272. package/src/seed/prompts/qa/visual-regression-review.md +0 -8
  273. package/src/seed/prompts/qa/wcag-axe-scan.md +0 -8
  274. package/src/seed/prompts/refactoring/dead-code-sweep.md +0 -8
  275. package/src/seed/prompts/refactoring/extract-duplicated-pattern.md +0 -8
  276. package/src/seed/prompts/refactoring/modernize-legacy-file.md +0 -8
  277. package/src/seed/prompts/refactoring/reduce-cyclomatic-complexity.md +0 -8
  278. package/src/seed/prompts/refactoring/tighten-module-boundaries.md +0 -8
  279. package/src/seed/prompts/security/authz-audit.md +0 -8
  280. package/src/seed/prompts/security/crypto-correctness.md +0 -8
  281. package/src/seed/prompts/security/cwe-top-25-hunt.md +0 -8
  282. package/src/seed/prompts/security/dependency-audit.md +0 -8
  283. package/src/seed/prompts/security/ipc-boundary-hardening.md +0 -8
  284. package/src/seed/prompts/security/owasp-top-10-staged-diff.md +0 -8
  285. package/src/seed/prompts/security/secret-credential-scan.md +0 -8
  286. package/web/README.md +0 -41
  287. package/web/project-pages/logic/dist/logic.cjs +0 -4709
  288. package/web/project-pages/render.cjs +0 -70
  289. package/web/project-pages/renderer/dist/renderer.cjs +0 -18900
  290. package/web/project-pages/validate-summary.cjs +0 -62
@@ -159,21 +159,28 @@ test('resolveArchivedPrdsDirs: a prds-archived/ dir created inside an ALREADY-EX
159
159
  // so the mtime-keyed freshness key alone would never invalidate. The
160
160
  // short TTL backstop (same idiom as activeSessions.cjs's cwdScanCache)
161
161
  // bounds that blind spot instead of leaving it stale indefinitely.
162
- vi.useFakeTimers();
163
- try {
164
- const projectsDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sm-prdloc-blindspot-projects-'));
165
- tmpDirs.push(projectsDir);
166
- const projectCwd = await mkEpicProject();
167
- tmpDirs.push(projectCwd);
162
+ //
163
+ // Why this test is sensitive to the process environment: the code under test
164
+ // keys its cache on REAL directory mtimes and expires it via Date.now(); the
165
+ // fixtures are mkdtemp'd under os.tmpdir(), which a TMPDIR override moves.
166
+ // Installing fake timers BEFORE the async fs fixture setup let the fake timer
167
+ // queue interleave with real fs completions. Build every fixture on the real
168
+ // clock first, then fake ONLY Date — the sole clock the TTL reads.
169
+ const projectsDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sm-prdloc-blindspot-projects-'));
170
+ tmpDirs.push(projectsDir);
171
+ const projectCwd = await mkEpicProject();
172
+ tmpDirs.push(projectCwd);
168
173
 
169
- const epicId = `blindspot-epic-${process.pid}`;
170
- const epicPrdsDir = resolveEpicPrdWriteDir(projectCwd, epicId);
171
- fs.mkdirSync(epicPrdsDir, { recursive: true }); // Epic already exists, well before archiving.
174
+ const epicId = `blindspot-epic-${process.pid}`;
175
+ const epicPrdsDir = resolveEpicPrdWriteDir(projectCwd, epicId);
176
+ fs.mkdirSync(epicPrdsDir, { recursive: true }); // Epic already exists, well before archiving.
172
177
 
173
- const projDir = path.join(projectsDir, 'blindspot-project');
174
- fs.mkdirSync(projDir, { recursive: true });
175
- fs.writeFileSync(path.join(projDir, 'session1.jsonl'), `${JSON.stringify({ cwd: projectCwd })}\n`);
178
+ const projDir = path.join(projectsDir, 'blindspot-project');
179
+ fs.mkdirSync(projDir, { recursive: true });
180
+ fs.writeFileSync(path.join(projDir, 'session1.jsonl'), `${JSON.stringify({ cwd: projectCwd })}\n`);
176
181
 
182
+ vi.useFakeTimers({ toFake: ['Date'] });
183
+ try {
177
184
  // Prime the cache — no prds-archived/ dir exists yet.
178
185
  const before = resolveArchivedPrdsDirs(90, { projectsDir });
179
186
  const epicArchiveDir = path.join(epicPrdsDir, '..', 'prds-archived');
@@ -185,7 +192,7 @@ test('resolveArchivedPrdsDirs: a prds-archived/ dir created inside an ALREADY-EX
185
192
  fs.mkdirSync(epicArchiveDir, { recursive: true });
186
193
 
187
194
  // Bounded staleness is acceptable — but it must actually be bounded.
188
- vi.advanceTimersByTime(31_000);
195
+ vi.advanceTimersByTime(121_000); // TTL is 120 s — above the 60 s dispatch-loop interval
189
196
  const after = resolveArchivedPrdsDirs(90, { projectsDir });
190
197
  expect(after.map((d) => path.resolve(d))).toContain(path.resolve(epicArchiveDir));
191
198
  } finally {
@@ -0,0 +1,125 @@
1
+ /**
2
+ * proc-role-env.test.cjs — SM_PROC_ROLE attribution env + scripts/sm-ps.cjs.
3
+ *
4
+ * Run: timeout 120 npx vitest run src/main/__tests__/proc-role-env.test.cjs
5
+ */
6
+ 'use strict';
7
+
8
+ import { test, expect, describe, beforeEach, afterEach } from 'vitest';
9
+
10
+ const fs = require('node:fs');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+ const { spawn, spawnSync } = require('node:child_process');
14
+
15
+ const { cleanChildEnv, withProcRole, inferProcRole } = require('../lib/cleanEnv.cjs');
16
+ const { runClaudeP } = require('../lib/runClaudeP.cjs');
17
+ const { runDocEdit } = require('../docEdit.cjs');
18
+
19
+ const SM_PS = path.join(__dirname, '..', '..', '..', 'scripts', 'sm-ps.cjs');
20
+
21
+ let tmp;
22
+ let savedBin;
23
+ beforeEach(() => {
24
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-proc-role-'));
25
+ savedBin = process.env.SM_CLAUDE_BIN;
26
+ });
27
+ afterEach(() => {
28
+ if (savedBin === undefined) delete process.env.SM_CLAUDE_BIN; else process.env.SM_CLAUDE_BIN = savedBin;
29
+ fs.rmSync(tmp, { recursive: true, force: true });
30
+ });
31
+
32
+ /** Stub `claude` that prints {"after":"<SM_PROC_ROLE>"} — valid for both runClaudeP and docEdit. */
33
+ function writeStub() {
34
+ const bin = path.join(tmp, 'claude-stub.sh');
35
+ fs.writeFileSync(bin, '#!/bin/sh\nprintf \'{"after":"%s"}\' "$SM_PROC_ROLE"\n', { mode: 0o755 });
36
+ return bin;
37
+ }
38
+
39
+ describe('cleanChildEnv role stamping', () => {
40
+ test('explicit role wins; inference from existing attribution vars; default aux', () => {
41
+ expect(cleanChildEnv({ SM_PROC_ROLE: 'shell' }).SM_PROC_ROLE).toBe('shell');
42
+ expect(inferProcRole({ SM_SCHEDULER_JOB_SLUG: 's' })).toBe('job');
43
+ expect(inferProcRole({ SM_CHAT_SESSION_ID: 'c' })).toBe('chat');
44
+ expect(inferProcRole({ SM_CHAT_SESSION_ID: 'c', SESSION_MANAGER_TAB_ID: 'c' })).toBe('shell');
45
+ expect(cleanChildEnv().SM_PROC_ROLE).toBe('aux');
46
+ });
47
+
48
+ test('is additive: existing attribution vars survive and SM_PROC_ROOT is untouched', () => {
49
+ const env = cleanChildEnv({ SM_SCHEDULER_JOB_SLUG: 'slug-1', SM_CHAT_SESSION_ID: 'chat-1', SM_PROJECT_ROOT: '/p' });
50
+ expect(env).toMatchObject({ SM_PROC_ROLE: 'job', SM_SCHEDULER_JOB_SLUG: 'slug-1', SM_CHAT_SESSION_ID: 'chat-1', SM_PROJECT_ROOT: '/p' });
51
+ expect('SM_PROC_ROOT' in env).toBe(process.env.SM_PROC_ROOT !== undefined);
52
+ });
53
+
54
+ test('withProcRole returns a copy and does not mutate its input', () => {
55
+ const base = { A: '1' };
56
+ expect(withProcRole(base, 'aux')).toEqual({ A: '1', SM_PROC_ROLE: 'aux' });
57
+ expect(base).toEqual({ A: '1' });
58
+ });
59
+ });
60
+
61
+ describe('real spawn paths carry SM_PROC_ROLE', () => {
62
+ test('runClaudeP (bypasses cleanChildEnv)', async () => {
63
+ process.env.SM_CLAUDE_BIN = writeStub();
64
+ const r = await runClaudeP('hi');
65
+ expect(r.ok).toBe(true);
66
+ expect(JSON.parse(r.out).after).toBe('aux');
67
+ });
68
+
69
+ test('docEdit runClaude (bypasses cleanChildEnv)', async () => {
70
+ process.env.SM_CLAUDE_BIN = writeStub();
71
+ const r = await runDocEdit({ path: path.join(os.homedir(), 'x.md'), before: 'a', instruction: 'b', documentText: '' });
72
+ expect(r).toEqual({ ok: true, after: 'aux' });
73
+ });
74
+
75
+ test('cleanChildEnv-built env reaches a spawned child', async () => {
76
+ const out = await new Promise((resolve) => {
77
+ const c = spawn('/bin/sh', ['-c', 'printf %s "$SM_PROC_ROLE"'], { env: cleanChildEnv({ SM_SCHEDULER_JOB_SLUG: 'x' }) });
78
+ let s = '';
79
+ c.stdout.on('data', (d) => { s += d; });
80
+ c.on('close', () => resolve(s));
81
+ });
82
+ expect(out).toBe('job');
83
+ });
84
+ });
85
+
86
+ describe('scripts/sm-ps.cjs', () => {
87
+ test('--json lists a tagged stub child (and its descendant) with role, slug, project root', async () => {
88
+ const env = cleanChildEnv({ SM_SCHEDULER_JOB_SLUG: 'fixture-slug', SM_PROJECT_ROOT: '/fixture/root' });
89
+ // outer sh forks an inner sleep, so we also assert descendants are included
90
+ const child = spawn('/bin/sh', ['-c', 'sleep 30 & wait'], { env, stdio: 'ignore' });
91
+ try {
92
+ await new Promise((r) => setTimeout(r, 300));
93
+ const res = spawnSync(process.execPath, [SM_PS, '--json'], { encoding: 'utf8', timeout: 20000 });
94
+ expect(res.status).toBe(0);
95
+ const { processes } = JSON.parse(res.stdout);
96
+ const hit = processes.find((p) => p.pid === child.pid);
97
+ expect(hit).toMatchObject({ role: 'job', slug: 'fixture-slug', projectRoot: '/fixture/root', attributed: true });
98
+ expect(processes.some((p) => p.ppid === child.pid)).toBe(true);
99
+ } finally {
100
+ try { process.kill(-child.pid); } catch { /* */ }
101
+ child.kill('SIGKILL');
102
+ }
103
+ });
104
+
105
+ test('exits 0 with an empty result set when nothing is running (empty proc root)', () => {
106
+ const root = path.join(tmp, 'proc');
107
+ fs.mkdirSync(root);
108
+ const res = spawnSync(process.execPath, [SM_PS, '--json', '--proc-root', root], { encoding: 'utf8' });
109
+ expect(res.status).toBe(0);
110
+ expect(JSON.parse(res.stdout)).toEqual({ processes: [] });
111
+ });
112
+
113
+ test('degrades without attribution on unreadable environ / mid-scan exit, never crashes', () => {
114
+ const root = path.join(tmp, 'proc');
115
+ fs.mkdirSync(path.join(root, '100'), { recursive: true }); // comm-named ours, environ absent
116
+ fs.writeFileSync(path.join(root, '100', 'stat'), '100 (sm-watchdog) S 1 0 0');
117
+ fs.writeFileSync(path.join(root, '100', 'cmdline'), 'node\0x.js\0');
118
+ fs.mkdirSync(path.join(root, '101')); // vanished: no stat at all
119
+ const res = spawnSync(process.execPath, [SM_PS, '--json', '--proc-root', root], { encoding: 'utf8' });
120
+ expect(res.status).toBe(0);
121
+ const { processes } = JSON.parse(res.stdout);
122
+ expect(processes).toHaveLength(1);
123
+ expect(processes[0]).toMatchObject({ pid: 100, comm: 'sm-watchdog', role: null, attributed: false });
124
+ });
125
+ });
@@ -0,0 +1,304 @@
1
+ /**
2
+ * procname-claude-spawn-sites.test.cjs — PRD pn-02: every `claude` spawn site
3
+ * execs a role alias (sm-claude-job/-chat/-aux) with a labelled argv0, WITHOUT
4
+ * breaking the four /\bclaude\b/ cmdline gates the reapers depend on.
5
+ *
6
+ * HOME is redirected BEFORE procName/claudeBin/scheduler load (ALIAS_ROOT is
7
+ * computed at require time) — never the real ~/.claude. Linux-only for the
8
+ * /proc readbacks; the stubs never touch process.cwd().
9
+ *
10
+ * Run: timeout 300 npx vitest run src/main/__tests__/procname-claude-spawn-sites.test.cjs
11
+ */
12
+ 'use strict';
13
+
14
+ import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
15
+ const fs = require('node:fs');
16
+ const os = require('node:os');
17
+ const path = require('node:path');
18
+ const { spawn } = require('node:child_process');
19
+
20
+ const HAS_PROC = process.platform === 'linux' && fs.existsSync('/proc/self/comm');
21
+
22
+ let tmpHome;
23
+ let realHome;
24
+ let realClaudeBin;
25
+ let procName;
26
+ let claudeBin;
27
+ let scheduler;
28
+ let reaper;
29
+ let cr;
30
+ let childWithLog;
31
+ let procIdentity;
32
+
33
+ beforeAll(() => {
34
+ realHome = process.env.HOME;
35
+ realClaudeBin = process.env.SM_CLAUDE_BIN;
36
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-pn02-'));
37
+ process.env.HOME = tmpHome;
38
+ for (const m of ['procName', 'claudeBin']) {
39
+ delete require.cache[require.resolve(`../lib/${m}.cjs`)];
40
+ }
41
+ procName = require('../lib/procName.cjs');
42
+ claudeBin = require('../lib/claudeBin.cjs');
43
+ scheduler = require('../scheduler.cjs');
44
+ reaper = require('../lib/reaperHelpers.cjs');
45
+ cr = require('../chatRunner.cjs');
46
+ childWithLog = require('../lib/childWithLog.cjs');
47
+ procIdentity = require('../lib/procIdentity.cjs');
48
+ });
49
+
50
+ afterAll(() => {
51
+ process.env.HOME = realHome;
52
+ if (realClaudeBin === undefined) delete process.env.SM_CLAUDE_BIN;
53
+ else process.env.SM_CLAUDE_BIN = realClaudeBin;
54
+ fs.rmSync(tmpHome, { recursive: true, force: true });
55
+ });
56
+
57
+ afterEach(() => {
58
+ delete process.env.SM_CLAUDE_BIN;
59
+ if (cr) { cr.__resetQueueForTests(); cr.attachWindow(null); }
60
+ });
61
+
62
+ // Stub `claude`: reports its OWN comm + cmdline (+ prompt) to `capturePath`,
63
+ // emits one stream-json result and exits 0. With `linger` it stays alive so a
64
+ // test can inspect it from outside.
65
+ function writeStub({ capturePath, linger = false } = {}) {
66
+ const stubPath = path.join(tmpHome, `stub-${Math.floor(Math.random() * 1e9)}.cjs`);
67
+ const body = `
68
+ const fs = require('fs');
69
+ ${capturePath ? `fs.writeFileSync(${JSON.stringify(capturePath)}, JSON.stringify({
70
+ comm: fs.readFileSync('/proc/self/comm', 'utf8').trim(),
71
+ cmdline: fs.readFileSync('/proc/self/cmdline', 'utf8').replace(/\\0/g, ' ').trim(),
72
+ }));` : ''}
73
+ process.stdout.write(JSON.stringify({ type: 'result', subtype: 'success', result: 'ok' }) + '\\n');
74
+ ${linger ? 'setTimeout(() => process.exit(0), 30000);' : 'process.exit(0);'}
75
+ `;
76
+ fs.writeFileSync(stubPath, `#!${process.execPath}\n${body}\n`, { mode: 0o755 });
77
+ return stubPath;
78
+ }
79
+
80
+ async function waitFor(fn, timeoutMs = 8000) {
81
+ const start = Date.now();
82
+ for (;;) {
83
+ const v = fn();
84
+ if (v) return v;
85
+ if (Date.now() - start > timeoutMs) throw new Error('waitFor timed out');
86
+ await new Promise((r) => setTimeout(r, 25));
87
+ }
88
+ }
89
+
90
+ function setupProject() {
91
+ const projectCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-pn02-project-'));
92
+ fs.mkdirSync(path.join(tmpHome, '.claude'), { recursive: true });
93
+ const runDir = fs.mkdtempSync(path.join(tmpHome, '.claude', 'pn02-run-'));
94
+ return { projectCwd, runDir };
95
+ }
96
+
97
+ function writePrd(projectCwd, slug) {
98
+ const dir = path.join(projectCwd, 'session-manager-operations', 'scheduler', 'prds');
99
+ fs.mkdirSync(dir, { recursive: true });
100
+ fs.writeFileSync(path.join(dir, `${slug}.md`), 'do the thing', 'utf8');
101
+ }
102
+
103
+ // Regexes replicated from the live gates; the reaperHelpers functions are ALSO
104
+ // exercised for real below.
105
+ const GATE = /\bclaude\b/;
106
+
107
+ describe('claudeSpawnTarget', () => {
108
+ it('skips aliasing entirely and returns the raw value when SM_CLAUDE_BIN is set', () => {
109
+ process.env.SM_CLAUDE_BIN = '/tmp/some stub/with spaces';
110
+ expect(claudeBin.claudeSpawnTarget('job', 'slug')).toEqual({ command: '/tmp/some stub/with spaces' });
111
+ });
112
+
113
+ it('aliases each role to its comm and labels argv0 (SM_CLAUDE_BIN unset)', () => {
114
+ const real = writeStub();
115
+ for (const [role, alias] of [['job', 'sm-claude-job'], ['chat', 'sm-claude-chat'], ['aux', 'sm-claude-aux']]) {
116
+ const t = claudeBin.claudeSpawnTarget(role, 'abc', real);
117
+ expect(path.basename(t.command)).toBe(alias);
118
+ expect(t.argv0).toBe(`sm-claude-${role}:abc`);
119
+ expect(fs.readlinkSync(t.command)).toBe(real);
120
+ }
121
+ });
122
+
123
+ it('every real alias name and argv0 label satisfies /\\bclaude\\b/ (round-trip)', () => {
124
+ for (const alias of ['sm-claude-job', 'sm-claude-chat', 'sm-claude-aux']) {
125
+ expect(GATE.test(alias)).toBe(true);
126
+ expect(GATE.test(path.join(procName.procnamesRoot(), alias))).toBe(true);
127
+ }
128
+ for (const role of ['job', 'chat', 'aux']) {
129
+ expect(GATE.test(procName.smArgv0(role, 'a-slug'))).toBe(true);
130
+ expect(GATE.test(procName.smArgv0(role, undefined))).toBe(true);
131
+ }
132
+ });
133
+
134
+ it('falls back to the unchanged bin with NO argv0 when aliasing fails open', () => {
135
+ expect(claudeBin.claudeSpawnTarget('job', 's', 'definitely-not-a-real-cmd-xyz')).toEqual({ command: 'definitely-not-a-real-cmd-xyz' });
136
+ });
137
+ });
138
+
139
+ describe.skipIf(!HAS_PROC)('real aliased processes vs the reaper gates', () => {
140
+ const kids = [];
141
+ afterAll(() => { for (const k of kids) { try { process.kill(-k.pid, 'SIGKILL'); } catch { /* gone */ } } });
142
+
143
+ function spawnAliased(role, detail, { detached = true } = {}) {
144
+ const real = writeStub({ linger: true });
145
+ const t = claudeBin.claudeSpawnTarget(role, detail, real);
146
+ const child = spawn(t.command, ['-p', `prompt mentioning ${detail}`], {
147
+ cwd: os.tmpdir(), stdio: 'ignore', detached, ...(t.argv0 ? { argv0: t.argv0 } : {}),
148
+ });
149
+ kids.push(child);
150
+ return child;
151
+ }
152
+
153
+ const comm = (pid) => { try { return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); } catch { return null; } };
154
+ const cmdline = (pid) => fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ');
155
+
156
+ it('kernel comm is the alias, cmdline carries the label + slug, and all four gates match', async () => {
157
+ const slug = `pn02-slug-${process.pid}-${Date.now()}`;
158
+ const child = spawnAliased('job', slug);
159
+ await waitFor(() => comm(child.pid) === 'sm-claude-job');
160
+ const cmd = cmdline(child.pid);
161
+ // A shebang stub's cmdline[0] is the interpreter and [1] the ALIAS PATH (the
162
+ // kernel rewrites argv for scripts, so argv0 is not visible); a native
163
+ // binary shows the label instead — see the ELF test below.
164
+ expect(cmd.includes(path.join(procName.procnamesRoot(), 'sm-claude-job'))).toBe(true);
165
+ expect(cmd.includes(slug)).toBe(true);
166
+ // scheduler.cjs killOrphanClaudePid + reaperHelpers.cjs:31 / :105 / :107 regexes
167
+ expect(GATE.test(cmd)).toBe(true);
168
+ expect(reaper.claudePidAlive(child.pid)).toBe(true);
169
+ expect(reaper.findLiveProcessForJob({ slug })).toBe(child.pid);
170
+ });
171
+
172
+ it('a native (ELF) binary shows the smArgv0 label as cmdline[0] and passes every gate', async () => {
173
+ const sleepBin = ['/bin/sleep', '/usr/bin/sleep'].find((p) => fs.existsSync(p));
174
+ if (!sleepBin) return;
175
+ const slug = `pn02-elf-${process.pid}-${Date.now()}`;
176
+ const t = claudeBin.claudeSpawnTarget('job', slug, sleepBin);
177
+ const child = spawn(t.command, ['30'], { cwd: os.tmpdir(), stdio: 'ignore', detached: true, argv0: t.argv0 });
178
+ kids.push(child);
179
+ await waitFor(() => comm(child.pid) === 'sm-claude-job');
180
+ const cmd = cmdline(child.pid);
181
+ expect(cmd.startsWith(`sm-claude-job:${slug}`)).toBe(true);
182
+ expect(GATE.test(cmd)).toBe(true);
183
+ expect(reaper.claudePidAlive(child.pid)).toBe(true);
184
+ expect(reaper.findLiveProcessForJob({ slug })).toBe(child.pid);
185
+ expect(scheduler.killOrphanClaudePid(child.pid)).toBe('killed');
186
+ });
187
+
188
+ it('findLiveProcessForJob still finds the job by slug when the argv0 label is absent (fail-open path)', async () => {
189
+ const slug = 'pn02-noargv0-slug';
190
+ const real = writeStub({ linger: true });
191
+ const child = spawn(real, ['-p', `claude prompt ${slug}`], { cwd: os.tmpdir(), stdio: 'ignore', detached: true });
192
+ kids.push(child);
193
+ await waitFor(() => { try { return cmdline(child.pid).includes(slug); } catch { return false; } });
194
+ expect(reaper.findLiveProcessForJob({ slug })).toBe(child.pid);
195
+ });
196
+
197
+ it('killOrphanClaudePid kills an aliased process group', async () => {
198
+ const child = spawnAliased('job', 'pn02-kill');
199
+ await waitFor(() => comm(child.pid) === 'sm-claude-job');
200
+ expect(scheduler.killOrphanClaudePid(child.pid)).toBe('killed');
201
+ await waitFor(() => child.exitCode !== null || child.signalCode !== null);
202
+ });
203
+
204
+ it('pid-recycling migration: identity recorded pre-alias OR post-alias for the same pid never vetoes its own kill', async () => {
205
+ // Legacy (unaliased) process, identity recorded "before", kill compared "after".
206
+ const legacyReal = writeStub({ linger: true });
207
+ const legacy = spawn(legacyReal, ['-p', 'claude legacy'], { cwd: os.tmpdir(), stdio: 'ignore', detached: true });
208
+ kids.push(legacy);
209
+ await waitFor(() => { try { return cmdline(legacy.pid).includes('legacy'); } catch { return false; } });
210
+ const recordedLegacy = procIdentity.identity(legacy.pid);
211
+ expect(recordedLegacy.complete).toBe(true);
212
+ expect(scheduler.killOrphanClaudePid(legacy.pid, recordedLegacy)).toBe('killed');
213
+
214
+ const aliased = spawnAliased('job', 'pn02-mig');
215
+ await waitFor(() => comm(aliased.pid) === 'sm-claude-job');
216
+ const recorded = procIdentity.identity(aliased.pid);
217
+ expect(procIdentity.isDifferentProcess(recorded, procIdentity.identity(aliased.pid))).toBe(false);
218
+ expect(scheduler.killOrphanClaudePid(aliased.pid, recorded)).toBe('killed');
219
+ // A genuinely recycled pid (different cmdline/starttime) is still vetoed.
220
+ expect(procIdentity.isDifferentProcess({ ...recorded, cmdline: '/usr/bin/claude -p old' }, { ...recorded, cmdline: 'sm-claude-job:new' })).toBe(true);
221
+ });
222
+
223
+ it('process-group semantics unchanged: detached child leads its own group; killTree/cancel reaps it', async () => {
224
+ const real = writeStub({ linger: true });
225
+ const t = claudeBin.claudeSpawnTarget('job', 'pn02-pgid', real);
226
+ const fd = fs.openSync(path.join(tmpHome, 'pgid.log'), 'a');
227
+ let exit = null;
228
+ const { child } = childWithLog.withChildAndLog({
229
+ fd, logPath: path.join(tmpHome, 'pgid.log'), safeLog() {}, closeFd() { try { fs.closeSync(fd); } catch { /* */ } },
230
+ spawn: { command: t.command, args: ['-p', 'claude x'], options: { cwd: os.tmpdir(), detached: true, ...(t.argv0 ? { argv0: t.argv0 } : {}) } },
231
+ onExit(info) { exit = info; },
232
+ });
233
+ await waitFor(() => comm(child.pid) === 'sm-claude-job');
234
+ const stat = fs.readFileSync(`/proc/${child.pid}/stat`, 'utf8');
235
+ const pgrp = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[2]);
236
+ expect(pgrp).toBe(child.pid);
237
+ process.kill(-child.pid, 'SIGTERM');
238
+ await waitFor(() => exit);
239
+ expect(exit.signal).toBe('SIGTERM');
240
+ expect(exit.leakedDescendants).toEqual([]);
241
+ });
242
+ });
243
+
244
+ describe.skipIf(!HAS_PROC)('comm assertions through the real runners', () => {
245
+ it('executeJob: the spawned claude has comm sm-claude-job', async () => {
246
+ const { projectCwd, runDir } = setupProject();
247
+ try {
248
+ const slug = `pn02-comm-${process.pid}-${Math.floor(Math.random() * 1e6)}`;
249
+ writePrd(projectCwd, slug);
250
+ const capturePath = path.join(runDir, 'cap.json');
251
+ const stub = writeStub({ capturePath });
252
+ // SM_CLAUDE_BIN skips aliasing by design; the test aliases explicitly.
253
+ process.env.SM_CLAUDE_BIN = procName.aliasBinFor(stub, 'sm-claude-job');
254
+ expect(path.basename(process.env.SM_CLAUDE_BIN)).toBe('sm-claude-job');
255
+ const result = await scheduler.executeJob({ slug, cwd: projectCwd }, runDir, projectCwd, () => Promise.resolve());
256
+ expect(result.exitCode).toBe(0);
257
+ expect(JSON.parse(fs.readFileSync(capturePath, 'utf8')).comm).toBe('sm-claude-job');
258
+ } finally {
259
+ fs.rmSync(projectCwd, { recursive: true, force: true });
260
+ fs.rmSync(runDir, { recursive: true, force: true });
261
+ }
262
+ });
263
+
264
+ it('chatRunner: the spawned claude has comm sm-claude-chat', async () => {
265
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-pn02-chat-'));
266
+ try {
267
+ const capturePath = path.join(tmpHome, 'chat-cap.json');
268
+ const stub = writeStub({ capturePath });
269
+ process.env.SM_CLAUDE_BIN = procName.aliasBinFor(stub, 'sm-claude-chat');
270
+ cr.run({ tabId: 'pn02-tab', sessionId: `pn02-sess-${process.pid}`, prompt: 'hello', cwd, resume: false });
271
+ await waitFor(() => fs.existsSync(capturePath));
272
+ expect(JSON.parse(fs.readFileSync(capturePath, 'utf8')).comm).toBe('sm-claude-chat');
273
+ } finally {
274
+ fs.rmSync(cwd, { recursive: true, force: true });
275
+ }
276
+ });
277
+
278
+ it('fail-open: an unusable ALIAS_ROOT still lets the job run to completion', async () => {
279
+ const { projectCwd, runDir } = setupProject();
280
+ fs.rmSync(procName.procnamesRoot(), { recursive: true, force: true });
281
+ fs.mkdirSync(path.dirname(procName.procnamesRoot()), { recursive: true });
282
+ fs.writeFileSync(procName.procnamesRoot(), 'not a directory'); // mkdir/symlink under it must fail
283
+ try {
284
+ const slug = `pn02-failopen-${process.pid}`;
285
+ writePrd(projectCwd, slug);
286
+ const capturePath = path.join(runDir, 'cap.json');
287
+ const stub = writeStub({ capturePath });
288
+ const aliased = procName.aliasBinFor(stub, 'sm-claude-job');
289
+ expect(aliased).toBe(stub); // failed open
290
+ process.env.SM_CLAUDE_BIN = aliased;
291
+ const result = await scheduler.executeJob({ slug, cwd: projectCwd }, runDir, projectCwd, () => Promise.resolve());
292
+ expect(result.exitCode).toBe(0);
293
+ // Unaliased: comm is the stub's own basename, not an sm-claude-* name.
294
+ expect(JSON.parse(fs.readFileSync(capturePath, 'utf8')).comm).not.toMatch(/^sm-claude-/);
295
+ // And the target helper degrades to the raw bin with no argv0.
296
+ delete process.env.SM_CLAUDE_BIN;
297
+ expect(claudeBin.claudeSpawnTarget('job', slug, stub)).toEqual({ command: stub });
298
+ } finally {
299
+ fs.rmSync(procName.procnamesRoot(), { force: true });
300
+ fs.rmSync(projectCwd, { recursive: true, force: true });
301
+ fs.rmSync(runDir, { recursive: true, force: true });
302
+ }
303
+ });
304
+ });
@@ -0,0 +1,127 @@
1
+ /**
2
+ * procname-sm-processes.test.cjs — PRD pn-03: Session Manager's own processes
3
+ * (main, MCP server, watchdog, inhibit holder, terminal shells) get
4
+ * self-describing kernel `comm` names. Headless: reads /proc/<pid>/comm.
5
+ * HOME is redirected BEFORE procName loads (ALIAS_ROOT is fixed at require time).
6
+ *
7
+ * Run: timeout 300 npx vitest run src/main/__tests__/procname-sm-processes.test.cjs
8
+ */
9
+ 'use strict';
10
+
11
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
12
+ const fs = require('node:fs');
13
+ const os = require('node:os');
14
+ const path = require('node:path');
15
+ const { spawn, spawnSync, execFileSync } = require('node:child_process');
16
+
17
+ const LINUX = process.platform === 'linux' && fs.existsSync('/proc/self/comm');
18
+ const REPO = path.resolve(__dirname, '..', '..', '..');
19
+ const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
20
+ const commOf = (pid) => fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim();
21
+
22
+ let tmpHome; let realHome; let names; let procName;
23
+
24
+ beforeAll(() => {
25
+ realHome = process.env.HOME;
26
+ tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-pn03-'));
27
+ process.env.HOME = tmpHome;
28
+ for (const m of ['procName', 'smProcNames']) delete require.cache[require.resolve(`../lib/${m}.cjs`)];
29
+ procName = require('../lib/procName.cjs');
30
+ names = require('../lib/smProcNames.cjs');
31
+ });
32
+ afterAll(() => {
33
+ process.env.HOME = realHome;
34
+ fs.rmSync(tmpHome, { recursive: true, force: true });
35
+ });
36
+
37
+ async function waitComm(pid, want, ms = 8000) {
38
+ const end = Date.now() + ms;
39
+ let last = '';
40
+ while (Date.now() < end) {
41
+ try { last = commOf(pid); if (last === want) return last; } catch { /* not yet */ }
42
+ await sleepMs(50);
43
+ }
44
+ return last;
45
+ }
46
+
47
+ describe('names', () => {
48
+ it('every name is <= 15 chars and distinct', () => {
49
+ const vals = Object.values(names.PROC_NAMES);
50
+ for (const v of vals) expect(v.length).toBeLessThanOrEqual(15);
51
+ expect(new Set(vals).size).toBe(vals.length);
52
+ expect(names.PROC_NAMES.main).toBe('session-manager');
53
+ expect(names.PROC_NAMES.main.length).toBe(15);
54
+ });
55
+ });
56
+
57
+ describe.skipIf(!LINUX)('process.title', () => {
58
+ it('sets comm and does not disturb process.argv', () => {
59
+ const out = execFileSync(process.execPath, ['-e', `
60
+ const n = require(${JSON.stringify(path.join(REPO, 'src/main/lib/smProcNames.cjs'))});
61
+ n.setProcessTitle(n.PROC_NAMES.main);
62
+ console.log(require('fs').readFileSync('/proc/self/comm','utf8').trim() + '|' + process.argv.slice(1).join(','));
63
+ `, 'a', '--simple'], { encoding: 'utf8', env: { ...process.env, HOME: tmpHome } }).trim();
64
+ expect(out).toBe('session-manager|a,--simple');
65
+ });
66
+
67
+ it('scheduler-mcp-server.cjs reports sm-mcp-server', async () => {
68
+ const child = spawn(process.execPath, [path.join(REPO, 'scripts/scheduler-mcp-server.cjs')], { stdio: ['pipe', 'ignore', 'ignore'], env: { ...process.env, HOME: tmpHome } });
69
+ try { expect(await waitComm(child.pid, 'sm-mcp-server')).toBe('sm-mcp-server'); } finally { child.kill('SIGKILL'); }
70
+ });
71
+
72
+ it('scheduler-watchdog.cjs names itself before any other work (static) and the setter yields sm-watchdog', async () => {
73
+ // Not spawned for real: a stale-heartbeat run relaunches the app via npx.
74
+ const src = fs.readFileSync(path.join(REPO, 'scripts/scheduler-watchdog.cjs'), 'utf8');
75
+ const first = src.indexOf('setProcessTitle(PROC_NAMES.watchdog)');
76
+ expect(first).toBeGreaterThan(-1);
77
+ expect(first).toBeLessThan(src.indexOf("require('node:fs')"));
78
+ const child = spawn(process.execPath, ['-e', `require(${JSON.stringify(path.join(REPO, 'src/main/lib/smProcNames.cjs'))}).setProcessTitle('sm-watchdog'); setTimeout(()=>{},20000)`], { stdio: 'ignore', env: { ...process.env, HOME: tmpHome } });
79
+ try { expect(await waitComm(child.pid, 'sm-watchdog')).toBe('sm-watchdog'); } finally { child.kill('SIGKILL'); }
80
+ });
81
+
82
+ it('inhibit holder shell aliased to sm-inhibit-hold runs the poll loop', async () => {
83
+ const child = spawn(names.inhibitHolderShell(), ['-c', `while kill -0 ${process.pid} 2>/dev/null; do sleep 1; done`], { stdio: 'ignore' });
84
+ try { expect(await waitComm(child.pid, 'sm-inhibit-hold')).toBe('sm-inhibit-hold'); } finally { child.kill('SIGKILL'); }
85
+ });
86
+
87
+ it('bash login shell via sm-shell still sources rc files and keeps $SHELL', () => {
88
+ const bash = ['/bin/bash', '/usr/bin/bash'].find((p) => fs.existsSync(p));
89
+ if (!bash) return;
90
+ const bin = names.aliasedShellBin(bash);
91
+ expect(path.basename(bin)).toBe('sm-shell');
92
+ fs.writeFileSync(path.join(tmpHome, '.bash_profile'), 'export SM_RC_MARK=sourced\n');
93
+ fs.writeFileSync(path.join(tmpHome, '.bashrc'), 'export SM_RC_MARK=sourced\n');
94
+ const r = spawnSync(bin, ['-il', '-c', 'echo "$SM_RC_MARK|$SHELL|$(cat /proc/$$/comm)"'], { encoding: 'utf8', env: { HOME: tmpHome, SHELL: bash, PATH: process.env.PATH } });
95
+ expect(r.stdout.trim().split('\n').pop()).toBe(`sourced|${bash}|sm-shell`);
96
+ });
97
+
98
+ it('loadGate top-CPU line (ps comm) shows an aliased process', async () => {
99
+ const child = spawn(names.inhibitHolderShell(), ['-c', 'while :; do :; done'], { stdio: 'ignore' });
100
+ try {
101
+ await waitComm(child.pid, 'sm-inhibit-hold');
102
+ const out = execFileSync('ps', ['-eo', 'pid,pcpu,comm', '--sort=-pcpu'], { encoding: 'utf8' });
103
+ expect(out).toMatch(new RegExp(`^\\s*${child.pid}\\s+\\S+\\s+sm-inhibit-hold$`, 'm'));
104
+ } finally { child.kill('SIGKILL'); }
105
+ });
106
+ });
107
+
108
+ describe('shell aliasing rules', () => {
109
+ it('skips non-bash/zsh shells (fish, nu, unknown) and non-strings', () => {
110
+ for (const s of ['/usr/bin/fish', '/usr/bin/nu', '/opt/weird/xsh', '', undefined]) expect(names.aliasedShellBin(s)).toBe(s);
111
+ });
112
+ it('aliases zsh by path basename', () => {
113
+ const fake = path.join(tmpHome, 'zsh');
114
+ fs.writeFileSync(fake, '#!/bin/sh\n', { mode: 0o755 });
115
+ expect(path.basename(names.aliasedShellBin(fake))).toBe('sm-shell');
116
+ });
117
+ it('fails open when ALIAS_ROOT is unwritable', () => {
118
+ fs.rmSync(procName.procnamesRoot(), { recursive: true, force: true });
119
+ fs.mkdirSync(path.dirname(procName.procnamesRoot()), { recursive: true });
120
+ fs.writeFileSync(procName.procnamesRoot(), 'a file, so mkdir/symlink under it fails');
121
+ try {
122
+ expect(names.inhibitHolderShell()).toBe('/bin/sh');
123
+ const bash = ['/bin/bash', '/usr/bin/bash'].find((p) => fs.existsSync(p));
124
+ if (bash) expect(names.aliasedShellBin(bash)).toBe(bash);
125
+ } finally { fs.rmSync(procName.procnamesRoot(), { force: true }); }
126
+ });
127
+ });