pi-crew 0.9.53 → 0.9.55

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 (493) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +6 -3
  3. package/scripts/clean-strip-types.mjs +60 -0
  4. package/src/adapters/claude-adapter.ts +23 -0
  5. package/src/adapters/codex-adapter.ts +21 -0
  6. package/src/adapters/cursor-adapter.ts +17 -0
  7. package/src/adapters/export-util.ts +143 -0
  8. package/src/adapters/index.ts +15 -0
  9. package/src/adapters/registry.ts +18 -0
  10. package/src/adapters/types.ts +23 -0
  11. package/src/agents/agent-config.ts +194 -0
  12. package/src/agents/agent-search.ts +98 -0
  13. package/src/agents/agent-serializer.ts +38 -0
  14. package/src/agents/discover-agents.ts +623 -0
  15. package/src/benchmark/benchmark-runner.ts +313 -0
  16. package/src/benchmark/feedback-loop.ts +73 -0
  17. package/src/config/config.ts +1270 -0
  18. package/src/config/defaults.ts +193 -0
  19. package/src/config/drift-detector.ts +290 -0
  20. package/src/config/markers.ts +330 -0
  21. package/src/config/resilient-parser.ts +117 -0
  22. package/src/config/role-tools.ts +118 -0
  23. package/src/config/suggestions.ts +75 -0
  24. package/src/config/types.ts +280 -0
  25. package/src/errors.ts +194 -0
  26. package/src/extension/action-suggestions.ts +117 -0
  27. package/src/extension/async-notifier.ts +179 -0
  28. package/src/extension/autonomous-policy.ts +209 -0
  29. package/src/extension/command-completions.ts +120 -0
  30. package/src/extension/context-status-injection.ts +185 -0
  31. package/src/extension/crew-autocomplete.ts +131 -0
  32. package/src/extension/crew-cleanup.ts +168 -0
  33. package/src/extension/crew-input-router.ts +93 -0
  34. package/src/extension/crew-shortcuts.ts +87 -0
  35. package/src/extension/crew-vibes/cat-frames.ts +18 -0
  36. package/src/extension/crew-vibes/config.ts +195 -0
  37. package/src/extension/crew-vibes/figures.ts +101 -0
  38. package/src/extension/crew-vibes/font-detect.ts +71 -0
  39. package/src/extension/crew-vibes/footer.ts +292 -0
  40. package/src/extension/crew-vibes/index.ts +432 -0
  41. package/src/extension/crew-vibes/provider-usage.ts +396 -0
  42. package/src/extension/crew-vibes/render.ts +206 -0
  43. package/src/extension/crew-vibes/speed.ts +286 -0
  44. package/src/extension/cross-extension-rpc.ts +350 -0
  45. package/src/extension/help.ts +62 -0
  46. package/src/extension/import-index.ts +74 -0
  47. package/src/extension/knowledge-injection.ts +402 -0
  48. package/src/extension/management.ts +571 -0
  49. package/src/extension/message-renderers.ts +108 -0
  50. package/src/extension/notification-router.ts +152 -0
  51. package/src/extension/notification-sink.ts +54 -0
  52. package/src/extension/pi-api.ts +56 -0
  53. package/src/extension/plan-orchestrate.ts +302 -0
  54. package/src/extension/project-init.ts +170 -0
  55. package/src/extension/register.ts +113 -0
  56. package/src/extension/registration/artifact-cleanup.ts +20 -0
  57. package/src/extension/registration/command-registration.ts +58 -0
  58. package/src/extension/registration/command-utils.ts +58 -0
  59. package/src/extension/registration/commands.ts +1228 -0
  60. package/src/extension/registration/compaction-guard.ts +333 -0
  61. package/src/extension/registration/context-builder.ts +135 -0
  62. package/src/extension/registration/crash-recovery-cache.ts +54 -0
  63. package/src/extension/registration/foreground-run-controller.ts +238 -0
  64. package/src/extension/registration/hook-registration.ts +119 -0
  65. package/src/extension/registration/lazy-configurers.ts +124 -0
  66. package/src/extension/registration/lifecycle-handlers.ts +923 -0
  67. package/src/extension/registration/lifecycle.ts +259 -0
  68. package/src/extension/registration/observability.ts +322 -0
  69. package/src/extension/registration/registration-types.ts +158 -0
  70. package/src/extension/registration/runtime-cleanup.ts +230 -0
  71. package/src/extension/registration/subagent-helpers.ts +125 -0
  72. package/src/extension/registration/subagent-manager-setup.ts +330 -0
  73. package/src/extension/registration/subagent-tools.ts +456 -0
  74. package/src/extension/registration/team-tool.ts +225 -0
  75. package/src/extension/registration/tool-registration.ts +50 -0
  76. package/src/extension/registration/ui.ts +172 -0
  77. package/src/extension/registration/viewers.ts +121 -0
  78. package/src/extension/registration/wire-cross-extension.ts +37 -0
  79. package/src/extension/result-watcher.ts +139 -0
  80. package/src/extension/rpc-hmac.ts +256 -0
  81. package/src/extension/run-bundle-schema.ts +104 -0
  82. package/src/extension/run-export.ts +97 -0
  83. package/src/extension/run-import.ts +168 -0
  84. package/src/extension/run-index.ts +131 -0
  85. package/src/extension/run-maintenance.ts +190 -0
  86. package/src/extension/session-summary.ts +18 -0
  87. package/src/extension/team-manager-command.ts +153 -0
  88. package/src/extension/team-onboard.ts +180 -0
  89. package/src/extension/team-recommendation.ts +288 -0
  90. package/src/extension/team-tool/anchor.ts +172 -0
  91. package/src/extension/team-tool/api.ts +1244 -0
  92. package/src/extension/team-tool/auto-summarize.ts +142 -0
  93. package/src/extension/team-tool/cache-control.ts +19 -0
  94. package/src/extension/team-tool/cancel.ts +337 -0
  95. package/src/extension/team-tool/chain-dispatch.ts +95 -0
  96. package/src/extension/team-tool/chain-executor.ts +379 -0
  97. package/src/extension/team-tool/config-patch.ts +50 -0
  98. package/src/extension/team-tool/context.ts +149 -0
  99. package/src/extension/team-tool/destructive-gate.ts +52 -0
  100. package/src/extension/team-tool/dispatch/automate.ts +80 -0
  101. package/src/extension/team-tool/dispatch/control.ts +42 -0
  102. package/src/extension/team-tool/dispatch/index.ts +95 -0
  103. package/src/extension/team-tool/dispatch/manage.ts +161 -0
  104. package/src/extension/team-tool/dispatch/run.ts +53 -0
  105. package/src/extension/team-tool/dispatch/status.ts +187 -0
  106. package/src/extension/team-tool/doctor.ts +431 -0
  107. package/src/extension/team-tool/explain.ts +282 -0
  108. package/src/extension/team-tool/failure-patterns.ts +118 -0
  109. package/src/extension/team-tool/goal-wrap.ts +330 -0
  110. package/src/extension/team-tool/goal.ts +556 -0
  111. package/src/extension/team-tool/handle-schedule.ts +332 -0
  112. package/src/extension/team-tool/handle-settings.ts +520 -0
  113. package/src/extension/team-tool/health-monitor.ts +481 -0
  114. package/src/extension/team-tool/inspect.ts +88 -0
  115. package/src/extension/team-tool/intent-policy.ts +45 -0
  116. package/src/extension/team-tool/lifecycle-actions.ts +615 -0
  117. package/src/extension/team-tool/orchestrate.ts +98 -0
  118. package/src/extension/team-tool/parallel-dispatch.ts +183 -0
  119. package/src/extension/team-tool/plan.ts +50 -0
  120. package/src/extension/team-tool/respond.ts +150 -0
  121. package/src/extension/team-tool/run-deadline.ts +66 -0
  122. package/src/extension/team-tool/run-not-found.ts +49 -0
  123. package/src/extension/team-tool/run.ts +1051 -0
  124. package/src/extension/team-tool/status.ts +260 -0
  125. package/src/extension/team-tool/workflow-manage.ts +261 -0
  126. package/src/extension/team-tool-types.ts +26 -0
  127. package/src/extension/team-tool.ts +750 -0
  128. package/src/extension/tool-result.ts +16 -0
  129. package/src/extension/validate-resources.ts +108 -0
  130. package/src/hooks/registry.ts +200 -0
  131. package/src/hooks/types.ts +69 -0
  132. package/src/i18n.ts +212 -0
  133. package/src/observability/correlation.ts +50 -0
  134. package/src/observability/event-bus.ts +86 -0
  135. package/src/observability/event-to-metric.ts +170 -0
  136. package/src/observability/exporters/adapter.ts +27 -0
  137. package/src/observability/exporters/otlp-exporter.ts +356 -0
  138. package/src/observability/exporters/prometheus-exporter.ts +54 -0
  139. package/src/observability/metric-registry.ts +100 -0
  140. package/src/observability/metric-retention.ts +64 -0
  141. package/src/observability/metric-sink.ts +99 -0
  142. package/src/observability/metrics-primitives.ts +219 -0
  143. package/src/plugins/plugin-define.ts +6 -0
  144. package/src/plugins/plugin-registry.ts +32 -0
  145. package/src/plugins/plugins/index.ts +3 -0
  146. package/src/plugins/plugins/nextjs.ts +19 -0
  147. package/src/plugins/plugins/vite.ts +10 -0
  148. package/src/plugins/plugins/vitest.ts +9 -0
  149. package/src/prompt/prompt-runtime.ts +380 -0
  150. package/src/runtime/adaptive-plan.ts +563 -0
  151. package/src/runtime/agent-control.ts +215 -0
  152. package/src/runtime/agent-memory.ts +81 -0
  153. package/src/runtime/agent-observability.ts +122 -0
  154. package/src/runtime/anchor-manager.ts +475 -0
  155. package/src/runtime/async-marker.ts +32 -0
  156. package/src/runtime/async-runner.ts +381 -0
  157. package/src/runtime/attention-events.ts +28 -0
  158. package/src/runtime/auto-summarize.ts +344 -0
  159. package/src/runtime/background-runner.ts +840 -0
  160. package/src/runtime/batch-barrier.ts +147 -0
  161. package/src/runtime/broker-issuer.ts +39 -0
  162. package/src/runtime/cancellation-token.ts +99 -0
  163. package/src/runtime/cancellation.ts +99 -0
  164. package/src/runtime/capability-inventory.ts +137 -0
  165. package/src/runtime/chain-parser.ts +237 -0
  166. package/src/runtime/chain-runner.ts +606 -0
  167. package/src/runtime/checkpoint.ts +291 -0
  168. package/src/runtime/child-pi-constants.ts +42 -0
  169. package/src/runtime/child-pi-kill.ts +180 -0
  170. package/src/runtime/child-pi-pool.ts +68 -0
  171. package/src/runtime/child-pi-spawn.ts +287 -0
  172. package/src/runtime/child-pi-steering.ts +128 -0
  173. package/src/runtime/child-pi-streams.ts +296 -0
  174. package/src/runtime/child-pi-transcript.ts +169 -0
  175. package/src/runtime/child-pi.ts +1105 -0
  176. package/src/runtime/coalesce-tasks.ts +268 -0
  177. package/src/runtime/code-summary.ts +292 -0
  178. package/src/runtime/command-trace.ts +105 -0
  179. package/src/runtime/compact-pipeline.ts +56 -0
  180. package/src/runtime/compact-stages/ansi-strip-stage.ts +25 -0
  181. package/src/runtime/compact-stages/blank-collapse-stage.ts +31 -0
  182. package/src/runtime/compact-stages/deduplicate-stage.ts +34 -0
  183. package/src/runtime/compact-stages/head-snap-stage.ts +57 -0
  184. package/src/runtime/compact-stages/index.ts +23 -0
  185. package/src/runtime/compact-stages/tail-capture-stage.ts +77 -0
  186. package/src/runtime/compact-stages/truncation-stage.ts +74 -0
  187. package/src/runtime/compaction-summary.ts +278 -0
  188. package/src/runtime/completion-guard.ts +207 -0
  189. package/src/runtime/concurrency.ts +58 -0
  190. package/src/runtime/crash-classification.ts +229 -0
  191. package/src/runtime/crash-recovery.ts +594 -0
  192. package/src/runtime/crew-agent-records.ts +595 -0
  193. package/src/runtime/crew-agent-runtime.ts +62 -0
  194. package/src/runtime/crew-broker-child.ts +88 -0
  195. package/src/runtime/crew-broker-client.ts +673 -0
  196. package/src/runtime/crew-broker-tokens.ts +159 -0
  197. package/src/runtime/crew-broker.ts +1304 -0
  198. package/src/runtime/crew-hooks.ts +227 -0
  199. package/src/runtime/cross-extension-rpc.ts +143 -0
  200. package/src/runtime/custom-tools/irc-tool.ts +282 -0
  201. package/src/runtime/custom-tools/submit-result-tool.ts +102 -0
  202. package/src/runtime/deadletter.ts +47 -0
  203. package/src/runtime/delivery-coordinator.ts +211 -0
  204. package/src/runtime/delta-conflict.ts +348 -0
  205. package/src/runtime/deterministic-ast.ts +161 -0
  206. package/src/runtime/diagnostic-export.ts +171 -0
  207. package/src/runtime/direct-run.ts +45 -0
  208. package/src/runtime/dwf-state-store.ts +102 -0
  209. package/src/runtime/dynamic-workflow-context.ts +1013 -0
  210. package/src/runtime/dynamic-workflow-runner.ts +325 -0
  211. package/src/runtime/effectiveness.ts +90 -0
  212. package/src/runtime/errors/crew-errors.ts +162 -0
  213. package/src/runtime/event-stream-bridge.ts +98 -0
  214. package/src/runtime/foreground-control.ts +193 -0
  215. package/src/runtime/foreground-watchdog.ts +132 -0
  216. package/src/runtime/global-worker-cap.ts +96 -0
  217. package/src/runtime/goal-achievement.ts +148 -0
  218. package/src/runtime/goal-evaluator.ts +365 -0
  219. package/src/runtime/goal-loop-runner.ts +825 -0
  220. package/src/runtime/goal-state-store.ts +219 -0
  221. package/src/runtime/green-contract.ts +55 -0
  222. package/src/runtime/group-join.ts +267 -0
  223. package/src/runtime/handoff-manager.ts +598 -0
  224. package/src/runtime/heartbeat-gradient.ts +36 -0
  225. package/src/runtime/heartbeat-watcher.ts +239 -0
  226. package/src/runtime/hidden-handoff.ts +407 -0
  227. package/src/runtime/important-line-classifier.ts +140 -0
  228. package/src/runtime/intercom-bridge.ts +187 -0
  229. package/src/runtime/iteration-hooks.ts +305 -0
  230. package/src/runtime/live-agent-control.ts +136 -0
  231. package/src/runtime/live-agent-manager.ts +704 -0
  232. package/src/runtime/live-control-realtime.ts +56 -0
  233. package/src/runtime/live-extension-bridge.ts +148 -0
  234. package/src/runtime/live-irc.ts +97 -0
  235. package/src/runtime/live-session-health.ts +108 -0
  236. package/src/runtime/live-session-runtime.ts +1146 -0
  237. package/src/runtime/loop-gates.ts +128 -0
  238. package/src/runtime/manifest-cache.ts +375 -0
  239. package/src/runtime/mcp-proxy.ts +105 -0
  240. package/src/runtime/metric-parser.ts +36 -0
  241. package/src/runtime/model-fallback.ts +409 -0
  242. package/src/runtime/model-resolver.ts +126 -0
  243. package/src/runtime/model-scope.ts +158 -0
  244. package/src/runtime/orphan-worker-registry.ts +465 -0
  245. package/src/runtime/output-validator.ts +202 -0
  246. package/src/runtime/overflow-recovery.ts +206 -0
  247. package/src/runtime/parallel-research.ts +68 -0
  248. package/src/runtime/parallel-utils.ts +160 -0
  249. package/src/runtime/parent-guard.ts +134 -0
  250. package/src/runtime/path-overlap.ts +150 -0
  251. package/src/runtime/peer-dep.ts +292 -0
  252. package/src/runtime/per-write-validator.ts +181 -0
  253. package/src/runtime/phase-progress.ts +217 -0
  254. package/src/runtime/phase-tracker.ts +385 -0
  255. package/src/runtime/pi-args.ts +655 -0
  256. package/src/runtime/pi-json-output.ts +170 -0
  257. package/src/runtime/pi-spawn.ts +273 -0
  258. package/src/runtime/pipeline-runner.ts +523 -0
  259. package/src/runtime/plan-templates.ts +201 -0
  260. package/src/runtime/policy-engine.ts +115 -0
  261. package/src/runtime/post-checks.ts +142 -0
  262. package/src/runtime/post-exit-stdio-guard.ts +109 -0
  263. package/src/runtime/process-lifecycle.ts +491 -0
  264. package/src/runtime/process-status.ts +154 -0
  265. package/src/runtime/progress-event-coalescer.ts +44 -0
  266. package/src/runtime/progress-tracker.ts +124 -0
  267. package/src/runtime/prose-compressor.ts +162 -0
  268. package/src/runtime/recovery-recipes.ts +203 -0
  269. package/src/runtime/replace.ts +570 -0
  270. package/src/runtime/resilient-edit.ts +153 -0
  271. package/src/runtime/result-extractor.ts +217 -0
  272. package/src/runtime/retry-executor.ts +109 -0
  273. package/src/runtime/retry-runner.ts +336 -0
  274. package/src/runtime/role-permission.ts +59 -0
  275. package/src/runtime/run-coalesced-task-group.ts +308 -0
  276. package/src/runtime/run-drift.ts +219 -0
  277. package/src/runtime/run-tracker.ts +116 -0
  278. package/src/runtime/run-worker.ts +78 -0
  279. package/src/runtime/runtime-policy.ts +29 -0
  280. package/src/runtime/runtime-resolver.ts +172 -0
  281. package/src/runtime/runtime-warmup.ts +160 -0
  282. package/src/runtime/scheduler.ts +353 -0
  283. package/src/runtime/semaphore.ts +141 -0
  284. package/src/runtime/sensitive-paths.ts +93 -0
  285. package/src/runtime/session-resources.ts +25 -0
  286. package/src/runtime/session-snapshot.ts +59 -0
  287. package/src/runtime/session-usage.ts +79 -0
  288. package/src/runtime/settings-store.ts +155 -0
  289. package/src/runtime/sidechain-output.ts +35 -0
  290. package/src/runtime/single-agent-compose.ts +84 -0
  291. package/src/runtime/skill-effectiveness.ts +524 -0
  292. package/src/runtime/skill-instructions.ts +394 -0
  293. package/src/runtime/stale-reconciler.ts +680 -0
  294. package/src/runtime/stream-preview.ts +184 -0
  295. package/src/runtime/streaming-output.ts +50 -0
  296. package/src/runtime/subagent-manager.ts +561 -0
  297. package/src/runtime/subprocess-tool-registry.ts +70 -0
  298. package/src/runtime/supervisor-contact.ts +64 -0
  299. package/src/runtime/task-display.ts +52 -0
  300. package/src/runtime/task-graph-scheduler.ts +227 -0
  301. package/src/runtime/task-graph.ts +290 -0
  302. package/src/runtime/task-health.ts +83 -0
  303. package/src/runtime/task-id.ts +161 -0
  304. package/src/runtime/task-output-context.ts +602 -0
  305. package/src/runtime/task-packet.ts +268 -0
  306. package/src/runtime/task-quality.ts +199 -0
  307. package/src/runtime/task-runner/capabilities.ts +78 -0
  308. package/src/runtime/task-runner/child-executor.ts +790 -0
  309. package/src/runtime/task-runner/context-retrieval.ts +163 -0
  310. package/src/runtime/task-runner/live-executor.ts +227 -0
  311. package/src/runtime/task-runner/output-splitter.ts +152 -0
  312. package/src/runtime/task-runner/post-execution.ts +480 -0
  313. package/src/runtime/task-runner/pre-execution.ts +365 -0
  314. package/src/runtime/task-runner/progress.ts +157 -0
  315. package/src/runtime/task-runner/prompt-builder.ts +278 -0
  316. package/src/runtime/task-runner/prompt-pipeline.ts +88 -0
  317. package/src/runtime/task-runner/result-utils.ts +16 -0
  318. package/src/runtime/task-runner/retrieval-orchestrator.ts +310 -0
  319. package/src/runtime/task-runner/run-projection.ts +125 -0
  320. package/src/runtime/task-runner/scaffold-executor.ts +25 -0
  321. package/src/runtime/task-runner/state-helpers.ts +176 -0
  322. package/src/runtime/task-runner/tail-read.ts +34 -0
  323. package/src/runtime/task-runner.ts +216 -0
  324. package/src/runtime/team-runner-artifacts.ts +13 -0
  325. package/src/runtime/team-runner.ts +2396 -0
  326. package/src/runtime/tool-output-pruner.ts +333 -0
  327. package/src/runtime/tool-progress.ts +278 -0
  328. package/src/runtime/usage-tracker.ts +73 -0
  329. package/src/runtime/verification-gates.ts +579 -0
  330. package/src/runtime/verification-integrity.ts +108 -0
  331. package/src/runtime/verification-worktree.ts +186 -0
  332. package/src/runtime/worker-heartbeat.ts +25 -0
  333. package/src/runtime/worker-startup.ts +83 -0
  334. package/src/runtime/workflow-state.ts +195 -0
  335. package/src/runtime/workspace-lock.ts +443 -0
  336. package/src/runtime/workspace-tree.ts +312 -0
  337. package/src/runtime/yield-handler.ts +224 -0
  338. package/src/runtime/zombie-scanner.ts +298 -0
  339. package/src/schema/config-schema.ts +327 -0
  340. package/src/schema/team-tool-schema.ts +492 -0
  341. package/src/schema/validation-types.ts +159 -0
  342. package/src/skills/discover-skills.ts +203 -0
  343. package/src/skills/skill-templates.ts +456 -0
  344. package/src/skills/validate.ts +285 -0
  345. package/src/state/active-run-registry.ts +439 -0
  346. package/src/state/artifact-store.ts +176 -0
  347. package/src/state/atomic-write.ts +970 -0
  348. package/src/state/blob-store.ts +308 -0
  349. package/src/state/contracts.ts +160 -0
  350. package/src/state/crew-init.ts +269 -0
  351. package/src/state/decision-ledger.ts +372 -0
  352. package/src/state/event-log-rotation.ts +399 -0
  353. package/src/state/event-log.ts +1465 -0
  354. package/src/state/event-reconstructor.ts +229 -0
  355. package/src/state/gitignore-manager.ts +46 -0
  356. package/src/state/health-store.ts +79 -0
  357. package/src/state/hook-instinct-bridge.ts +94 -0
  358. package/src/state/hook-integrations.ts +51 -0
  359. package/src/state/instinct-store.ts +275 -0
  360. package/src/state/jsonl-writer.ts +107 -0
  361. package/src/state/locks.ts +562 -0
  362. package/src/state/mailbox.ts +916 -0
  363. package/src/state/observation-store.ts +176 -0
  364. package/src/state/run-cache.ts +193 -0
  365. package/src/state/run-graph.ts +183 -0
  366. package/src/state/run-metrics.ts +165 -0
  367. package/src/state/schedule.ts +166 -0
  368. package/src/state/session-state-map.ts +51 -0
  369. package/src/state/state-store.ts +973 -0
  370. package/src/state/task-claims.ts +61 -0
  371. package/src/state/tiered-eval.ts +480 -0
  372. package/src/state/types-eval.ts +58 -0
  373. package/src/state/types.ts +447 -0
  374. package/src/state/usage.ts +138 -0
  375. package/src/state/worker-atomic-writer.ts +198 -0
  376. package/src/subagents/async-entry.ts +1 -0
  377. package/src/subagents/index.ts +3 -0
  378. package/src/subagents/live/control.ts +1 -0
  379. package/src/subagents/live/manager.ts +1 -0
  380. package/src/subagents/live/realtime.ts +1 -0
  381. package/src/subagents/live/session-runtime.ts +1 -0
  382. package/src/subagents/manager.ts +1 -0
  383. package/src/subagents/spawn.ts +1 -0
  384. package/src/teams/discover-teams.ts +187 -0
  385. package/src/teams/team-config.ts +27 -0
  386. package/src/teams/team-serializer.ts +38 -0
  387. package/src/tools/safe-bash-extension.ts +54 -0
  388. package/src/tools/safe-bash.ts +505 -0
  389. package/src/types/diff.d.ts +18 -0
  390. package/src/types/new-api-types.ts +35 -0
  391. package/src/ui/agent-management-overlay.ts +160 -0
  392. package/src/ui/card-colors.ts +139 -0
  393. package/src/ui/crew-footer.ts +102 -0
  394. package/src/ui/crew-select-list.ts +112 -0
  395. package/src/ui/dashboard-panes/agents-pane.ts +164 -0
  396. package/src/ui/dashboard-panes/cancellation-pane.ts +66 -0
  397. package/src/ui/dashboard-panes/capability-pane.ts +77 -0
  398. package/src/ui/dashboard-panes/health-pane.ts +31 -0
  399. package/src/ui/dashboard-panes/mailbox-pane.ts +35 -0
  400. package/src/ui/dashboard-panes/metrics-pane.ts +37 -0
  401. package/src/ui/dashboard-panes/progress-pane.ts +38 -0
  402. package/src/ui/dashboard-panes/transcript-pane.ts +10 -0
  403. package/src/ui/deploy-bundled-themes.ts +71 -0
  404. package/src/ui/dwf-phase-display.ts +151 -0
  405. package/src/ui/dynamic-border.ts +35 -0
  406. package/src/ui/format-helpers.ts +31 -0
  407. package/src/ui/heartbeat-aggregator.ts +74 -0
  408. package/src/ui/key-utils.ts +42 -0
  409. package/src/ui/keybinding-map.ts +248 -0
  410. package/src/ui/layout-primitives.ts +106 -0
  411. package/src/ui/live-conversation-overlay.ts +183 -0
  412. package/src/ui/live-duration.ts +55 -0
  413. package/src/ui/live-run-sidebar.ts +293 -0
  414. package/src/ui/loaders.ts +6 -0
  415. package/src/ui/mascot.ts +449 -0
  416. package/src/ui/overlays/agent-picker-overlay.ts +66 -0
  417. package/src/ui/overlays/confirm-overlay.ts +60 -0
  418. package/src/ui/overlays/help-overlay.ts +177 -0
  419. package/src/ui/overlays/mailbox-compose-overlay.ts +181 -0
  420. package/src/ui/overlays/mailbox-compose-preview.ts +78 -0
  421. package/src/ui/overlays/mailbox-detail-overlay.ts +155 -0
  422. package/src/ui/pi-ui-compat.ts +68 -0
  423. package/src/ui/powerbar-publisher.ts +459 -0
  424. package/src/ui/render-coalescer.ts +101 -0
  425. package/src/ui/render-diff.ts +160 -0
  426. package/src/ui/render-scheduler.ts +278 -0
  427. package/src/ui/run-action-dispatcher.ts +182 -0
  428. package/src/ui/run-dashboard.ts +910 -0
  429. package/src/ui/run-event-bus.ts +381 -0
  430. package/src/ui/run-snapshot-cache.ts +1057 -0
  431. package/src/ui/settings-overlay.ts +1067 -0
  432. package/src/ui/shared-overlay-scheduler.ts +96 -0
  433. package/src/ui/snapshot-types.ts +90 -0
  434. package/src/ui/spinner.ts +17 -0
  435. package/src/ui/status-colors.ts +143 -0
  436. package/src/ui/syntax-highlight.ts +136 -0
  437. package/src/ui/terminal-status.ts +269 -0
  438. package/src/ui/theme-adapter.ts +271 -0
  439. package/src/ui/theme-discovery.ts +199 -0
  440. package/src/ui/tool-progress-formatter.ts +93 -0
  441. package/src/ui/tool-renderers/brief-mode.ts +225 -0
  442. package/src/ui/tool-renderers/index.ts +726 -0
  443. package/src/ui/transcript-cache.ts +128 -0
  444. package/src/ui/transcript-entries.ts +256 -0
  445. package/src/ui/transcript-viewer.ts +424 -0
  446. package/src/ui/widget/index.ts +418 -0
  447. package/src/ui/widget/widget-formatters.ts +182 -0
  448. package/src/ui/widget/widget-model.ts +110 -0
  449. package/src/ui/widget/widget-renderer.ts +182 -0
  450. package/src/ui/widget/widget-types.ts +36 -0
  451. package/src/utils/bm25-search.ts +235 -0
  452. package/src/utils/completion-dedupe.ts +63 -0
  453. package/src/utils/conflict-detect.ts +668 -0
  454. package/src/utils/env-allowlist.ts +30 -0
  455. package/src/utils/env-filter.ts +155 -0
  456. package/src/utils/file-coalescer.ts +98 -0
  457. package/src/utils/fingerprint.ts +180 -0
  458. package/src/utils/frontmatter.ts +70 -0
  459. package/src/utils/fs-watch.ts +37 -0
  460. package/src/utils/gh-protocol.ts +556 -0
  461. package/src/utils/git.ts +260 -0
  462. package/src/utils/guards.ts +107 -0
  463. package/src/utils/ids.ts +24 -0
  464. package/src/utils/incremental-reader.ts +220 -0
  465. package/src/utils/internal-error.ts +10 -0
  466. package/src/utils/names.ts +36 -0
  467. package/src/utils/ndjson.ts +115 -0
  468. package/src/utils/paths.ts +227 -0
  469. package/src/utils/project-detector.ts +160 -0
  470. package/src/utils/redaction.ts +370 -0
  471. package/src/utils/resolve-shell.ts +36 -0
  472. package/src/utils/run-watcher-registry.ts +152 -0
  473. package/src/utils/safe-paths.ts +393 -0
  474. package/src/utils/scan-cache.ts +144 -0
  475. package/src/utils/session-utils.ts +110 -0
  476. package/src/utils/sleep.ts +54 -0
  477. package/src/utils/socket-path.ts +164 -0
  478. package/src/utils/sse-parser.ts +131 -0
  479. package/src/utils/task-name-generator.ts +337 -0
  480. package/src/utils/timings.ts +33 -0
  481. package/src/utils/token-counter.ts +200 -0
  482. package/src/utils/visual.ts +207 -0
  483. package/src/workflows/cost-estimator.ts +34 -0
  484. package/src/workflows/discover-workflows.ts +308 -0
  485. package/src/workflows/intermediate-store.ts +166 -0
  486. package/src/workflows/preflight-validator.ts +168 -0
  487. package/src/workflows/topology-analyzer.ts +203 -0
  488. package/src/workflows/validate-workflow.ts +50 -0
  489. package/src/workflows/workflow-config.ts +75 -0
  490. package/src/workflows/workflow-serializer.ts +32 -0
  491. package/src/worktree/branch-freshness.ts +112 -0
  492. package/src/worktree/cleanup.ts +341 -0
  493. package/src/worktree/worktree-manager.ts +1204 -0
@@ -0,0 +1,840 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { allAgents, discoverAgents } from "../agents/discover-agents.ts";
4
+ import { loadConfig } from "../config/config.ts";
5
+ import { atomicWriteFile } from "../state/atomic-write.ts";
6
+ import { appendEvent } from "../state/event-log.ts";
7
+ import { withRunLockSync } from "../state/locks.ts";
8
+ import { createRunPaths, loadRunManifestById, saveRunManifestAsync, updateRunStatus } from "../state/state-store.ts";
9
+ import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
10
+ import { allTeams, discoverTeams } from "../teams/discover-teams.ts";
11
+ import { errorMessage } from "../utils/guards.ts";
12
+ import { projectCrewRoot } from "../utils/paths.ts";
13
+ import { allWorkflows, discoverWorkflows } from "../workflows/discover-workflows.ts";
14
+ // Heavy runtime — lazy-loaded to avoid pulling team-runner into background-runner
15
+ // at module load time. Only needed when a background run actually starts.
16
+ import { primePeerDep } from "./peer-dep.ts";
17
+ import type { executeTeamRun as ExecuteTeamRunFn } from "./team-runner.ts";
18
+
19
+ let _cachedExecuteTeamRun: typeof ExecuteTeamRunFn | undefined;
20
+
21
+ /** Maximum runtime for a single background run before the watchdog force-aborts
22
+ * it. Prevents zombie background-runner processes when a team run hangs forever
23
+ * (e.g. a hung child Pi process, a stuck lock, or a test that spawns a run
24
+ * without cleanup). Default 2h — generous for legitimate long runs (research
25
+ * workflows, goal-loops) but catches true zombies (observed: 10h+ stale test
26
+ * runs). Override via PI_CREW_MAX_RUN_MS env (milliseconds). The watchdog
27
+ * aborts via the shared AbortController, then force-exits after a grace
28
+ * period in case the abort signal does not propagate to all execution paths. */
29
+ const MAX_BACKGROUND_RUN_MS = (() => {
30
+ const env = Number.parseInt(process.env.PI_CREW_MAX_RUN_MS ?? "", 10);
31
+ return Number.isFinite(env) && env > 0 ? env : 2 * 60 * 60 * 1000;
32
+ })();
33
+ async function executeTeamRun(...args: Parameters<typeof ExecuteTeamRunFn>): Promise<Awaited<ReturnType<typeof ExecuteTeamRunFn>>> {
34
+ if (!_cachedExecuteTeamRun) {
35
+ // FIX (split-scope install): prime the ESM peer dep BEFORE team-runner is
36
+ // imported, so its transitive skill-instructions.ts can read getAgentDir()
37
+ // from the primed cache instead of crashing on `Cannot find module`.
38
+ await primePeerDep().catch(() => {});
39
+ // LAZY: avoid pulling team-runner into background-runner at module load time.
40
+ const mod = await import("./team-runner.ts");
41
+ _cachedExecuteTeamRun = mod.executeTeamRun;
42
+ }
43
+ return _cachedExecuteTeamRun(...args);
44
+ }
45
+
46
+ import { logInternalError } from "../utils/internal-error.ts";
47
+ import { writeAsyncStartMarker } from "./async-marker.ts";
48
+ import { terminateActiveChildPiProcesses } from "./child-pi.ts";
49
+ import { directTeamAndWorkflowFromRun } from "./direct-run.ts";
50
+ import { unregisterWorker } from "./orphan-worker-registry.ts";
51
+ import { expandParallelResearchWorkflow } from "./parallel-research.ts";
52
+ import { startParentGuard, stopParentGuard } from "./parent-guard.ts";
53
+ import { resolveCrewRuntime, runtimeResolutionState } from "./runtime-resolver.ts";
54
+
55
+ /**
56
+ * Debug logger gated behind PI_CREW_DEBUG env var. Writes to background.log
57
+ * (console is redirected there). Eliminates log noise in normal operation
58
+ * while keeping diagnostics available when explicitly enabled.
59
+ */
60
+ function debugLog(message: string): void {
61
+ if (process.env.PI_CREW_DEBUG) console.log(message);
62
+ }
63
+
64
+ /**
65
+ * Heartbeat mechanism: periodically write a heartbeat file so the stale reconciler
66
+ * can distinguish "process died" from "process still alive but quiet".
67
+ * Without this, the reconciler relies solely on process.kill(pid, 0) which can
68
+ * false-positive when a process is SIGKILLed and the PID hasn't been recycled yet.
69
+ */
70
+ function startHeartbeat(stateRoot: string, eventsPath: string, runId: string): () => void {
71
+ const heartbeatPath = path.join(stateRoot, "heartbeat.json");
72
+ const writeHeartbeat = (): void => {
73
+ try {
74
+ const mem = process.memoryUsage();
75
+ atomicWriteFile(
76
+ heartbeatPath,
77
+ JSON.stringify({
78
+ pid: process.pid,
79
+ at: Date.now(),
80
+ runId,
81
+ memory: {
82
+ heapUsedMb: Math.round(mem.heapUsed / 1024 / 1024),
83
+ rssMb: Math.round(mem.rss / 1024 / 1024),
84
+ },
85
+ }),
86
+ );
87
+ } catch {
88
+ /* ignore — best-effort */
89
+ }
90
+ };
91
+ // Write immediately so the stale reconciler can use heartbeat age as liveness evidence.
92
+ writeHeartbeat();
93
+ const interval = setInterval(writeHeartbeat, 15_000);
94
+ interval.unref();
95
+ return () => clearInterval(interval);
96
+ }
97
+
98
+ /**
99
+ * Remove macOS malloc-stack-logging vars that get inherited by child shells.
100
+ * Without this, every subprocess prints "MallocStackLogging: can't turn off..." to stderr.
101
+ */
102
+ function scrubProcessEnv(): void {
103
+ delete process.env.MallocStackLogging;
104
+ delete process.env.MallocStackLoggingNoCompact;
105
+ }
106
+
107
+ function argValue(name: string): string | undefined {
108
+ const index = process.argv.indexOf(name);
109
+ if (index === -1) return undefined;
110
+ return process.argv[index + 1];
111
+ }
112
+
113
+ function startInterruptGuard(
114
+ manifest: { runId: string; stateRoot: string; eventsPath: string },
115
+ abortController: AbortController,
116
+ stopParentGuard: () => void,
117
+ ): () => void {
118
+ const controlPath = path.join(manifest.stateRoot, "foreground-control.json");
119
+ // FIX: Made configurable via PI_CREW_INTERRUPT_GUARD_INTERVAL_MS env var.
120
+ // Default 250ms balances fast SIGINT response against filesystem overhead.
121
+ const interruptGuardInterval = Number(process.env.PI_CREW_INTERRUPT_GUARD_INTERVAL_MS) || 250;
122
+ const interval = setInterval(() => {
123
+ try {
124
+ if (!fs.existsSync(controlPath)) return;
125
+ const parsed = JSON.parse(fs.readFileSync(controlPath, "utf-8")) as {
126
+ requests?: Array<{ type: string; acknowledged?: boolean }>;
127
+ };
128
+ const last = parsed.requests?.at(-1);
129
+ if (last?.type === "interrupt" && last?.acknowledged !== true) {
130
+ appendEvent(manifest.eventsPath, {
131
+ type: "async.interrupt_detected",
132
+ runId: manifest.runId,
133
+ message: "Background runner detected foreground interrupt — killing child processes and exiting.",
134
+ });
135
+ // FIX: Terminate ALL child-pi processes IMMEDIATELY before exiting.
136
+ // Previously this was missing, causing orphaned child processes to run forever
137
+ // after the background-runner exited. terminateActiveChildPiProcesses sends
138
+ // SIGTERM then SIGKILL (after HARD_KILL_MS=3s) to every active child.
139
+ const killed = terminateActiveChildPiProcesses();
140
+ console.log(`[background-runner] interrupt: killed ${killed} child processes`);
141
+ // Also abort the run signal so executeTeamRun exits quickly via its signal check.
142
+ abortController.abort();
143
+ // Call stopParentGuard() explicitly in addition to the finally block in
144
+ // main() — defense-in-depth ensures the guard is torn down promptly.
145
+ stopParentGuard();
146
+ // CORE-7 fix: Do NOT call process.exit() — it skips the finally block in
147
+ // main() (which runs unregisterWorker + stopParentGuard), leaving a stale
148
+ // orphan registry entry. Setting exitCode lets the event loop drain and
149
+ // main()'s finally block run cleanup before the process exits naturally
150
+ // with code 130.
151
+ process.exitCode = 130;
152
+ } else if (last) {
153
+ console.warn(`[background-runner] Ignoring unknown foreground control request: ${last.type}`);
154
+ }
155
+ } catch {
156
+ /* ignore read/parse errors */
157
+ }
158
+ }, interruptGuardInterval);
159
+ interval.unref();
160
+ return () => clearInterval(interval);
161
+ }
162
+
163
+ /**
164
+ * CRITICAL: Node.js v24 throws on unhandled rejections by default.
165
+ * Without this handler, any unhandled promise rejection (e.g., from cleanupTempDir,
166
+ * terminateLiveAgentsForRun, or other async cleanup) will crash the background runner
167
+ * BEFORE async.completed is written to the event log.
168
+ * This causes the async notifier to falsely detect a stuck run after quietMs expires.
169
+ */
170
+ function setupUnhandledRejectionGuard(
171
+ state: {
172
+ cwd?: string;
173
+ runId?: string;
174
+ eventsPath?: string;
175
+ },
176
+ abortController: AbortController,
177
+ setExitFlag: () => void,
178
+ ): void {
179
+ process.on("unhandledRejection", (reason, promise) => {
180
+ const message = errorMessage(reason);
181
+ console.error("[background-runner] UNHANDLED REJECTION:", reason);
182
+ console.error("[background-runner] Stack:", reason instanceof Error ? reason.stack : "N/A");
183
+ try {
184
+ if (state.eventsPath && state.runId) {
185
+ appendEvent(state.eventsPath, {
186
+ type: "async.failed",
187
+ runId: state.runId,
188
+ message: `Unhandled rejection: ${message}`,
189
+ data: {
190
+ reason: String(reason),
191
+ stack: reason instanceof Error ? reason.stack : undefined,
192
+ handled: false,
193
+ },
194
+ });
195
+ }
196
+ } catch (appendErr) {
197
+ console.error("[background-runner] Failed to write async.failed event:", appendErr);
198
+ }
199
+ // FIX Issues #2& #4: Signal child processes to terminate via abortController,
200
+ // set the exit flag so main() exits after the finally block runs cleanup.
201
+ // Previously this called process.exit(1) directly, bypassing the finally block
202
+ // and leaving child processes orphaned.
203
+ abortController.abort();
204
+ setExitFlag();
205
+ });
206
+ }
207
+
208
+ /**
209
+ * FIX Issue #4: Shared cleanup function called by both the finally block
210
+ * and error handlers. This ensures consistent cleanup regardless of how
211
+ * the process exits (normal flow, unhandled rejection, or main() exception).
212
+ */
213
+ function runCleanup(
214
+ stopInterruptGuard: () => void,
215
+ stopParentGuard: () => void,
216
+ stopHeartbeat: () => void,
217
+ keepAlive: NodeJS.Timeout,
218
+ watchdogTimer: NodeJS.Timeout,
219
+ exitDueToRejection: boolean,
220
+ eventsPath?: string,
221
+ ): void {
222
+ console.log(`[background-runner] runCleanup, exitDueToRejection=${exitDueToRejection}`);
223
+ stopInterruptGuard();
224
+ stopParentGuard();
225
+ stopHeartbeat();
226
+ // FIX: clearInterval FIRST, then kill children. This ensures the heartbeat
227
+ // interval is always cleaned up even if terminateActiveChildPiProcesses throws.
228
+ clearInterval(keepAlive);
229
+ // Clear the anti-zombie watchdog so a normally-completing run does not
230
+ // carry a pending force-exit timer into the exit path.
231
+ clearTimeout(watchdogTimer);
232
+ // FIX Issues #1, #2, #4: Wrap child process termination in try/catch so errors
233
+ // don't prevent the cleanup from completing. We log but don't re-throw since
234
+ // we're already exiting.
235
+ let killed = 0;
236
+ try {
237
+ killed = terminateActiveChildPiProcesses();
238
+ } catch (error) {
239
+ console.log(`[background-runner] runCleanup: terminateActiveChildPiProcesses error: ${errorMessage(error)}`);
240
+ }
241
+ console.log(`[background-runner] runCleanup: killed ${killed} child processes`);
242
+ // FIX Issue #5: Unregister this worker from the orphan registry on exit.
243
+ // Previously this was only cleaned up on the next session_start cleanup cycle,
244
+ // causing unnecessary delay in removing stale registrations.
245
+ try {
246
+ unregisterWorker(process.pid);
247
+ } catch (error) {
248
+ console.log(`[background-runner] runCleanup: unregisterWorker error: ${errorMessage(error)}`);
249
+ if (eventsPath) {
250
+ try {
251
+ appendEvent(eventsPath, {
252
+ type: "background.unregister_worker_failed",
253
+ runId: argValue("--run-id") ?? "unknown",
254
+ message: `unregisterWorker failed: ${errorMessage(error)}`,
255
+ data: { pid: process.pid },
256
+ });
257
+ } catch {
258
+ /* best-effort */
259
+ }
260
+ }
261
+ }
262
+ // FIX Issues #2 & #4: If an unhandled rejection occurred, exit with code 1
263
+ // after cleanup completes. This ensures the finally block runs cleanup first,
264
+ // then we exit with the appropriate code.
265
+ if (exitDueToRejection) {
266
+ process.exit(1);
267
+ }
268
+ }
269
+
270
+ // Module-level flag: set by unhandled rejection guard and main() catch.
271
+ // Used by the module-level catch to signal that finally should call process.exit(1).
272
+ let exitDueToRejection = false;
273
+
274
+ async function main(): Promise<void> {
275
+ // FIX: Store logFd so it can be closed on exit to prevent file descriptor leak
276
+ let logFd: number | undefined;
277
+ // Redirect console to background.log since stdio is "ignore" in detached mode.
278
+ // This is the ABSOLUTE FIRST thing main() does after reading --cwd/--run-id
279
+ // (which are required to build the log path). Any later — after heavy imports,
280
+ // scrubProcessEnv, or signal handler setup — and JS-level crashes during those
281
+ // steps would lose their console output.
282
+ //
283
+ // NOTE on native crashes: a V8 heap-OOM abort() or segfault bypasses this
284
+ // console redirect entirely (it writes straight to the process stderr fd).
285
+ // Those are now captured two other ways: (1) the parent drains the child's
286
+ // stderr pipe into background.log (see async-runner.ts spawn), and (2) the
287
+ // V8 --report-on-fatalerror flag (ON by default) writes a report file into
288
+ // the run stateRoot. This console redirect only covers JS-level output.
289
+ const _cwd = argValue("--cwd");
290
+ const _runId = argValue("--run-id");
291
+ if (_cwd && _runId) {
292
+ try {
293
+ // Use projectCrewRoot() so the background log lives next to the
294
+ // manifest in either .crew/state/runs/ or .pi/teams/state/runs/
295
+ // depending on the project's chosen layout (issue #29).
296
+ const logPath = path.join(projectCrewRoot(_cwd), "state", "runs", _runId, "background.log");
297
+ logFd = fs.openSync(logPath, "a");
298
+ const origWrite =
299
+ (_prefix: string) =>
300
+ (data: unknown, ...args: unknown[]) => {
301
+ // FIX: Never let the in-process console redirect crash the background
302
+ // runner. If logFd is missing/invalid or the write fails, swallow the
303
+ // error silently — losing one debug line is far better than killing the
304
+ // scheduler (a previous version only redirected console.log/error, so
305
+ // console.debug/.warn still wrote to the original stdout/stderr pipe
306
+ // which is closed after the parent detaches, producing EPIPE → process
307
+ // crash mid-workflow → runs hang at 25% forever).
308
+ if (logFd === undefined) return;
309
+ const msg = [data, ...args].map(String).join(" ") + "\n";
310
+ try {
311
+ fs.writeSync(logFd, msg);
312
+ } catch {
313
+ /* best-effort: never crash the scheduler over a log write */
314
+ }
315
+ };
316
+ console.log = origWrite("OUT");
317
+ console.error = origWrite("ERR");
318
+ // FIX: Also redirect console.debug and console.warn — otherwise they still
319
+ // hit the original stdout/stderr pipe, which is closed once the parent
320
+ // process detaches, causing EPIPE unhandled errors that kill the scheduler.
321
+ console.debug = origWrite("DBG");
322
+ console.warn = origWrite("WARN");
323
+ // FIX: Close logFd on process exit to prevent file descriptor leak
324
+ process.on("exit", () => {
325
+ try {
326
+ if (logFd !== undefined) fs.closeSync(logFd);
327
+ } catch {
328
+ /* ignore */
329
+ }
330
+ });
331
+ } catch {
332
+ /* best-effort */
333
+ }
334
+ }
335
+
336
+ // Scrub macOS malloc vars BEFORE anything else — must be clean for all child processes
337
+ scrubProcessEnv();
338
+ // Install signal handlers EARLY — log events before exiting so we can distinguish
339
+ // OOM/SIGKILL (no event) from SIGTERM/SIGINT (event written).
340
+ const signalLog = (sig: string, eventsPath: string): void => {
341
+ const runId = argValue("--run-id");
342
+ if (runId && eventsPath) {
343
+ appendEvent(eventsPath, {
344
+ type: "async.failed",
345
+ runId,
346
+ message: `Background runner received ${sig} — exiting.`,
347
+ data: { signal: sig, pid: process.pid },
348
+ });
349
+ }
350
+ };
351
+ // BUG #17 FIX: Compute exitCodePath at module load time using args,
352
+ // NOT by referencing `manifest` (declared inside main() and not in scope at module load).
353
+ const exitCodePath = ((): string | undefined => {
354
+ const cwd = argValue("--cwd");
355
+ const runId = argValue("--run-id");
356
+ if (!cwd || !runId) return undefined;
357
+ // Use projectCrewRoot() to honour the .pi/teams/ fallback (issue #29).
358
+ return path.join(projectCrewRoot(cwd), "state", "runs", runId, "exit-code.txt");
359
+ })();
360
+ if (exitCodePath) {
361
+ process.on("exit", (code) => {
362
+ // Only log non-zero exit codes to avoid noise in exit-code.txt
363
+ if (code === 0 || code === undefined) return;
364
+ try {
365
+ fs.appendFileSync(exitCodePath, `${new Date().toISOString()} exit_code=${code} pid=${process.pid}\n`);
366
+ } catch (error) {
367
+ logInternalError("background-runner.exit-code-write", error, `exitCodePath=${exitCodePath}`, "debug");
368
+ }
369
+ });
370
+ }
371
+
372
+ // FIX Issue #1: Load manifest and create abortController BEFORE signal handlers
373
+ // are installed, since the handlers reference manifest.eventsPath and abortController.
374
+ const cwd = argValue("--cwd");
375
+ const runId = argValue("--run-id");
376
+ if (!cwd || !runId) throw new Error("Usage: background-runner.ts --cwd <cwd> --run-id <runId>");
377
+ // FIX Issue #3: Wrap in withRunLockSync to prevent concurrent background-runners
378
+ // for the same runId from reading stale manifest state. If lock cannot be
379
+ // be acquired within 5s, fail immediately rather than proceeding with stale data.
380
+ //
381
+ // BUGFIX (caught by E2E parallel-spawn, 2026-06-27): the lock manifest must
382
+ // carry the REAL per-run stateRoot, NOT an empty string. lockPath() derives
383
+ // `<stateRoot>/run.lock`, so `stateRoot: ""` collapses every concurrent
384
+ // background-runner (different runIds, same spawn instant) onto a SINGLE
385
+ // shared `run.lock` at cwd — 1 acquires, the rest fail-fast and die. Compute
386
+ // the per-run stateRoot from (cwd, runId) via createRunPaths (same helper
387
+ // resolveRunStateRoot uses internally), so each run locks its own
388
+ // `<cwd>/.crew/state/runs/<runId>/run.lock`. Matches locks-race.test.ts.
389
+ const bootstrapStateRoot = createRunPaths(cwd, runId).stateRoot;
390
+ let loaded: { manifest: TeamRunManifest; tasks: TeamTaskState[] } | undefined;
391
+ try {
392
+ loaded = withRunLockSync({ stateRoot: bootstrapStateRoot, runId, cwd } as TeamRunManifest, () => loadRunManifestById(cwd, runId), {
393
+ staleMs: 30_000,
394
+ });
395
+ } catch (lockErr) {
396
+ throw new Error(`Failed to acquire lock for run '${runId}': ${errorMessage(lockErr)}`);
397
+ }
398
+ if (!loaded) throw new Error(`Run '${runId}' not found.`);
399
+ let { manifest, tasks } = loaded;
400
+ const abortController = new AbortController();
401
+
402
+ process.on("SIGTERM", () => {
403
+ // BUG #17 FIX: Handle SIGTERM for graceful shutdown. Real I/O (appendEvent) flushes io_uring state before abort to prevent corruption..
404
+ // IMPORTANT: Perform real I/O here to flush io_uring state after EINTR.
405
+ // Without I/O, io_uring can enter corrupted state and cause silent crash.
406
+ // FIX Issue #3: Trigger graceful shutdown via abortController signal,
407
+ // allowing the finally block to run and clean up child processes.
408
+ // The io_uring I/O is still performed before abort takes effect.
409
+ const runId = argValue("--run-id");
410
+ if (runId && manifest.eventsPath) {
411
+ try {
412
+ appendEvent(manifest.eventsPath, {
413
+ type: "async.sigterm_received_graceful_shutdown",
414
+ runId,
415
+ message: `SIGTERM received, graceful shutdown via abort pid=${process.pid}`,
416
+ data: { pid: process.pid, ppid: process.ppid },
417
+ });
418
+ } catch {
419
+ /* best-effort */
420
+ }
421
+ }
422
+ // Trigger graceful shutdown via abort signal so finally block runs
423
+ abortController.abort();
424
+ });
425
+ process.on("SIGINT", () => {
426
+ signalLog("SIGINT", manifest.eventsPath);
427
+ process.exit(130);
428
+ });
429
+ // BUG #17: Catch ALL signals to identify what kills the background runner
430
+ for (const sig of [
431
+ "SIGHUP",
432
+ "SIGUSR1",
433
+ "SIGUSR2",
434
+ "SIGPIPE",
435
+ "SIGALRM",
436
+ "SIGPROF",
437
+ "SIGIO",
438
+ "SIGPWR",
439
+ "SIGSYS",
440
+ "SIGURG",
441
+ "SIGWINCH",
442
+ "SIGCONT",
443
+ "SIGTSTP",
444
+ "SIGTTIN",
445
+ "SIGTTOU",
446
+ "SIGVTALRM",
447
+ "SIGXCPU",
448
+ "SIGXFSZ",
449
+ ] as const) {
450
+ try {
451
+ process.on(sig, () => {
452
+ signalLog(sig, manifest.eventsPath);
453
+ });
454
+ } catch {
455
+ /* some signals not supported on this platform */
456
+ }
457
+ }
458
+ // Hook Node.js abort — if process.exit is called with code 1 (uncaught exception, assert failure)
459
+ // we log it before exiting so it appears in background.log.
460
+ // NOTE: process.exit is monkey-patched here (not using process.on('exit')) because
461
+ // we need the log write to happen synchronously before the process actually exits.
462
+ // process.on('exit') handlers run too late for I/O to complete reliably.
463
+ // Wrapped in try/catch to guard against failures in the patch itself.
464
+ try {
465
+ const origExit = process.exit.bind(process);
466
+ // Intercept all exit(code) calls to log them as async.exit events before exiting.
467
+ // This surfaces uncaught exceptions / early exits that would otherwise vanish silently.
468
+ process.exit = ((code?: number | string): never => {
469
+ const runId2 = argValue("--run-id");
470
+ const codeStr = code === undefined ? "<none>" : String(code);
471
+ if (runId2 && manifest.eventsPath) {
472
+ try {
473
+ appendEvent(manifest.eventsPath, {
474
+ type: "async.exit",
475
+ runId: runId2,
476
+ message: `Background runner exit(${codeStr}) pid=${process.pid}`,
477
+ data: { code, pid: process.pid },
478
+ });
479
+ } catch {
480
+ /* best-effort */
481
+ }
482
+ }
483
+ return origExit(code);
484
+ }) as typeof process.exit;
485
+ } catch {
486
+ // If patching process.exit fails (e.g. frozen process object), continue
487
+ // without the exit log — the run will still proceed normally.
488
+ }
489
+
490
+ // Setup unhandled rejection guard FIRST — must be before any async operations
491
+ // that might produce unhandled rejections during cleanup. Without this, any unhandled
492
+ // rejection would crash the worker BEFORE async.failed events are written.
493
+ const rejectionGuardState = {
494
+ cwd,
495
+ runId,
496
+ eventsPath: manifest.eventsPath,
497
+ };
498
+ // FIX Issues #2& #4: Flag to signal that an unhandled rejection occurred.
499
+ // When set, runCleanup() will ensure process.exit(1) is called after cleanup.
500
+ exitDueToRejection = false;
501
+ const setExitFlag = (): void => {
502
+ exitDueToRejection = true;
503
+ };
504
+ setupUnhandledRejectionGuard(rejectionGuardState, abortController, setExitFlag);
505
+
506
+ // Start parent guard — if parent is already dead, exit immediately
507
+ const parentPid = Number(process.env.PI_CREW_PARENT_PID);
508
+ if (parentPid > 0) startParentGuard(parentPid);
509
+ // NOTE: intentionally no unref() — the guard keeps the event loop alive
510
+ // to prevent premature worker exit. See parent-guard.ts:86 for rationale.
511
+
512
+ appendEvent(manifest.eventsPath, {
513
+ type: "async.started",
514
+ runId: manifest.runId,
515
+ data: { pid: process.pid },
516
+ });
517
+ debugLog(`[background-runner] async.started written, pid=${process.pid}`);
518
+ writeAsyncStartMarker(manifest, {
519
+ pid: process.pid,
520
+ startedAt: new Date().toISOString(),
521
+ });
522
+ const stopHeartbeat = startHeartbeat(manifest.stateRoot, manifest.eventsPath, manifest.runId);
523
+ const stopInterruptGuard = startInterruptGuard(manifest, abortController, stopParentGuard);
524
+ debugLog(`[background-runner] heartbeat+interrupt guard started`);
525
+ // NOTE: Keep-alive interval is NOT unref'd (unlike heartbeat and interrupt
526
+ // guard intervals which ARE unref'd). This is intentional — during jiti
527
+ // compilation of team-runner.ts, the event loop must not drain prematurely.
528
+ // The interval is always cleared in the finally block, so the delay is
529
+ // bounded by the 5s interval. The event loop exit is deferred at most 5s.
530
+ const keepAlive = setInterval(() => {}, 5000);
531
+
532
+ // WATCHDOG (anti-zombie): if the run exceeds MAX_BACKGROUND_RUN_MS without
533
+ // completing, abort it and force-exit. Without this, a hung team run
534
+ // (stuck child Pi, deadlocked lock, test that never cleans up) leaves the
535
+ // background-runner alive forever because keepAlive holds the event loop.
536
+ // The watchdog fires once; it is cleared in the finally block via runCleanup.
537
+ const watchdogTimer = setTimeout(() => {
538
+ console.error(`[background-runner] WATCHDOG: run ${runId} exceeded ${MAX_BACKGROUND_RUN_MS}ms — aborting (zombie prevention)`);
539
+ try {
540
+ appendEvent(manifest.eventsPath, {
541
+ type: "async.watchdog_fired",
542
+ runId,
543
+ message: `Run exceeded ${MAX_BACKGROUND_RUN_MS}ms and was force-aborted to prevent a zombie background-runner process.`,
544
+ data: { maxRunMs: MAX_BACKGROUND_RUN_MS },
545
+ });
546
+ } catch {
547
+ /* best-effort event log */
548
+ }
549
+ // Signal the finally block to exit(1) after cleanup.
550
+ exitDueToRejection = true;
551
+ // Abort the in-flight team run via the shared signal (propagates to
552
+ // executeTeamRun → child-pi → kills child processes).
553
+ abortController.abort();
554
+ // Hard-exit safety net: if the abort does not propagate within 15s
555
+ // (e.g. a hung native call), force-kill so the process cannot linger.
556
+ const forceExit = setTimeout(() => {
557
+ console.error(`[background-runner] WATCHDOG: abort did not propagate within grace period — force-exiting`);
558
+ stopParentGuard();
559
+ try {
560
+ terminateActiveChildPiProcesses();
561
+ } catch {
562
+ /* best-effort */
563
+ }
564
+ process.exit(1);
565
+ }, 15_000);
566
+ forceExit.unref();
567
+ }, MAX_BACKGROUND_RUN_MS);
568
+
569
+ try {
570
+ debugLog(`[background-runner] about to call discoverAgents`);
571
+ const agents = allAgents(discoverAgents(cwd));
572
+ debugLog(`[background-runner] discoverAgents done, ${agents.length} agents`);
573
+ // Round 27 (BUG 2): openSync returned an fd that was never closed → FD
574
+ // leak per background runner startup. Close it in a finally (matches the
575
+ // canonical pattern in checkpoint.ts:83 and event-log.ts:582).
576
+ try {
577
+ const fd = fs.openSync(manifest.eventsPath, "a");
578
+ try {
579
+ fs.fsyncSync(fd);
580
+ } finally {
581
+ try {
582
+ fs.closeSync(fd);
583
+ } catch {
584
+ /* best-effort */
585
+ }
586
+ }
587
+ } catch {
588
+ /* best-effort */
589
+ } // FORCE flush so we see this before death
590
+ // Fix round-4 CRITICAL: goal-loop and dynamic-workflow manifests use SYNTHETIC
591
+ // team/workflow names not in discoverTeams/discoverWorkflows. The team+workflow
592
+ // lookup below would throw "Team not found" BEFORE the runKind switch, making the
593
+ // goal feature unreachable from background. Short-circuit the new runKinds here.
594
+ process.env.PI_CREW_BACKGROUND_MODE = "1";
595
+ let earlyResult: { manifest: TeamRunManifest; tasks: TeamTaskState[] } | undefined;
596
+ let result: { manifest: TeamRunManifest; tasks: TeamTaskState[] } | undefined;
597
+ if (manifest.runKind === "goal-loop" || manifest.runKind === "dynamic-workflow") {
598
+ debugLog(`[background-runner] short-circuiting ${manifest.runKind} (synthetic team/workflow)`);
599
+ if (manifest.runKind === "goal-loop") {
600
+ // LAZY: defer dynamic import of ./goal-loop-runner.ts to its call site.
601
+ const { runGoalLoop } = await import("./goal-loop-runner.ts");
602
+ // LAZY: defer dynamic import of ./goal-state-store.ts to its call site.
603
+ const { GoalStore } = await import("./goal-state-store.ts");
604
+ // LAZY: defer dynamic import of ../agents/discover-agents.ts to its call site.
605
+ const { discoverAgents, allAgents } = await import("../agents/discover-agents.ts");
606
+ const store = new GoalStore(manifest.cwd);
607
+ const goalState = store.load(manifest.runId);
608
+ if (!goalState)
609
+ throw new Error(`runKind="goal-loop" but GoalLoopState '${manifest.runId}' not found (cwd=${manifest.cwd})`);
610
+ const goalResult = await runGoalLoop({
611
+ goalState,
612
+ manifest,
613
+ signal: abortController.signal,
614
+ deps: {
615
+ discoverAgents: (c: string) => allAgents(discoverAgents(c)),
616
+ },
617
+ });
618
+ // Fix P1-1 + round-6 #5: persist terminal status reflecting the goal's actual outcome,
619
+ // not a blanket 'completed'. Map goal state → manifest status.
620
+ const goalStatusToRunStatus: Record<string, TeamRunManifest["status"]> = {
621
+ achieved: "completed",
622
+ max_turns: "completed",
623
+ budget_exceeded: "completed",
624
+ blocked: "blocked",
625
+ cancelled: "cancelled",
626
+ paused: "blocked",
627
+ running: "running",
628
+ };
629
+ const runStatus = goalStatusToRunStatus[goalResult.goalState.state] ?? "completed";
630
+ const finalGoalManifest: TeamRunManifest = {
631
+ ...goalResult.manifest,
632
+ status: runStatus,
633
+ updatedAt: new Date().toISOString(),
634
+ };
635
+ await saveRunManifestAsync(finalGoalManifest);
636
+ earlyResult = {
637
+ manifest: finalGoalManifest,
638
+ tasks: goalResult.tasks,
639
+ };
640
+ } else {
641
+ // LAZY: defer dynamic import of ./dynamic-workflow-runner.ts to its call site.
642
+ const { runDynamicWorkflow } = await import("./dynamic-workflow-runner.ts");
643
+ // LAZY: defer dynamic import of ../workflows/discover-workflows.ts to its call site.
644
+ const { allWorkflows, discoverWorkflows } = await import("../workflows/discover-workflows.ts");
645
+ const wf = allWorkflows(discoverWorkflows(manifest.cwd)).find((w) => w.name === manifest.workflow);
646
+ if (wf?.runtime !== "dynamic" || !wf.dynamicScript)
647
+ throw new Error(
648
+ `runKind="dynamic-workflow" but workflow '${manifest.workflow}' is not dynamic (runId=${manifest.runId})`,
649
+ );
650
+ const dwfResult = await runDynamicWorkflow({
651
+ manifest,
652
+ workflow: wf as import("../workflows/workflow-config.ts").DynamicWorkflowConfig,
653
+ signal: abortController.signal,
654
+ tokenBudget: wf.maxTokenBudget,
655
+ });
656
+ await saveRunManifestAsync(dwfResult.manifest);
657
+ earlyResult = dwfResult;
658
+ }
659
+ console.log(`[background-runner] ${manifest.runKind} returned, status=${earlyResult.manifest.status}`);
660
+ result = earlyResult;
661
+ }
662
+ if (!earlyResult) {
663
+ debugLog(`[background-runner] calling directTeamAndWorkflowFromRun`);
664
+ const direct = directTeamAndWorkflowFromRun(manifest, tasks, agents);
665
+ debugLog(`[background-runner] direct done, finding team`);
666
+ const team = direct?.team ?? allTeams(discoverTeams(cwd)).find((candidate) => candidate.name === manifest.team);
667
+ if (!team) throw new Error(`Team '${manifest.team}' not found.`);
668
+ debugLog(`[background-runner] team=${team.name}, finding workflow`);
669
+ const baseWorkflow =
670
+ direct?.workflow ?? allWorkflows(discoverWorkflows(cwd)).find((candidate) => candidate.name === manifest.workflow);
671
+ if (!baseWorkflow) throw new Error(`Workflow '${manifest.workflow ?? ""}' not found.`);
672
+ debugLog(`[background-runner] workflow=${baseWorkflow.name}`);
673
+ const workflow = expandParallelResearchWorkflow(baseWorkflow, cwd);
674
+ debugLog(`[background-runner] loading config`);
675
+ const loadedConfig = loadConfig(cwd);
676
+ const runConfig =
677
+ manifest.runConfig && typeof manifest.runConfig === "object" && !Array.isArray(manifest.runConfig)
678
+ ? (manifest.runConfig as typeof loadedConfig.config)
679
+ : loadedConfig.config;
680
+ const runtime = manifest.runtimeResolution
681
+ ? {
682
+ kind: manifest.runtimeResolution.kind,
683
+ requestedMode: manifest.runtimeResolution.requestedMode,
684
+ available: manifest.runtimeResolution.available,
685
+ fallback: manifest.runtimeResolution.fallback,
686
+ steer: manifest.runtimeResolution.kind === "live-session",
687
+ resume: manifest.runtimeResolution.kind === "live-session",
688
+ liveToolActivity: manifest.runtimeResolution.kind === "live-session",
689
+ transcript: manifest.runtimeResolution.kind !== "scaffold",
690
+ reason: manifest.runtimeResolution.reason,
691
+ safety: manifest.runtimeResolution.safety,
692
+ }
693
+ : await resolveCrewRuntime(runConfig);
694
+ const runtimeResolution = manifest.runtimeResolution ?? runtimeResolutionState(runtime);
695
+ manifest = {
696
+ ...manifest,
697
+ runtimeResolution,
698
+ runConfig,
699
+ updatedAt: new Date().toISOString(),
700
+ };
701
+ await saveRunManifestAsync(manifest);
702
+ appendEvent(manifest.eventsPath, {
703
+ type: "runtime.resolved",
704
+ runId: manifest.runId,
705
+ message: `Runtime resolved: ${runtime.kind} safety=${runtime.safety}`,
706
+ data: { runtimeResolution, async: true },
707
+ });
708
+ if (runtime.safety === "blocked")
709
+ throw new Error(runtime.reason ?? "Child worker execution is disabled; refusing to create no-op scaffold subagents.");
710
+ const executeWorkers = runtime.kind !== "scaffold";
711
+ // Use ownerSessionId for workspaceId to ensure agents are only visible to the session that spawned them.
712
+ // manifest.cwd would cause cross-session visibility since all sessions share the same project directory.
713
+ // Mark this as background mode so task-runner writes events to background.log for debugging.
714
+ process.env.PI_CREW_BACKGROUND_MODE = "1";
715
+ // BUG #17: Keep-alive interval (NOT unref'd) prevents event loop from exiting
716
+ // during jiti compilation of team-runner.ts. Without this, the event loop
717
+ // can drain when import() blocks, causing the process to exit prematurely.
718
+ // NOTE: abortController is already created above (before heartbeat/interrupt guard start)
719
+ // so it is available here and its signal is passed through to executeTeamRun → child-pi.
720
+
721
+ debugLog(`[background-runner] dispatching runKind=${manifest.runKind ?? "team-run"}`);
722
+ try {
723
+ // Fix round-4: goal-loop/dynamic-workflow handled by the short-circuit above.
724
+ // This switch now only carries the traditional team-run path.
725
+ switch (manifest.runKind ?? "team-run") {
726
+ default: {
727
+ // Existing "team-run" path — unchanged behavior.
728
+ // Forward budget fields from manifest (set by team-tool/run.ts
729
+ // from params.budgetTotal/etc.) so the team-runner's
730
+ // checkPerTaskBudget guard actually arms.
731
+ result = await executeTeamRun({
732
+ manifest,
733
+ tasks,
734
+ team,
735
+ workflow,
736
+ agents,
737
+ executeWorkers,
738
+ limits: runConfig.limits,
739
+ runtime,
740
+ runtimeConfig: runConfig.runtime,
741
+ skillOverride: manifest.skillOverride,
742
+ reliability: runConfig.reliability,
743
+ workspaceId: manifest.ownerSessionId ?? manifest.cwd,
744
+ signal: abortController.signal,
745
+ ...(manifest.budgetTotal !== undefined ? { budgetTotal: manifest.budgetTotal } : {}),
746
+ ...(manifest.budgetWarning !== undefined ? { budgetWarning: manifest.budgetWarning } : {}),
747
+ ...(manifest.budgetAbort !== undefined ? { budgetAbort: manifest.budgetAbort } : {}),
748
+ ...(manifest.budgetUnlimited !== undefined ? { budgetUnlimited: manifest.budgetUnlimited } : {}),
749
+ });
750
+ break;
751
+ }
752
+ }
753
+ console.log(`[background-runner] executeTeamRun returned, status=${result.manifest.status}`);
754
+ } catch (execError) {
755
+ console.log(`[background-runner] executeTeamRun THREW: ${errorMessage(execError)}`);
756
+ console.log(`[background-runner] stack: ${execError instanceof Error ? execError.stack : "N/A"}`);
757
+ throw execError;
758
+ }
759
+ } // close if (!earlyResult) — team-run setup+execute done; earlyResult path skips to here
760
+ manifest = result!.manifest;
761
+ tasks = result!.tasks;
762
+ appendEvent(manifest.eventsPath, {
763
+ type: "async.completed",
764
+ runId: manifest.runId,
765
+ data: { status: manifest.status, tasks: tasks.length },
766
+ });
767
+ console.log(`[background-runner] async.completed written, status=${manifest.status}`);
768
+ if (manifest.status === "failed" || manifest.status === "cancelled" || manifest.status === "blocked") process.exitCode = 1;
769
+ } catch (error) {
770
+ // Terminate live agents on failure too — agents are done when the run fails
771
+ try {
772
+ const loaded = withRunLockSync(manifest, () => loadRunManifestById(cwd, runId), { staleMs: 30_000 }); // Use withRunLockSync to prevent race with concurrent writers (e.g., stale reconciler)
773
+ // between the read and the subsequent save.
774
+ const manifestToUse = loaded?.manifest ?? manifest;
775
+ if (manifestToUse) {
776
+ // LAZY: live-agent-manager only needed on failure cleanup path; avoid module load at hot path.
777
+ const { terminateLiveAgentsForRun } = await import("./live-agent-manager.ts");
778
+ void terminateLiveAgentsForRun(manifestToUse.runId, "failed", appendEvent, manifestToUse.eventsPath).catch((error) =>
779
+ logInternalError("background-runner.terminate", error, `runId=${manifestToUse.runId}`),
780
+ );
781
+ }
782
+ } catch {
783
+ /* best-effort */
784
+ }
785
+ const message = errorMessage(error);
786
+ manifest = updateRunStatus(manifest, "failed", message);
787
+ appendEvent(manifest.eventsPath, {
788
+ type: "async.failed",
789
+ runId: manifest.runId,
790
+ message,
791
+ });
792
+ process.exitCode = 1;
793
+ console.log(`[background-runner] catch block, error=${errorMessage(error)}`);
794
+ } finally {
795
+ // FIX Issue #4: Use shared runCleanup() function for consistent cleanup
796
+ // across all exit paths (normal, unhandled rejection, main() exception).
797
+ // FIX Issue #1: Wrap runCleanup in try/catch to ensure process.exit(1)
798
+ // is called even if runCleanup throws unexpectedly.
799
+ try {
800
+ runCleanup(
801
+ stopInterruptGuard,
802
+ stopParentGuard,
803
+ stopHeartbeat,
804
+ keepAlive,
805
+ watchdogTimer,
806
+ exitDueToRejection,
807
+ manifest.eventsPath,
808
+ );
809
+ } catch (cleanupError) {
810
+ console.error(`[background-runner] runCleanup threw: ${errorMessage(cleanupError)}`);
811
+ }
812
+ // NOTE: If exitDueToRejection was set, runCleanup() already called process.exit(1)
813
+ // so this finally block never continues past that point.
814
+ }
815
+ }
816
+
817
+ // FIX Issue #1: Restructure so the finally block (which calls runCleanup) ALWAYS
818
+ // runs and decides when to exit. The old pattern: await main().catch((err) =>
819
+ // { process.exit(1); }) bypassed the finally block because .catch() intercepted
820
+ // the rejection and called process.exit(1) directly. If exitDueToRejection was
821
+ // already true, the finally called process.exit(1) first and .catch() was never
822
+ // reached. If exitDueToRejection was false (main() threw but unhandled rejection
823
+ // guard didn't fire), .catch() ran instead of the finally block doing the exit.
824
+ // New pattern: move await main() inside main() itself, wrapped in try/catch that
825
+ // sets exitDueToRejection so the finally block exits with code 1 after cleanup.
826
+ try {
827
+ await main();
828
+ } catch (err) {
829
+ console.error(`[background-runner] DEBUG: main() uncaught: ${errorMessage(err)}`);
830
+ // FIX Issue #1: Set the flag so the finally block's runCleanup() call
831
+ // will trigger process.exit(1) after cleanup completes. Previously this
832
+ // called process.exit(1) directly, bypassing the finally block and leaving
833
+ // orphaned child processes.
834
+ exitDueToRejection = true;
835
+ // FIX: Call stopParentGuard directly here as a safety net in case the
836
+ // finally block (which calls runCleanup→stopParentGuard) does not complete.
837
+ // This ensures the parent guard is stopped in ALL exit paths: normal
838
+ // completion, unhandled rejection, and fatal errors.
839
+ stopParentGuard();
840
+ }