pi-crew 0.9.51 → 0.9.52

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 (610) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +216 -20
  3. package/dist/build-meta.json +2090 -1638
  4. package/dist/index.mjs +18057 -17119
  5. package/docs/actions-reference.md +431 -1
  6. package/package.json +19 -9
  7. package/schema.json +41 -0
  8. package/scripts/check-bundle-size.mjs +38 -0
  9. package/scripts/test-runner.mjs +11 -1
  10. package/dist/index.mjs.map +0 -7
  11. package/docs/FEATURE_INTAKE.md +0 -126
  12. package/docs/HARNESS.md +0 -87
  13. package/docs/HARNESS_BACKLOG.md +0 -89
  14. package/docs/PROJECT_REVIEW.md +0 -270
  15. package/docs/PROJECT_REVIEW_FIXES.md +0 -342
  16. package/docs/PROJECT_REVIEW_ROUND4.md +0 -156
  17. package/docs/PROJECT_REVIEW_ROUND5.md +0 -86
  18. package/docs/REVIEW-FINDINGS-2026-06 +0 -357
  19. package/docs/REVIEW-FINDINGS-2026-07-CORE.md +0 -139
  20. package/docs/REVIEW-FINDINGS-2026-07.md +0 -125
  21. package/docs/TEST_MATRIX.md +0 -51
  22. package/docs/archive/README.md +0 -91
  23. package/docs/archive/followup-review-round3-2026-05-12.md +0 -342
  24. package/docs/archive/followup-review-round4-2026-05-13.md +0 -107
  25. package/docs/archive/pi-crew-bugs.md +0 -961
  26. package/docs/archive/pi-crew-test-final.md +0 -120
  27. package/docs/archive/pi-crew-test-results.md +0 -260
  28. package/docs/archive/pi-crew-test-round2.md +0 -136
  29. package/docs/archive/pi-crew-test-round4.md +0 -100
  30. package/docs/archive/pi-crew-test-round5.md +0 -70
  31. package/docs/archive/pi-crew-test-round6.md +0 -110
  32. package/docs/archive/pi-crew-v0.5.10-audit-fix-plan.md +0 -60
  33. package/docs/archive/pi-crew-v0.5.11-audit-fix-plan.md +0 -92
  34. package/docs/archive/pi-crew-v0.5.12-audit-fix-plan.md +0 -76
  35. package/docs/archive/pi-crew-v0.5.13-audit-fix-plan.md +0 -75
  36. package/docs/archive/pi-crew-v0.5.14-audit-fix-plan.md +0 -75
  37. package/docs/archive/pi-crew-v0.5.16-audit-fix-plan.md +0 -35
  38. package/docs/archive/pi-crew-v0.5.17-audit-fix-plan.md +0 -80
  39. package/docs/archive/pi-crew-v0.5.5-audit-fix-plan.md +0 -133
  40. package/docs/archive/pi-crew-v0.5.9-audit-fix-plan.md +0 -88
  41. package/docs/archive/pi-mono-opportunities.md +0 -969
  42. package/docs/archive/pi-mono-review.md +0 -291
  43. package/docs/archive/pi-subagent4-comparison.md +0 -261
  44. package/docs/archive/pi-subagents3-deep-analysis.md +0 -508
  45. package/docs/bugs/bug-021-notification-badge-counter-misleading.md +0 -293
  46. package/docs/bugs/bug-023-chain-windows-path-resolution.md +0 -106
  47. package/docs/bugs/bug-quota-display-truncation.md +0 -223
  48. package/docs/bugs/cross-session-notification-leakage.md +0 -82
  49. package/docs/code-review-2026-05-11.md +0 -592
  50. package/docs/coding-agent-optimization.md +0 -268
  51. package/docs/comparison-pi-subagents-vs-pi-crew.md +0 -303
  52. package/docs/decisions/0001-durable-state.md +0 -41
  53. package/docs/decisions/0002-child-process-for-async.md +0 -42
  54. package/docs/decisions/0003-depth-guard.md +0 -36
  55. package/docs/decisions/0004-execfile-over-exec.md +0 -34
  56. package/docs/decisions/0005-no-parameter-properties.md +0 -49
  57. package/docs/decisions/0006-publish-bundled-esm.md +0 -63
  58. package/docs/decisions/0007-active-run-binary-index.md +0 -54
  59. package/docs/decisions/0008-child-pi-warm-pool.md +0 -61
  60. package/docs/decisions/2026-07-21-broker-phase4-default-on.md +0 -77
  61. package/docs/decisions/2026-07-21-broker-windows-perms.md +0 -91
  62. package/docs/decisions/2026-07-22-broker-phase4-gated-on.md +0 -99
  63. package/docs/decisions/2026-07-24-oidc-trusted-publishing.md +0 -112
  64. package/docs/decisions/2026-07-26-c6-mascot-visibility-not-wired.md +0 -84
  65. package/docs/decisions/README.md +0 -26
  66. package/docs/deep-review-report.md +0 -384
  67. package/docs/distillation/cybersecurity-patterns.md +0 -294
  68. package/docs/feature-analysis-subagent4.md +0 -305
  69. package/docs/fix-plan-disabletools-exit-null.md +0 -219
  70. package/docs/fixes/BATCH_A_H1_H2.md +0 -86
  71. package/docs/fixes/bug-006-foreground-cancel-concurrent.md +0 -78
  72. package/docs/fixes/bug-007-async-notifier-stale-ctx.md +0 -112
  73. package/docs/fixes/bug-008-child-process-silent-timeout.md +0 -100
  74. package/docs/fixes/bug-009-executor-yield-limit-needs-attention.md +0 -75
  75. package/docs/fixes/bug-010-child-process-api-key-filtered.md +0 -109
  76. package/docs/fixes/bug-011-spawn-pi-enoent.md +0 -92
  77. package/docs/fixes/bug-012-essential-env-stripped.md +0 -89
  78. package/docs/fixes/bug-013-background-runner-death.md +0 -84
  79. package/docs/fixes/bug-014-infinite-retry-loop-needs-attention.md +0 -82
  80. package/docs/fixes/bug-015-background-runner-sigterm.md +0 -65
  81. package/docs/fixes/bug-017-background-runner-session-shutdown.md +0 -66
  82. package/docs/fixes/bug-017-background-runner-sigkill-double-fork.md +0 -28
  83. package/docs/fixes/bug-018-child-pi-worker-stdin-hang.md +0 -61
  84. package/docs/fixes/bug-019-phantom-runs-temp-workspace.md +0 -52
  85. package/docs/fixes/bug-020-infinite-retry-loop-needs-attention.md +0 -47
  86. package/docs/fixes/v0.9.10/locks-fix-verify.md +0 -3
  87. package/docs/fixes/v0.9.10/smoke-test.md +0 -12
  88. package/docs/followup-plan-2026-05-12.md +0 -463
  89. package/docs/followup-review-2026-05-12.md +0 -297
  90. package/docs/goals.md +0 -59
  91. package/docs/implementation-plan-top3.md +0 -333
  92. package/docs/issue-29-analysis.md +0 -189
  93. package/docs/live-mailbox-runtime.md +0 -36
  94. package/docs/migration/atomic-write-v2-migration.md +0 -299
  95. package/docs/next-upgrade-roadmap.md +0 -808
  96. package/docs/oh-my-pi-research.md +0 -509
  97. package/docs/optimization-plan-2026-07.md +0 -366
  98. package/docs/optimization-plan.md +0 -644
  99. package/docs/patterns/command-agent-skill.md +0 -71
  100. package/docs/perf/baseline-2026-05.md +0 -113
  101. package/docs/perf/final-report-2026-05.md +0 -206
  102. package/docs/perf/optimization-plan-2026-07-verified.md +0 -396
  103. package/docs/perf/performance-audit-report-2026-07.md +0 -948
  104. package/docs/perf/performance-review-2026-07.md +0 -287
  105. package/docs/perf/sprint-1-report.md +0 -71
  106. package/docs/perf/sprint-2-report.md +0 -81
  107. package/docs/perf/sprint-2.5-report.md +0 -53
  108. package/docs/perf/sprint-3-report.md +0 -36
  109. package/docs/perf/sprint-4-report.md +0 -47
  110. package/docs/perf/sprint-5-report.md +0 -51
  111. package/docs/perf/sprint-6-report.md +0 -94
  112. package/docs/perf/sprint-7-report.md +0 -74
  113. package/docs/perf/upgrade-plan-2026-05.md +0 -147
  114. package/docs/performance-optimization-execution-plan.md +0 -520
  115. package/docs/phase4-triage.md +0 -58
  116. package/docs/pi-crew-investigation-report.md +0 -411
  117. package/docs/product/README.md +0 -31
  118. package/docs/product/platform.md +0 -27
  119. package/docs/product/runtime-safety.md +0 -37
  120. package/docs/product/team-run.md +0 -39
  121. package/docs/product/team-tool.md +0 -37
  122. package/docs/runtime-analysis-child-vs-live.md +0 -171
  123. package/docs/runtime-migration-in-process-analysis.md +0 -250
  124. package/docs/skills/REFERENCE.md +0 -138
  125. package/docs/stories/README.md +0 -32
  126. package/docs/stories/US-DEPS-major-upgrade.md +0 -62
  127. package/docs/stories/backlog.md +0 -36
  128. package/docs/superpowers/plans/2026-06-09-fallow-patterns-adoption.md +0 -1270
  129. package/docs/templates/decision.md +0 -27
  130. package/docs/templates/story.md +0 -44
  131. package/docs/templates/validation-report.md +0 -32
  132. package/docs/ui-optimization-plan.md +0 -447
  133. package/src/adapters/claude-adapter.ts +0 -23
  134. package/src/adapters/codex-adapter.ts +0 -21
  135. package/src/adapters/cursor-adapter.ts +0 -17
  136. package/src/adapters/export-util.ts +0 -143
  137. package/src/adapters/index.ts +0 -15
  138. package/src/adapters/registry.ts +0 -18
  139. package/src/adapters/types.ts +0 -23
  140. package/src/agents/agent-config.ts +0 -194
  141. package/src/agents/agent-search.ts +0 -98
  142. package/src/agents/agent-serializer.ts +0 -38
  143. package/src/agents/discover-agents.ts +0 -623
  144. package/src/benchmark/benchmark-runner.ts +0 -313
  145. package/src/benchmark/feedback-loop.ts +0 -73
  146. package/src/config/config.ts +0 -1269
  147. package/src/config/defaults.ts +0 -193
  148. package/src/config/drift-detector.ts +0 -290
  149. package/src/config/markers.ts +0 -330
  150. package/src/config/resilient-parser.ts +0 -117
  151. package/src/config/role-tools.ts +0 -118
  152. package/src/config/suggestions.ts +0 -75
  153. package/src/config/types.ts +0 -278
  154. package/src/errors.ts +0 -194
  155. package/src/extension/action-suggestions.ts +0 -117
  156. package/src/extension/async-notifier.ts +0 -179
  157. package/src/extension/autonomous-policy.ts +0 -209
  158. package/src/extension/command-completions.ts +0 -120
  159. package/src/extension/context-status-injection.ts +0 -185
  160. package/src/extension/crew-autocomplete.ts +0 -131
  161. package/src/extension/crew-cleanup.ts +0 -168
  162. package/src/extension/crew-input-router.ts +0 -93
  163. package/src/extension/crew-shortcuts.ts +0 -87
  164. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  165. package/src/extension/crew-vibes/config.ts +0 -195
  166. package/src/extension/crew-vibes/figures.ts +0 -101
  167. package/src/extension/crew-vibes/font-detect.ts +0 -71
  168. package/src/extension/crew-vibes/footer.ts +0 -292
  169. package/src/extension/crew-vibes/index.ts +0 -432
  170. package/src/extension/crew-vibes/provider-usage.ts +0 -396
  171. package/src/extension/crew-vibes/render.ts +0 -206
  172. package/src/extension/crew-vibes/speed.ts +0 -286
  173. package/src/extension/cross-extension-rpc.ts +0 -350
  174. package/src/extension/help.ts +0 -62
  175. package/src/extension/import-index.ts +0 -74
  176. package/src/extension/knowledge-injection.ts +0 -402
  177. package/src/extension/management.ts +0 -571
  178. package/src/extension/message-renderers.ts +0 -108
  179. package/src/extension/notification-router.ts +0 -152
  180. package/src/extension/notification-sink.ts +0 -54
  181. package/src/extension/pi-api.ts +0 -56
  182. package/src/extension/plan-orchestrate.ts +0 -302
  183. package/src/extension/project-init.ts +0 -170
  184. package/src/extension/register.ts +0 -113
  185. package/src/extension/registration/artifact-cleanup.ts +0 -20
  186. package/src/extension/registration/command-registration.ts +0 -58
  187. package/src/extension/registration/command-utils.ts +0 -58
  188. package/src/extension/registration/commands.ts +0 -1228
  189. package/src/extension/registration/compaction-guard.ts +0 -333
  190. package/src/extension/registration/context-builder.ts +0 -135
  191. package/src/extension/registration/crash-recovery-cache.ts +0 -54
  192. package/src/extension/registration/foreground-run-controller.ts +0 -238
  193. package/src/extension/registration/hook-registration.ts +0 -119
  194. package/src/extension/registration/lazy-configurers.ts +0 -124
  195. package/src/extension/registration/lifecycle-handlers.ts +0 -923
  196. package/src/extension/registration/lifecycle.ts +0 -259
  197. package/src/extension/registration/observability.ts +0 -322
  198. package/src/extension/registration/registration-types.ts +0 -158
  199. package/src/extension/registration/runtime-cleanup.ts +0 -230
  200. package/src/extension/registration/subagent-helpers.ts +0 -125
  201. package/src/extension/registration/subagent-manager-setup.ts +0 -330
  202. package/src/extension/registration/subagent-tools.ts +0 -456
  203. package/src/extension/registration/team-tool.ts +0 -220
  204. package/src/extension/registration/tool-registration.ts +0 -50
  205. package/src/extension/registration/ui.ts +0 -172
  206. package/src/extension/registration/viewers.ts +0 -121
  207. package/src/extension/registration/wire-cross-extension.ts +0 -37
  208. package/src/extension/result-watcher.ts +0 -139
  209. package/src/extension/rpc-hmac.ts +0 -256
  210. package/src/extension/run-bundle-schema.ts +0 -104
  211. package/src/extension/run-export.ts +0 -97
  212. package/src/extension/run-import.ts +0 -168
  213. package/src/extension/run-index.ts +0 -131
  214. package/src/extension/run-maintenance.ts +0 -190
  215. package/src/extension/session-summary.ts +0 -18
  216. package/src/extension/team-manager-command.ts +0 -153
  217. package/src/extension/team-onboard.ts +0 -177
  218. package/src/extension/team-recommendation.ts +0 -288
  219. package/src/extension/team-tool/anchor.ts +0 -172
  220. package/src/extension/team-tool/api.ts +0 -1244
  221. package/src/extension/team-tool/auto-summarize.ts +0 -142
  222. package/src/extension/team-tool/cache-control.ts +0 -19
  223. package/src/extension/team-tool/cancel.ts +0 -337
  224. package/src/extension/team-tool/chain-dispatch.ts +0 -95
  225. package/src/extension/team-tool/chain-executor.ts +0 -379
  226. package/src/extension/team-tool/config-patch.ts +0 -50
  227. package/src/extension/team-tool/context.ts +0 -149
  228. package/src/extension/team-tool/destructive-gate.ts +0 -52
  229. package/src/extension/team-tool/doctor.ts +0 -431
  230. package/src/extension/team-tool/explain.ts +0 -282
  231. package/src/extension/team-tool/failure-patterns.ts +0 -118
  232. package/src/extension/team-tool/goal-wrap.ts +0 -330
  233. package/src/extension/team-tool/goal.ts +0 -556
  234. package/src/extension/team-tool/handle-schedule.ts +0 -332
  235. package/src/extension/team-tool/handle-settings.ts +0 -520
  236. package/src/extension/team-tool/health-monitor.ts +0 -481
  237. package/src/extension/team-tool/inspect.ts +0 -88
  238. package/src/extension/team-tool/intent-policy.ts +0 -45
  239. package/src/extension/team-tool/lifecycle-actions.ts +0 -615
  240. package/src/extension/team-tool/orchestrate.ts +0 -98
  241. package/src/extension/team-tool/parallel-dispatch.ts +0 -183
  242. package/src/extension/team-tool/plan.ts +0 -50
  243. package/src/extension/team-tool/respond.ts +0 -150
  244. package/src/extension/team-tool/run-not-found.ts +0 -49
  245. package/src/extension/team-tool/run.ts +0 -1035
  246. package/src/extension/team-tool/status.ts +0 -260
  247. package/src/extension/team-tool/workflow-manage.ts +0 -261
  248. package/src/extension/team-tool-types.ts +0 -26
  249. package/src/extension/team-tool.ts +0 -1116
  250. package/src/extension/tool-result.ts +0 -16
  251. package/src/extension/validate-resources.ts +0 -108
  252. package/src/hooks/registry.ts +0 -200
  253. package/src/hooks/types.ts +0 -69
  254. package/src/i18n.ts +0 -212
  255. package/src/observability/correlation.ts +0 -50
  256. package/src/observability/event-bus.ts +0 -86
  257. package/src/observability/event-to-metric.ts +0 -170
  258. package/src/observability/exporters/adapter.ts +0 -27
  259. package/src/observability/exporters/otlp-exporter.ts +0 -356
  260. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  261. package/src/observability/metric-registry.ts +0 -100
  262. package/src/observability/metric-retention.ts +0 -64
  263. package/src/observability/metric-sink.ts +0 -99
  264. package/src/observability/metrics-primitives.ts +0 -219
  265. package/src/plugins/plugin-define.ts +0 -6
  266. package/src/plugins/plugin-registry.ts +0 -32
  267. package/src/plugins/plugins/index.ts +0 -3
  268. package/src/plugins/plugins/nextjs.ts +0 -19
  269. package/src/plugins/plugins/vite.ts +0 -10
  270. package/src/plugins/plugins/vitest.ts +0 -9
  271. package/src/prompt/prompt-runtime.ts +0 -380
  272. package/src/runtime/adaptive-plan.ts +0 -563
  273. package/src/runtime/agent-control.ts +0 -215
  274. package/src/runtime/agent-memory.ts +0 -81
  275. package/src/runtime/agent-observability.ts +0 -122
  276. package/src/runtime/anchor-manager.ts +0 -475
  277. package/src/runtime/async-marker.ts +0 -32
  278. package/src/runtime/async-runner.ts +0 -381
  279. package/src/runtime/attention-events.ts +0 -28
  280. package/src/runtime/auto-summarize.ts +0 -344
  281. package/src/runtime/background-runner.ts +0 -837
  282. package/src/runtime/batch-barrier.ts +0 -147
  283. package/src/runtime/broker-issuer.ts +0 -37
  284. package/src/runtime/cancellation-token.ts +0 -99
  285. package/src/runtime/cancellation.ts +0 -99
  286. package/src/runtime/capability-inventory.ts +0 -137
  287. package/src/runtime/chain-parser.ts +0 -237
  288. package/src/runtime/chain-runner.ts +0 -606
  289. package/src/runtime/checkpoint.ts +0 -291
  290. package/src/runtime/child-pi-constants.ts +0 -42
  291. package/src/runtime/child-pi-kill.ts +0 -180
  292. package/src/runtime/child-pi-pool.ts +0 -68
  293. package/src/runtime/child-pi-spawn.ts +0 -287
  294. package/src/runtime/child-pi-steering.ts +0 -128
  295. package/src/runtime/child-pi-streams.ts +0 -296
  296. package/src/runtime/child-pi-transcript.ts +0 -169
  297. package/src/runtime/child-pi.ts +0 -1105
  298. package/src/runtime/coalesce-tasks.ts +0 -268
  299. package/src/runtime/code-summary.ts +0 -292
  300. package/src/runtime/command-trace.ts +0 -105
  301. package/src/runtime/compact-pipeline.ts +0 -56
  302. package/src/runtime/compact-stages/ansi-strip-stage.ts +0 -25
  303. package/src/runtime/compact-stages/blank-collapse-stage.ts +0 -31
  304. package/src/runtime/compact-stages/deduplicate-stage.ts +0 -34
  305. package/src/runtime/compact-stages/head-snap-stage.ts +0 -57
  306. package/src/runtime/compact-stages/index.ts +0 -23
  307. package/src/runtime/compact-stages/tail-capture-stage.ts +0 -77
  308. package/src/runtime/compact-stages/truncation-stage.ts +0 -74
  309. package/src/runtime/compaction-summary.ts +0 -278
  310. package/src/runtime/completion-guard.ts +0 -207
  311. package/src/runtime/concurrency.ts +0 -58
  312. package/src/runtime/crash-classification.ts +0 -229
  313. package/src/runtime/crash-recovery.ts +0 -577
  314. package/src/runtime/crew-agent-records.ts +0 -593
  315. package/src/runtime/crew-agent-runtime.ts +0 -62
  316. package/src/runtime/crew-broker-child.ts +0 -88
  317. package/src/runtime/crew-broker-client.ts +0 -673
  318. package/src/runtime/crew-broker-tokens.ts +0 -84
  319. package/src/runtime/crew-broker.ts +0 -1276
  320. package/src/runtime/crew-hooks.ts +0 -227
  321. package/src/runtime/cross-extension-rpc.ts +0 -143
  322. package/src/runtime/custom-tools/irc-tool.ts +0 -282
  323. package/src/runtime/custom-tools/submit-result-tool.ts +0 -102
  324. package/src/runtime/deadletter.ts +0 -47
  325. package/src/runtime/delivery-coordinator.ts +0 -211
  326. package/src/runtime/delta-conflict.ts +0 -348
  327. package/src/runtime/deterministic-ast.ts +0 -161
  328. package/src/runtime/diagnostic-export.ts +0 -171
  329. package/src/runtime/direct-run.ts +0 -45
  330. package/src/runtime/dwf-state-store.ts +0 -102
  331. package/src/runtime/dynamic-workflow-context.ts +0 -1016
  332. package/src/runtime/dynamic-workflow-runner.ts +0 -310
  333. package/src/runtime/effectiveness.ts +0 -90
  334. package/src/runtime/errors/crew-errors.ts +0 -162
  335. package/src/runtime/event-stream-bridge.ts +0 -98
  336. package/src/runtime/foreground-control.ts +0 -193
  337. package/src/runtime/foreground-watchdog.ts +0 -132
  338. package/src/runtime/global-worker-cap.ts +0 -96
  339. package/src/runtime/goal-achievement.ts +0 -148
  340. package/src/runtime/goal-evaluator.ts +0 -361
  341. package/src/runtime/goal-loop-runner.ts +0 -828
  342. package/src/runtime/goal-state-store.ts +0 -219
  343. package/src/runtime/green-contract.ts +0 -55
  344. package/src/runtime/group-join.ts +0 -267
  345. package/src/runtime/handoff-manager.ts +0 -598
  346. package/src/runtime/heartbeat-gradient.ts +0 -36
  347. package/src/runtime/heartbeat-watcher.ts +0 -239
  348. package/src/runtime/hidden-handoff.ts +0 -407
  349. package/src/runtime/important-line-classifier.ts +0 -140
  350. package/src/runtime/intercom-bridge.ts +0 -187
  351. package/src/runtime/iteration-hooks.ts +0 -305
  352. package/src/runtime/live-agent-control.ts +0 -136
  353. package/src/runtime/live-agent-manager.ts +0 -704
  354. package/src/runtime/live-control-realtime.ts +0 -56
  355. package/src/runtime/live-extension-bridge.ts +0 -148
  356. package/src/runtime/live-irc.ts +0 -97
  357. package/src/runtime/live-session-health.ts +0 -108
  358. package/src/runtime/live-session-runtime.ts +0 -1139
  359. package/src/runtime/loop-gates.ts +0 -128
  360. package/src/runtime/manifest-cache.ts +0 -375
  361. package/src/runtime/mcp-proxy.ts +0 -105
  362. package/src/runtime/metric-parser.ts +0 -36
  363. package/src/runtime/model-fallback.ts +0 -409
  364. package/src/runtime/model-resolver.ts +0 -126
  365. package/src/runtime/model-scope.ts +0 -158
  366. package/src/runtime/orphan-worker-registry.ts +0 -465
  367. package/src/runtime/output-validator.ts +0 -202
  368. package/src/runtime/overflow-recovery.ts +0 -206
  369. package/src/runtime/parallel-research.ts +0 -68
  370. package/src/runtime/parallel-utils.ts +0 -160
  371. package/src/runtime/parent-guard.ts +0 -134
  372. package/src/runtime/path-overlap.ts +0 -150
  373. package/src/runtime/peer-dep.ts +0 -292
  374. package/src/runtime/per-write-validator.ts +0 -181
  375. package/src/runtime/phase-progress.ts +0 -217
  376. package/src/runtime/phase-tracker.ts +0 -385
  377. package/src/runtime/pi-args.ts +0 -655
  378. package/src/runtime/pi-json-output.ts +0 -170
  379. package/src/runtime/pi-spawn.ts +0 -273
  380. package/src/runtime/pipeline-runner.ts +0 -523
  381. package/src/runtime/plan-templates.ts +0 -201
  382. package/src/runtime/policy-engine.ts +0 -115
  383. package/src/runtime/post-checks.ts +0 -142
  384. package/src/runtime/post-exit-stdio-guard.ts +0 -104
  385. package/src/runtime/process-lifecycle.ts +0 -491
  386. package/src/runtime/process-status.ts +0 -154
  387. package/src/runtime/progress-event-coalescer.ts +0 -44
  388. package/src/runtime/progress-tracker.ts +0 -124
  389. package/src/runtime/prose-compressor.ts +0 -162
  390. package/src/runtime/recovery-recipes.ts +0 -203
  391. package/src/runtime/replace.ts +0 -570
  392. package/src/runtime/resilient-edit.ts +0 -153
  393. package/src/runtime/result-extractor.ts +0 -213
  394. package/src/runtime/retry-executor.ts +0 -100
  395. package/src/runtime/retry-runner.ts +0 -336
  396. package/src/runtime/role-permission.ts +0 -59
  397. package/src/runtime/run-coalesced-task-group.ts +0 -308
  398. package/src/runtime/run-drift.ts +0 -219
  399. package/src/runtime/run-tracker.ts +0 -116
  400. package/src/runtime/runtime-policy.ts +0 -29
  401. package/src/runtime/runtime-resolver.ts +0 -172
  402. package/src/runtime/runtime-warmup.ts +0 -160
  403. package/src/runtime/scheduler.ts +0 -353
  404. package/src/runtime/semaphore.ts +0 -141
  405. package/src/runtime/sensitive-paths.ts +0 -93
  406. package/src/runtime/session-resources.ts +0 -25
  407. package/src/runtime/session-snapshot.ts +0 -59
  408. package/src/runtime/session-usage.ts +0 -79
  409. package/src/runtime/settings-store.ts +0 -155
  410. package/src/runtime/sidechain-output.ts +0 -35
  411. package/src/runtime/single-agent-compose.ts +0 -84
  412. package/src/runtime/skill-effectiveness.ts +0 -524
  413. package/src/runtime/skill-instructions.ts +0 -391
  414. package/src/runtime/stale-reconciler.ts +0 -680
  415. package/src/runtime/stream-preview.ts +0 -184
  416. package/src/runtime/streaming-output.ts +0 -50
  417. package/src/runtime/subagent-manager.ts +0 -561
  418. package/src/runtime/subprocess-tool-registry.ts +0 -70
  419. package/src/runtime/supervisor-contact.ts +0 -64
  420. package/src/runtime/task-display.ts +0 -52
  421. package/src/runtime/task-graph-scheduler.ts +0 -227
  422. package/src/runtime/task-graph.ts +0 -290
  423. package/src/runtime/task-health.ts +0 -83
  424. package/src/runtime/task-id.ts +0 -161
  425. package/src/runtime/task-output-context.ts +0 -602
  426. package/src/runtime/task-packet.ts +0 -268
  427. package/src/runtime/task-quality.ts +0 -199
  428. package/src/runtime/task-runner/capabilities.ts +0 -78
  429. package/src/runtime/task-runner/context-retrieval.ts +0 -163
  430. package/src/runtime/task-runner/live-executor.ts +0 -227
  431. package/src/runtime/task-runner/output-splitter.ts +0 -152
  432. package/src/runtime/task-runner/progress.ts +0 -157
  433. package/src/runtime/task-runner/prompt-builder.ts +0 -278
  434. package/src/runtime/task-runner/prompt-pipeline.ts +0 -88
  435. package/src/runtime/task-runner/result-utils.ts +0 -16
  436. package/src/runtime/task-runner/retrieval-orchestrator.ts +0 -310
  437. package/src/runtime/task-runner/run-projection.ts +0 -125
  438. package/src/runtime/task-runner/state-helpers.ts +0 -176
  439. package/src/runtime/task-runner/tail-read.ts +0 -34
  440. package/src/runtime/task-runner.ts +0 -1420
  441. package/src/runtime/team-runner-artifacts.ts +0 -13
  442. package/src/runtime/team-runner.ts +0 -1993
  443. package/src/runtime/tool-output-pruner.ts +0 -333
  444. package/src/runtime/tool-progress.ts +0 -278
  445. package/src/runtime/usage-tracker.ts +0 -73
  446. package/src/runtime/verification-gates.ts +0 -571
  447. package/src/runtime/verification-integrity.ts +0 -105
  448. package/src/runtime/verification-worktree.ts +0 -186
  449. package/src/runtime/worker-heartbeat.ts +0 -25
  450. package/src/runtime/worker-startup.ts +0 -83
  451. package/src/runtime/workflow-state.ts +0 -195
  452. package/src/runtime/workspace-lock.ts +0 -443
  453. package/src/runtime/workspace-tree.ts +0 -312
  454. package/src/runtime/yield-handler.ts +0 -224
  455. package/src/runtime/zombie-scanner.ts +0 -298
  456. package/src/schema/config-schema.ts +0 -327
  457. package/src/schema/team-tool-schema.ts +0 -415
  458. package/src/schema/validation-types.ts +0 -159
  459. package/src/skills/discover-skills.ts +0 -197
  460. package/src/skills/skill-templates.ts +0 -456
  461. package/src/skills/validate.ts +0 -285
  462. package/src/state/active-run-registry.ts +0 -439
  463. package/src/state/artifact-store.ts +0 -176
  464. package/src/state/atomic-write.ts +0 -903
  465. package/src/state/blob-store.ts +0 -308
  466. package/src/state/contracts.ts +0 -158
  467. package/src/state/crew-init.ts +0 -269
  468. package/src/state/decision-ledger.ts +0 -345
  469. package/src/state/event-log-rotation.ts +0 -342
  470. package/src/state/event-log.ts +0 -1311
  471. package/src/state/event-reconstructor.ts +0 -229
  472. package/src/state/gitignore-manager.ts +0 -46
  473. package/src/state/health-store.ts +0 -79
  474. package/src/state/hook-instinct-bridge.ts +0 -94
  475. package/src/state/hook-integrations.ts +0 -51
  476. package/src/state/instinct-store.ts +0 -275
  477. package/src/state/jsonl-writer.ts +0 -107
  478. package/src/state/locks.ts +0 -562
  479. package/src/state/mailbox.ts +0 -916
  480. package/src/state/observation-store.ts +0 -176
  481. package/src/state/run-cache.ts +0 -193
  482. package/src/state/run-graph.ts +0 -183
  483. package/src/state/run-metrics.ts +0 -165
  484. package/src/state/schedule.ts +0 -166
  485. package/src/state/session-state-map.ts +0 -51
  486. package/src/state/state-store.ts +0 -958
  487. package/src/state/task-claims.ts +0 -61
  488. package/src/state/tiered-eval.ts +0 -480
  489. package/src/state/types-eval.ts +0 -58
  490. package/src/state/types.ts +0 -440
  491. package/src/state/usage.ts +0 -138
  492. package/src/state/worker-atomic-writer.ts +0 -194
  493. package/src/subagents/async-entry.ts +0 -1
  494. package/src/subagents/index.ts +0 -3
  495. package/src/subagents/live/control.ts +0 -1
  496. package/src/subagents/live/manager.ts +0 -1
  497. package/src/subagents/live/realtime.ts +0 -1
  498. package/src/subagents/live/session-runtime.ts +0 -1
  499. package/src/subagents/manager.ts +0 -1
  500. package/src/subagents/spawn.ts +0 -1
  501. package/src/teams/discover-teams.ts +0 -187
  502. package/src/teams/team-config.ts +0 -27
  503. package/src/teams/team-serializer.ts +0 -38
  504. package/src/tools/safe-bash-extension.ts +0 -54
  505. package/src/tools/safe-bash.ts +0 -505
  506. package/src/types/diff.d.ts +0 -18
  507. package/src/types/new-api-types.ts +0 -35
  508. package/src/ui/agent-management-overlay.ts +0 -160
  509. package/src/ui/card-colors.ts +0 -139
  510. package/src/ui/crew-footer.ts +0 -102
  511. package/src/ui/crew-select-list.ts +0 -111
  512. package/src/ui/dashboard-panes/agents-pane.ts +0 -164
  513. package/src/ui/dashboard-panes/cancellation-pane.ts +0 -66
  514. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  515. package/src/ui/dashboard-panes/health-pane.ts +0 -31
  516. package/src/ui/dashboard-panes/mailbox-pane.ts +0 -35
  517. package/src/ui/dashboard-panes/metrics-pane.ts +0 -37
  518. package/src/ui/dashboard-panes/progress-pane.ts +0 -38
  519. package/src/ui/dashboard-panes/transcript-pane.ts +0 -10
  520. package/src/ui/deploy-bundled-themes.ts +0 -71
  521. package/src/ui/dwf-phase-display.ts +0 -151
  522. package/src/ui/dynamic-border.ts +0 -35
  523. package/src/ui/heartbeat-aggregator.ts +0 -74
  524. package/src/ui/key-utils.ts +0 -42
  525. package/src/ui/keybinding-map.ts +0 -248
  526. package/src/ui/layout-primitives.ts +0 -106
  527. package/src/ui/live-conversation-overlay.ts +0 -183
  528. package/src/ui/live-duration.ts +0 -55
  529. package/src/ui/live-run-sidebar.ts +0 -293
  530. package/src/ui/loaders.ts +0 -6
  531. package/src/ui/mascot.ts +0 -449
  532. package/src/ui/overlays/agent-picker-overlay.ts +0 -65
  533. package/src/ui/overlays/confirm-overlay.ts +0 -60
  534. package/src/ui/overlays/help-overlay.ts +0 -177
  535. package/src/ui/overlays/mailbox-compose-overlay.ts +0 -181
  536. package/src/ui/overlays/mailbox-compose-preview.ts +0 -78
  537. package/src/ui/overlays/mailbox-detail-overlay.ts +0 -154
  538. package/src/ui/pi-ui-compat.ts +0 -68
  539. package/src/ui/powerbar-publisher.ts +0 -459
  540. package/src/ui/render-coalescer.ts +0 -101
  541. package/src/ui/render-diff.ts +0 -160
  542. package/src/ui/render-scheduler.ts +0 -278
  543. package/src/ui/run-action-dispatcher.ts +0 -182
  544. package/src/ui/run-dashboard.ts +0 -904
  545. package/src/ui/run-event-bus.ts +0 -381
  546. package/src/ui/run-snapshot-cache.ts +0 -1057
  547. package/src/ui/settings-overlay.ts +0 -1067
  548. package/src/ui/shared-overlay-scheduler.ts +0 -96
  549. package/src/ui/snapshot-types.ts +0 -90
  550. package/src/ui/spinner.ts +0 -17
  551. package/src/ui/status-colors.ts +0 -143
  552. package/src/ui/syntax-highlight.ts +0 -136
  553. package/src/ui/terminal-status.ts +0 -269
  554. package/src/ui/theme-adapter.ts +0 -271
  555. package/src/ui/theme-discovery.ts +0 -199
  556. package/src/ui/tool-progress-formatter.ts +0 -93
  557. package/src/ui/tool-render.ts +0 -453
  558. package/src/ui/tool-renderers/brief-mode.ts +0 -225
  559. package/src/ui/tool-renderers/index.ts +0 -726
  560. package/src/ui/transcript-cache.ts +0 -128
  561. package/src/ui/transcript-entries.ts +0 -256
  562. package/src/ui/transcript-viewer.ts +0 -424
  563. package/src/ui/widget/index.ts +0 -391
  564. package/src/ui/widget/widget-formatters.ts +0 -182
  565. package/src/ui/widget/widget-model.ts +0 -110
  566. package/src/ui/widget/widget-renderer.ts +0 -182
  567. package/src/ui/widget/widget-types.ts +0 -36
  568. package/src/utils/bm25-search.ts +0 -235
  569. package/src/utils/completion-dedupe.ts +0 -63
  570. package/src/utils/conflict-detect.ts +0 -668
  571. package/src/utils/env-allowlist.ts +0 -30
  572. package/src/utils/env-filter.ts +0 -155
  573. package/src/utils/file-coalescer.ts +0 -98
  574. package/src/utils/fingerprint.ts +0 -180
  575. package/src/utils/frontmatter.ts +0 -70
  576. package/src/utils/fs-watch.ts +0 -37
  577. package/src/utils/gh-protocol.ts +0 -556
  578. package/src/utils/git.ts +0 -260
  579. package/src/utils/guards.ts +0 -107
  580. package/src/utils/ids.ts +0 -24
  581. package/src/utils/incremental-reader.ts +0 -220
  582. package/src/utils/internal-error.ts +0 -10
  583. package/src/utils/names.ts +0 -36
  584. package/src/utils/ndjson.ts +0 -115
  585. package/src/utils/paths.ts +0 -227
  586. package/src/utils/project-detector.ts +0 -160
  587. package/src/utils/redaction.ts +0 -347
  588. package/src/utils/resolve-shell.ts +0 -36
  589. package/src/utils/run-watcher-registry.ts +0 -152
  590. package/src/utils/safe-paths.ts +0 -383
  591. package/src/utils/scan-cache.ts +0 -144
  592. package/src/utils/session-utils.ts +0 -110
  593. package/src/utils/sleep.ts +0 -54
  594. package/src/utils/socket-path.ts +0 -127
  595. package/src/utils/sse-parser.ts +0 -129
  596. package/src/utils/task-name-generator.ts +0 -337
  597. package/src/utils/timings.ts +0 -33
  598. package/src/utils/token-counter.ts +0 -200
  599. package/src/utils/visual.ts +0 -207
  600. package/src/workflows/cost-estimator.ts +0 -34
  601. package/src/workflows/discover-workflows.ts +0 -290
  602. package/src/workflows/intermediate-store.ts +0 -166
  603. package/src/workflows/preflight-validator.ts +0 -168
  604. package/src/workflows/topology-analyzer.ts +0 -203
  605. package/src/workflows/validate-workflow.ts +0 -50
  606. package/src/workflows/workflow-config.ts +0 -70
  607. package/src/workflows/workflow-serializer.ts +0 -32
  608. package/src/worktree/branch-freshness.ts +0 -112
  609. package/src/worktree/cleanup.ts +0 -341
  610. package/src/worktree/worktree-manager.ts +0 -1200
@@ -1,904 +0,0 @@
1
- import * as fs from "node:fs";
2
- import type { MetricRegistry } from "../observability/metric-registry.ts";
3
- import { readCrewAgents } from "../runtime/crew-agent-records.ts";
4
- import type { CrewAgentRecord } from "../runtime/crew-agent-runtime.ts";
5
- import { getLiveAgentContextPercent } from "../runtime/live-agent-manager.ts";
6
- import { isDisplayActiveRun, isLikelyOrphanedActiveRun } from "../runtime/process-status.ts";
7
- import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
8
- import { aggregateUsage } from "../state/usage.ts";
9
- import { readJsonFileCoalesced } from "../utils/file-coalescer.ts";
10
- import { logInternalError } from "../utils/internal-error.ts";
11
- import { resolveRealContainedPath } from "../utils/safe-paths.ts";
12
- import { pad, sanitizeLine, truncate, visibleWidth } from "../utils/visual.ts";
13
- import { renderAgentsPane } from "./dashboard-panes/agents-pane.ts";
14
- import { summarizeTerminalReason } from "./dashboard-panes/cancellation-pane.ts";
15
- import { renderHealthPane } from "./dashboard-panes/health-pane.ts";
16
- import { renderMailboxPane } from "./dashboard-panes/mailbox-pane.ts";
17
- import { renderMetricsPane } from "./dashboard-panes/metrics-pane.ts";
18
- import { renderProgressPane } from "./dashboard-panes/progress-pane.ts";
19
- import { renderTranscriptPane } from "./dashboard-panes/transcript-pane.ts";
20
- import { DynamicCrewBorder } from "./dynamic-border.ts";
21
- import { dashboardActionForKey } from "./keybinding-map.ts";
22
- import { HelpOverlay } from "./overlays/help-overlay.ts";
23
- import type { OverlaySchedulerHandle } from "./shared-overlay-scheduler.ts";
24
- import { registerOverlayScheduler } from "./shared-overlay-scheduler.ts";
25
- import type { RunSnapshotCache, RunUiSnapshot } from "./snapshot-types.ts";
26
- import { spinnerBucket, spinnerFrame } from "./spinner.ts";
27
- import { applyStatusColor, colorizeStatusGlyphs, iconForStatus, type RunStatus } from "./status-colors.ts";
28
- import type { CrewTheme } from "./theme-adapter.ts";
29
- import { asCrewTheme, subscribeThemeChange } from "./theme-adapter.ts";
30
- import { renderLines } from "./widget/widget-renderer.ts";
31
-
32
- /** S05 — wrap a pane render in try/catch so a single pane crash does not bring down the whole dashboard. */
33
- function safeRenderPane(name: string, fn: () => string[]): string[] {
34
- try {
35
- return fn();
36
- } catch (error) {
37
- const message = error instanceof Error ? error.message : String(error);
38
- logInternalError("run-dashboard", new Error(`Dashboard pane '${name}' render failed: ${message}`));
39
- return [`<error: ${name}>`];
40
- }
41
- }
42
-
43
- interface DashboardComponent {
44
- invalidate(): void;
45
- render(width: number): string[];
46
- handleInput(data: string): void;
47
- }
48
-
49
- export interface RunDashboardOptions {
50
- placement?: "center" | "right";
51
- showModel?: boolean;
52
- showTokens?: boolean;
53
- showTools?: boolean;
54
- snapshotCache?: RunSnapshotCache;
55
- runProvider?: () => TeamRunManifest[];
56
- registry?: MetricRegistry;
57
- /**
58
- * Workspace/session ID for filtering runs and live agents. When provided,
59
- * only runs with matching ownerSessionId and live agents with matching
60
- * workspaceId are shown. This ensures session isolation in the UI.
61
- */
62
- workspaceId?: string;
63
- /**
64
- * Poke the host TUI to repaint after a state change. Must be wired from
65
- * `commands.ts` (`() => requestRenderTarget(tui)`) so keypresses and event-bus
66
- * updates immediately refresh the overlay instead of waiting on the next
67
- * host tick. Without this the overlay can desync and base content (chat,
68
- * status line) can paint through stale cells.
69
- */
70
- requestRender?: () => void;
71
- }
72
-
73
- /**
74
- * Persisted per-process so that pressing `r` (reload) or closing+reopening the
75
- * dashboard within the same Pi session keeps the user on the pane they were
76
- * looking at. Resetting to "agents" on every `new RunDashboard(...)` was a
77
- * UX regression.
78
- */
79
- let lastActivePane: "agents" | "progress" | "mailbox" | "output" | "health" | "metrics" = "agents";
80
-
81
- export type RunDashboardAction =
82
- | "status"
83
- | "summary"
84
- | "artifacts"
85
- | "api"
86
- | "events"
87
- | "agents"
88
- | "agent-events"
89
- | "agent-output"
90
- | "agent-transcript"
91
- | "agent-live"
92
- | "mailbox"
93
- | "reload"
94
- | "mailbox-detail"
95
- | "health-recovery"
96
- | "health-kill-stale"
97
- | "health-diagnostic-export"
98
- | "notifications-dismiss";
99
- export interface RunDashboardSelection {
100
- runId: string;
101
- action: RunDashboardAction;
102
- }
103
-
104
- const TASK_READ_TTL_MS = 1000;
105
-
106
- /** Max run rows rendered in the dashboard run-list block (L-1 window budget). */
107
- const RUN_LIST_MAX = 8;
108
-
109
- /**
110
- * 1.10 (UI-P1-2) — short TTL for the buildSignature cache. `buildSignature`
111
- * iterates every run and calls `snapshotFor → refreshIfStale`, which can
112
- * stat multiple files per run when the TTL expires. Rendering fires several
113
- * times per second (spinner + event-bus), so we cache the computed signature
114
- * for 100ms: enough to coalesce one render burst without holding the cache
115
- * across genuinely new data (>100ms idle means a fresh signature will be
116
- * computed on the next render anyway).
117
- */
118
- const SIGNATURE_CACHE_TTL_MS = 100;
119
-
120
- /**
121
- * F-4 — a live run's snapshot is considered "possibly stale" once its
122
- * `fetchedAt` is this old. A progressing run rebuilds on every stamp change,
123
- * so an old `fetchedAt` means the manifest read has been repeatedly flaky
124
- * (the cache silently returned the previous entry).
125
- */
126
- const STALE_SNAPSHOT_MS = 15_000;
127
-
128
- /** Left-pad `value` to a fixed VISIBLE width (ANSI-aware). Used by V-1. */
129
- function padVis(value: string, width: number): string {
130
- const current = visibleWidth(value);
131
- return current >= width ? value : `${" ".repeat(width - current)}${value}`;
132
- }
133
-
134
- /**
135
- * L-1 — compute the run-list window (visible slots + which scroll indicators
136
- * render) for a given offset. Shared by `ensureRunListWindow()` and the
137
- * render loop so they ALWAYS agree and the selection can never land off-screen.
138
- */
139
- interface RunListWindow {
140
- slots: number;
141
- hasTop: boolean;
142
- hasBottom: boolean;
143
- }
144
- function runListWindow(scrollOffset: number, count: number): RunListWindow {
145
- const hasTop = scrollOffset > 0;
146
- const availNoBottom = Math.max(1, RUN_LIST_MAX - (hasTop ? 1 : 0));
147
- const hasBottom = scrollOffset + availNoBottom < count;
148
- const slots = Math.max(1, RUN_LIST_MAX - (hasTop ? 1 : 0) - (hasBottom ? 1 : 0));
149
- return { slots, hasTop, hasBottom };
150
- }
151
-
152
- function formatAge(iso: string | undefined): string | undefined {
153
- if (!iso) return undefined;
154
- const ms = Math.max(0, Date.now() - new Date(iso).getTime());
155
- if (!Number.isFinite(ms)) return undefined;
156
- if (ms < 1000) return "now";
157
- if (ms < 60_000) return `${Math.floor(ms / 1000)}s`;
158
- if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m`;
159
- return `${Math.floor(ms / 3_600_000)}h`;
160
- }
161
-
162
- function readProgressPreview(run: TeamRunManifest, maxLines = 5, snapshotCache?: RunSnapshotCache): string[] {
163
- // P0-6: prefer the snapshot's `recentOutputLines` (no disk I/O) over reading the
164
- // progress artifact on every render. The progress artifact content is captured
165
- // into the snapshot's recent events / output pipeline upstream.
166
- const snapshot = snapshotFor(run, snapshotCache);
167
- if (snapshot?.recentOutputLines?.length) {
168
- return ["Progress:", ...snapshot.recentOutputLines.slice(0, maxLines)];
169
- }
170
- if (snapshotCache) return ["Progress: (loading…)"];
171
- // Legacy fallback: tests/dev paths without a snapshot cache still read the
172
- // progress artifact directly so existing assertions keep working.
173
- const progress = [...run.artifacts].reverse().find((artifact) => artifact.kind === "progress");
174
- if (!progress) return ["Progress: (none)"];
175
- try {
176
- const progressPath = resolveRealContainedPath(run.artifactsRoot, progress.path);
177
- if (!fs.existsSync(progressPath)) return ["Progress: (none)"];
178
- return ["Progress:", ...fs.readFileSync(progressPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(0, maxLines)];
179
- } catch (error) {
180
- const message = error instanceof Error ? error.message : String(error);
181
- return [`Progress: failed to read (${message})`];
182
- }
183
- }
184
-
185
- function formatTokens(usage: UsageState | undefined): string | undefined {
186
- if (!usage) return undefined;
187
- const total = (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
188
- if (!total) return undefined;
189
- const compact = total >= 1000 ? `${(total / 1000).toFixed(total >= 10_000 ? 0 : 1)}k` : `${total}`;
190
- const parts = [`tok=${compact}`];
191
- if (usage.input) parts.push(`in=${usage.input}`);
192
- if (usage.output) parts.push(`out=${usage.output}`);
193
- if (usage.cacheRead) parts.push(`cache=${usage.cacheRead}`);
194
- if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
195
- return parts.join("/");
196
- }
197
-
198
- function snapshotFor(run: TeamRunManifest, snapshotCache?: RunSnapshotCache): RunUiSnapshot | undefined {
199
- try {
200
- return snapshotCache?.refreshIfStale(run.runId);
201
- } catch {
202
- return snapshotCache?.get(run.runId);
203
- }
204
- }
205
-
206
- function readRunTasks(run: TeamRunManifest, snapshotCache?: RunSnapshotCache): TeamTaskState[] {
207
- const snapshot = snapshotFor(run, snapshotCache);
208
- if (snapshot) return snapshot.tasks;
209
- // P0-6: when a snapshot cache is provided but hasn't populated yet, return
210
- // empty (the render loop falls back to the empty pane placeholder) instead
211
- // of reading the tasks.json file synchronously every render tick.
212
- if (snapshotCache) return [];
213
- const parse = () => {
214
- if (!fs.existsSync(run.tasksPath)) return [];
215
- const parsed = JSON.parse(fs.readFileSync(run.tasksPath, "utf-8"));
216
- return Array.isArray(parsed) ? (parsed as TeamTaskState[]) : [];
217
- };
218
- try {
219
- return readJsonFileCoalesced(run.tasksPath, TASK_READ_TTL_MS, parse);
220
- } catch {
221
- return [];
222
- }
223
- }
224
-
225
- function taskForAgent(tasks: TeamTaskState[], agent: CrewAgentRecord): TeamTaskState | undefined {
226
- return tasks.find((task) => task.id === agent.taskId);
227
- }
228
-
229
- function modelForTask(task: TeamTaskState | undefined): string | undefined {
230
- const attempts = task?.modelAttempts;
231
- if (!attempts?.length) return undefined;
232
- return attempts.find((attempt) => attempt.success)?.model ?? attempts.at(-1)?.model;
233
- }
234
-
235
- function modelForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): string | undefined {
236
- return modelForTask(task) ?? agent.model;
237
- }
238
-
239
- function usageForAgent(agent: CrewAgentRecord, task: TeamTaskState | undefined): UsageState | undefined {
240
- return task?.usage ?? agent.usage;
241
- }
242
-
243
- function agentPreviewLine(agent: CrewAgentRecord, task: TeamTaskState | undefined, options: RunDashboardOptions): string {
244
- const stats = [
245
- agent.progress?.activityState,
246
- options.showModel !== false && modelForAgent(agent, task) ? `model=${modelForAgent(agent, task)}` : undefined,
247
- options.showTokens !== false
248
- ? (formatTokens(usageForAgent(agent, task)) ??
249
- (agent.progress?.tokens !== undefined ? `tok=${agent.progress.tokens}` : undefined))
250
- : undefined,
251
- options.showTools !== false && agent.progress?.currentTool ? `tool=${agent.progress.currentTool}` : undefined,
252
- options.showTools !== false && agent.toolUses !== undefined ? `${agent.toolUses} tools` : undefined,
253
- agent.progress?.turns !== undefined ? `${agent.progress.turns} turns` : undefined,
254
- agent.progress?.failedTool ? `failedTool=${agent.progress.failedTool}` : undefined,
255
- agent.startedAt ? `age=${formatAge(agent.completedAt ?? agent.startedAt)}` : undefined,
256
- ].filter((part): part is string => Boolean(part));
257
- const recent = agent.progress?.recentOutput?.at(-1);
258
- const icon = iconForStatus(agent.status, {
259
- runningGlyph: spinnerFrame(agent.taskId),
260
- });
261
- return sanitizeLine(
262
- `Agent: ${icon} ${agent.taskId} ${agent.role}->${agent.agent}${stats.length ? ` · ${stats.join(" · ")}` : ""}${recent ? ` ⎿ ${recent}` : ""}`,
263
- );
264
- }
265
-
266
- function readAgentPreview(run: TeamRunManifest, maxLines = 5, options: RunDashboardOptions = {}): string[] {
267
- try {
268
- const snapshot = snapshotFor(run, options.snapshotCache);
269
- // P0-6: when a snapshot cache is provided but hasn't populated yet, return
270
- // the empty-pane placeholder instead of calling `readCrewAgents` (disk I/O)
271
- // on every render tick. Legacy callers (no cache) keep the disk-read path
272
- // so existing unit tests continue to assert against concrete agent data.
273
- const agents = snapshot?.agents ?? (options.snapshotCache ? [] : readCrewAgents(run));
274
- const tasks = snapshot?.tasks ?? readRunTasks(run, options.snapshotCache);
275
- if (!agents.length) return ["Agents: (none)"];
276
- const totals = tasks.reduce(
277
- (acc, task) => {
278
- acc.input += task.usage?.input ?? 0;
279
- acc.output += task.usage?.output ?? 0;
280
- acc.cacheRead += task.usage?.cacheRead ?? 0;
281
- acc.cacheWrite += task.usage?.cacheWrite ?? 0;
282
- acc.cost += task.usage?.cost ?? 0;
283
- return acc;
284
- },
285
- { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 } as {
286
- input: number;
287
- output: number;
288
- cacheRead: number;
289
- cacheWrite: number;
290
- cost: number;
291
- },
292
- );
293
- const header = formatTokens(totals) ? `Agents: ${formatTokens(totals)}` : "Agents:";
294
- return [
295
- header,
296
- ...agents.slice(0, maxLines).map((agent) => agentPreviewLine(agent, taskForAgent(tasks, agent), options)),
297
- ...(agents.length > maxLines ? [`Agents: +${agents.length - maxLines} more`] : []),
298
- ];
299
- } catch (error) {
300
- const message = error instanceof Error ? error.message : String(error);
301
- return [`Agents: failed to read (${message})`];
302
- }
303
- }
304
-
305
- function agentsFor(run: TeamRunManifest, snapshotCache?: RunSnapshotCache): CrewAgentRecord[] {
306
- const snapshot = snapshotFor(run, snapshotCache);
307
- if (snapshot) return snapshot.agents;
308
- // P0-6: when a snapshot cache is provided but hasn't populated yet, return
309
- // empty (callers handle the empty-state placeholder) instead of calling
310
- // `readCrewAgents` synchronously on every render tick.
311
- if (snapshotCache) return [];
312
- try {
313
- return readCrewAgents(run);
314
- } catch {
315
- return [];
316
- }
317
- }
318
-
319
- function runLabel(run: TeamRunManifest, selected: boolean, snapshotCache?: RunSnapshotCache, maxW?: number): string {
320
- const agents = agentsFor(run, snapshotCache);
321
- const stale = isLikelyOrphanedActiveRun(run, agents);
322
- const running = agents.find((agent) => agent.status === "running");
323
- const queued = agents.find((agent) => agent.status === "queued");
324
- const step = stale
325
- ? "orphaned queued run"
326
- : running
327
- ? `step ${running.taskId}`
328
- : queued
329
- ? `queued ${queued.taskId}`
330
- : `agents ${agents.length}`;
331
- const status: RunStatus = stale ? "stale" : (run.status as RunStatus);
332
- const marker = selected ? "›" : " ";
333
- const icon = iconForStatus(status, {
334
- runningGlyph: spinnerFrame(run.runId),
335
- });
336
- // L-5: unified " · " separator (was "|").
337
- // L-3: keep the GOAL (the human identifier) visible on narrow terminals —
338
- // when the full line overflows, sacrifice the meta prefix (runId/status
339
- // survive; team/workflow/step clip) rather than the goal. Optional `maxW`
340
- // enables the goal-aware truncation; legacy 3-arg callers (dev patch
341
- // scripts) get the untruncated full label.
342
- const head = `${marker} ${icon} ${run.runId.slice(-8)} ${status}`;
343
- const meta = `${run.team}/${run.workflow ?? "none"} · ${step}`;
344
- const goal = sanitizeLine(run.goal ?? "");
345
- if (maxW === undefined) return sanitizeLine(`${head} · ${meta} · ${goal}`);
346
- const sepW = 3; // " · "
347
- if (visibleWidth(head) + sepW + visibleWidth(meta) + sepW + visibleWidth(goal) <= maxW) {
348
- return sanitizeLine(`${head} · ${meta} · ${goal}`);
349
- }
350
- // Not enough room: keep head + goal; clip the goal only if head+goal alone
351
- // cannot fit, then shrink the prefix (meta clips first) to match.
352
- const goalFits = visibleWidth(head) + sepW + visibleWidth(goal) <= maxW;
353
- const goalRender = goalFits ? goal : truncate(goal, Math.max(8, maxW - visibleWidth(head) - sepW));
354
- const prefixBudget = Math.max(0, maxW - visibleWidth(goalRender) - sepW);
355
- const prefixRender = truncate(`${head} · ${meta}`, prefixBudget);
356
- return sanitizeLine(`${prefixRender} · ${goalRender}`);
357
- }
358
-
359
- interface ResolvedRun {
360
- manifest: TeamRunManifest;
361
- snapshot: RunUiSnapshot | undefined;
362
- agents: CrewAgentRecord[];
363
- status: RunStatus;
364
- }
365
-
366
- function resolveRuns(runs: TeamRunManifest[], snapshotCache?: RunSnapshotCache): Map<string, ResolvedRun> {
367
- const map = new Map<string, ResolvedRun>();
368
- for (const run of runs) {
369
- const snapshot = snapshotFor(run, snapshotCache);
370
- const agents = snapshot?.agents ?? agentsFor(run, snapshotCache);
371
- const displayRun = snapshot?.manifest ?? run;
372
- const status: RunStatus = isLikelyOrphanedActiveRun(displayRun, agents) ? "stale" : (displayRun.status as RunStatus);
373
- map.set(run.runId, { manifest: run, snapshot, agents, status });
374
- }
375
- return map;
376
- }
377
-
378
- function groupedRuns(runs: TeamRunManifest[], snapshotCache?: RunSnapshotCache): Array<{ label: string; run?: TeamRunManifest }> {
379
- const resolved = resolveRuns(runs, snapshotCache);
380
- const rows: Array<{ label: string; run?: TeamRunManifest }> = [];
381
- const active = runs.filter((run) =>
382
- isDisplayActiveRun(resolved.get(run.runId)?.snapshot?.manifest ?? run, resolved.get(run.runId)?.agents ?? []),
383
- );
384
- const rest = runs.filter(
385
- (run) => !isDisplayActiveRun(resolved.get(run.runId)?.snapshot?.manifest ?? run, resolved.get(run.runId)?.agents ?? []),
386
- );
387
- if (active.length) rows.push({ label: "Active" }, ...active.map((run) => ({ label: run.runId, run })));
388
- if (rest.length) rows.push({ label: "Recent" }, ...rest.map((run) => ({ label: run.runId, run })));
389
- return rows;
390
- }
391
-
392
- function selectedRunFromGrouped(runs: TeamRunManifest[], selected: number, snapshotCache?: RunSnapshotCache): TeamRunManifest | undefined {
393
- return groupedRuns(runs, snapshotCache).filter((row) => row.run)[selected]?.run;
394
- }
395
-
396
- function countByStatus(runs: TeamRunManifest[], snapshotCache?: RunSnapshotCache): string {
397
- const resolved = resolveRuns(runs, snapshotCache);
398
- const counts = new Map<RunStatus, number>();
399
- for (const r of resolved.values()) counts.set(r.status, (counts.get(r.status) ?? 0) + 1);
400
- return [...counts.entries()].map(([status, count]) => `${status}=${count}`).join(", ") || "none";
401
- }
402
-
403
- export class RunDashboard implements DashboardComponent {
404
- // TEMP DIAGNOSTIC (remove after verifying keybind fix on Pi 0.81.1)
405
- private static _instanceCounter = 0;
406
- private readonly _instanceId: number;
407
- // END TEMP DIAGNOSTIC
408
-
409
- private selected = 0;
410
- private runScrollOffset = 0;
411
- private showFullProgress = false;
412
- private showHelp = false;
413
- private activePane: "agents" | "progress" | "mailbox" | "output" | "health" | "metrics" = lastActivePane;
414
- private runs: TeamRunManifest[];
415
- private readonly done: (selection: RunDashboardSelection | undefined) => void;
416
- private readonly theme: CrewTheme;
417
- private readonly options: RunDashboardOptions;
418
- private cachedWidth = 0;
419
- private cachedVersion = "";
420
- private cachedLines: string[] = [];
421
- /** 1.10 (UI-P1-2) — short-TTL cache for `buildSignature()` so per-run
422
- * `snapshotFor → refreshIfStale` calls don't fire on every render tick. */
423
- private cachedSignatureAt = 0;
424
- private cachedSignature = "";
425
- private readonly unsubscribeTheme: () => void;
426
- private readonly schedulerHandle: OverlaySchedulerHandle | undefined;
427
-
428
- constructor(
429
- runs: TeamRunManifest[],
430
- done: (selection: RunDashboardSelection | undefined) => void,
431
- theme: unknown = {},
432
- options: RunDashboardOptions = {},
433
- ) {
434
- // TEMP DIAGNOSTIC: log every constructor + handleInput + focus change
435
- this._instanceId = ++RunDashboard._instanceCounter;
436
- try {
437
- process.stderr.write(
438
- `[PI-CREW-DIAG] RunDashboard#${this._instanceId}.constructor runs=${runs.length} workspaceId=${options.workspaceId ?? "n/a"}\n`,
439
- );
440
- } catch {}
441
- // END TEMP DIAGNOSTIC
442
- // Filter runs by workspaceId for session isolation
443
- // If workspaceId is provided, only show runs owned by that session or runs with no owner (legacy)
444
- const filteredRuns = options.workspaceId
445
- ? runs.filter((run) => !run.ownerSessionId || run.ownerSessionId === options.workspaceId)
446
- : runs;
447
- this.runs = filteredRuns;
448
- this.done = done;
449
- this.theme = asCrewTheme(theme);
450
- this.options = options;
451
- // 1.10 (UI-P1-1): route run:state / worker:lifecycle / ui:invalidate
452
- // through a RenderScheduler (debounce + fallback) instead of registering
453
- // 3 raw runEventBus subscriptions that each schedule an immediate
454
- // invalidate+requestRender. With 3 overlays subscribing independently,
455
- // a single event triggered up to 9 callbacks and ~150 invalidates/sec.
456
- // The scheduler keeps the per-channel subscriptions but collapses them
457
- // into one debounced render + one coalesced invalidate per runId.
458
- //
459
- // FIND-07: scheduler must be constructed BEFORE the theme subscription
460
- // and the input-handler paths so they can route their invalidate+render
461
- // calls through `this.scheduleRender()` (debounced + coalesced) instead
462
- // of bypassing it with direct `invalidateAndRender()` calls. Each direct
463
- // call would otherwise skip the scheduler's debounce window and force
464
- // a synchronous repaint, recreating the burst-storm that this scheduler
465
- // was introduced to eliminate.
466
- const renderTick = (): void => {
467
- this.invalidateAndRender();
468
- };
469
- this.schedulerHandle = registerOverlayScheduler(renderTick, () => {
470
- // Drop any cached signature — data underneath may have
471
- // changed so the next buildSignature() needs to recompute.
472
- this.cachedSignature = "";
473
- this.cachedSignatureAt = 0;
474
- });
475
- // FIND-07: route theme changes through the scheduler so they coalesce
476
- // with run:state / worker:lifecycle / ui:invalidate bursts instead of
477
- // each firing their own immediate invalidate+requestRender.
478
- this.unsubscribeTheme = subscribeThemeChange(theme, () => this.scheduleRender());
479
- }
480
-
481
- /**
482
- * FIND-07: route an external invalidation through the RenderScheduler.
483
- *
484
- * Use this for any caller-driven invalidation (theme change, input
485
- * handler action) instead of calling `invalidateAndRender()` directly.
486
- * The scheduler debounces + coalesces these so a theme change arriving
487
- * in the middle of a run:state burst doesn't force a separate synchronous
488
- * repaint. Falls back to a direct render if the scheduler was not created
489
- * (defensive — currently always created in the constructor).
490
- */
491
- private scheduleRender(): void {
492
- if (this.schedulerHandle) {
493
- this.schedulerHandle.schedule();
494
- return;
495
- }
496
- this.invalidateAndRender();
497
- }
498
-
499
- /**
500
- * Invalidate the layout cache AND poke the host TUI to repaint. Without
501
- * the explicit `requestRender` call the host only repaints on its own
502
- * tick / on keypress, so async events (subagent completed, mailbox
503
- * updates, theme change) would leave the overlay showing stale data
504
- * until the user pressed a key — which is exactly when the "cascading
505
- * dashboard" symptom surfaces because the diff renderer was comparing
506
- * against a stale `previousLines` snapshot.
507
- */
508
- private invalidateAndRender(): void {
509
- this.invalidate();
510
- try {
511
- this.options.requestRender?.();
512
- } catch {
513
- /* host may not expose requestRender */
514
- }
515
- }
516
-
517
- /**
518
- * Stable overlay height. The host pi-tui positions overlays based on the
519
- * number of lines `render()` returns; if that number fluctuates between
520
- * frames (empty state → full pane → fewer agents) the anchor row shifts
521
- * up/down and the differential renderer cannot reliably erase the
522
- * previous footprint, producing the "ghost dashboard below" bug.
523
- *
524
- * Locking the output to a single height per render eliminates that.
525
- */
526
- private targetHeight(): number {
527
- const rows = Number.isFinite(process.stdout?.rows) ? Number(process.stdout?.rows) : 30;
528
- return Math.max(12, Math.min(36, rows - 2));
529
- }
530
-
531
- private refreshRuns(): void {
532
- if (!this.options.runProvider) return;
533
- const selectedRunId = this.selectedRunId();
534
- const next = this.options.runProvider();
535
- this.runs = Array.isArray(next) ? next : this.runs;
536
- if (selectedRunId) {
537
- const nextIndex = groupedRuns(this.runs, this.options.snapshotCache)
538
- .filter((row) => row.run)
539
- .findIndex((row) => row.run?.runId === selectedRunId);
540
- if (nextIndex >= 0) this.selected = nextIndex;
541
- else this.selected = 0;
542
- }
543
- }
544
-
545
- /**
546
- * L-1 — keep the run-list selection inside the rendered window so the `›`
547
- * marker can never scroll off-screen (and Enter can never act on an
548
- * invisible run). Uses the SAME `runListWindow()` the render loop uses and
549
- * iterates to a fixed point, because the slot count depends on whether the
550
- * ↑/↓ indicators render (which depends on the offset). This makes the
551
- * window correct on the SAME render that processed the keypress — there is
552
- * no one-frame lag where the marker is off-screen.
553
- */
554
- private ensureRunListWindow(selectableCount: number): void {
555
- if (selectableCount <= RUN_LIST_MAX) {
556
- this.runScrollOffset = 0;
557
- return;
558
- }
559
- for (let i = 0; i < 4; i++) {
560
- const { slots } = runListWindow(this.runScrollOffset, selectableCount);
561
- const prev = this.runScrollOffset;
562
- if (this.selected < this.runScrollOffset) this.runScrollOffset = this.selected;
563
- else if (this.selected >= this.runScrollOffset + slots) this.runScrollOffset = this.selected - slots + 1;
564
- this.runScrollOffset = Math.max(0, Math.min(this.runScrollOffset, Math.max(0, selectableCount - 1)));
565
- if (this.runScrollOffset === prev) break;
566
- }
567
- }
568
-
569
- private buildSignature(): string {
570
- // 1.10 (UI-P1-2) — short-TTL cache so we don't re-read every run's
571
- // snapshot on every render tick. `snapshotFor → refreshIfStale` can
572
- // stat multiple files per run when its own TTL expires, and the
573
- // dashboard's render is called several times per second (spinner +
574
- // event-bus). Cache the full computed signature for ~100ms: long
575
- // enough to coalesce one render burst, short enough that idle pauses
576
- // still pick up new data promptly.
577
- const now = Date.now();
578
- if (this.cachedSignature && now - this.cachedSignatureAt < SIGNATURE_CACHE_TTL_MS) {
579
- return this.cachedSignature;
580
- }
581
- let hasRunning = false;
582
- const statuses = this.runs
583
- .map((run) => {
584
- const snapshot = snapshotFor(run, this.options.snapshotCache);
585
- const displayRun = snapshot?.manifest ?? run;
586
- const agents = snapshot?.agents ?? agentsFor(run, this.options.snapshotCache);
587
- const stale = isLikelyOrphanedActiveRun(displayRun, agents);
588
- const status: RunStatus = stale ? "stale" : (displayRun.status as RunStatus);
589
- if (status === "running" || agents.some((agent) => agent.status === "running")) hasRunning = true;
590
- return snapshot?.signature ?? `${displayRun.runId}:${displayRun.status}:${displayRun.updatedAt}:${status}`;
591
- })
592
- .join("|");
593
- const metricsSig =
594
- this.activePane === "metrics" ? `:metrics=${this.options.registry?.snapshot().length ?? 0}:${spinnerBucket()}` : "";
595
- const sig = `${this.selected}:${this.showHelp ? 1 : 0}:${this.showFullProgress ? 1 : 0}:${this.activePane}:${statuses}${hasRunning ? `:spin=${spinnerBucket()}` : ""}${metricsSig}`;
596
- this.cachedSignature = sig;
597
- this.cachedSignatureAt = now;
598
- return sig;
599
- }
600
-
601
- invalidate(): void {
602
- this.cachedVersion = "";
603
- this.cachedLines = [];
604
- // 1.10 (UI-P1-2): also drop the short-TTL signature cache so the next
605
- // render can't return a stale snapshot-derived signature that was
606
- // computed before the invalidating event arrived.
607
- this.cachedSignature = "";
608
- this.cachedSignatureAt = 0;
609
- }
610
-
611
- dispose(): void {
612
- this.unsubscribeTheme();
613
- this.schedulerHandle?.dispose();
614
- }
615
-
616
- private selectedRunId(): string | undefined {
617
- return selectedRunFromGrouped(this.runs, this.selected, this.options.snapshotCache)?.runId;
618
- }
619
-
620
- render(width: number): string[] {
621
- try {
622
- return this.renderUnsafe(width);
623
- } catch (error) {
624
- logInternalError("run-dashboard.render", error);
625
- return renderLines(["Dashboard error — see logs for details.", "Press r to reload · Esc to close."], width);
626
- }
627
- }
628
-
629
- private renderUnsafe(width: number): string[] {
630
- this.refreshRuns();
631
- const signature = this.buildSignature();
632
- if (signature !== this.cachedVersion || this.cachedWidth !== width) {
633
- const innerWidth = Math.max(20, width - 4);
634
- const borderWidth = Math.min(innerWidth, Math.max(0, width - 2));
635
- const fg = (color: Parameters<CrewTheme["fg"]>[0], text: string) => this.theme.fg(color, text);
636
- const borderFill = (count: number) => new DynamicCrewBorder(this.theme).render(count)[0];
637
- const border = (left: string, right: string) => `${fg("border", left)}${borderFill(borderWidth)}${fg("border", right)}`;
638
- const row = (text: string) => `│ ${pad(truncate(text, innerWidth - 1), innerWidth - 1)}│`;
639
- const sep = () => border("├", "┤");
640
-
641
- const lines: string[] = [];
642
- if (this.showHelp) {
643
- // K-1: help overlay replaces the dashboard body until dismissed.
644
- lines.push(...new HelpOverlay(this.theme).render(width));
645
- } else {
646
- lines.push(
647
- border("╭", "╮"),
648
- row(
649
- `${fg("accent", "▐")} ${this.theme.bold("pi-crew")} · ${this.runs.length} runs ${fg("dim", "1-6 pane · ↑↓ · Enter · ? help · Esc")}`,
650
- ),
651
- sep(),
652
- );
653
-
654
- if (this.runs.length === 0) {
655
- // F-7: actionable empty state instead of a bare "No runs.".
656
- lines.push(row(fg("dim", "No runs yet.")));
657
- lines.push(row(fg("dim", "Start one: team action='run' · r reload · Esc close")));
658
- } else {
659
- // L-1: windowed run list so the selection can never scroll off-screen.
660
- const allGrouped = groupedRuns(this.runs, this.options.snapshotCache);
661
- const selectable = allGrouped.filter((rowItem) => rowItem.run);
662
- const selectableCount = selectable.length;
663
- if (this.selected > selectableCount - 1) this.selected = Math.max(0, selectableCount - 1);
664
- this.ensureRunListWindow(selectableCount);
665
- if (selectableCount <= RUN_LIST_MAX) {
666
- // Common case (≤8 runs): keep the Active/Recent group headers.
667
- for (const rowItem of allGrouped) {
668
- if (!rowItem.run) {
669
- lines.push(row(fg("dim", `── ${rowItem.label} ──`)));
670
- continue;
671
- }
672
- const idx = selectable.findIndex((c) => c.run?.runId === rowItem.run?.runId);
673
- const snap = snapshotFor(rowItem.run, this.options.snapshotCache);
674
- const run = snap?.manifest ?? rowItem.run;
675
- const agents = snap?.agents ?? agentsFor(rowItem.run, this.options.snapshotCache);
676
- const status: RunStatus = isLikelyOrphanedActiveRun(run, agents) ? "stale" : (run.status as RunStatus);
677
- const label = runLabel(run, idx === this.selected, this.options.snapshotCache, innerWidth - 2);
678
- lines.push(row(applyStatusColor(this.theme, status, label)));
679
- }
680
- } else {
681
- // >8 runs: windowed list (group headers omitted to maximise run rows).
682
- const win = runListWindow(this.runScrollOffset, selectableCount);
683
- if (win.hasTop) lines.push(row(fg("dim", `↑ ${this.runScrollOffset} more above`)));
684
- for (let gi = this.runScrollOffset; gi < Math.min(this.runScrollOffset + win.slots, selectableCount); gi++) {
685
- const rowItem = selectable[gi];
686
- if (!rowItem?.run) continue;
687
- const snap = snapshotFor(rowItem.run, this.options.snapshotCache);
688
- const run = snap?.manifest ?? rowItem.run;
689
- const agents = snap?.agents ?? agentsFor(rowItem.run, this.options.snapshotCache);
690
- const status: RunStatus = isLikelyOrphanedActiveRun(run, agents) ? "stale" : (run.status as RunStatus);
691
- const label = runLabel(run, gi === this.selected, this.options.snapshotCache, innerWidth - 2);
692
- lines.push(row(applyStatusColor(this.theme, status, label)));
693
- }
694
- if (win.hasBottom)
695
- lines.push(row(fg("dim", `↓ ${selectableCount - (this.runScrollOffset + win.slots)} more below`)));
696
- }
697
-
698
- // Selected run detail — compact
699
- const selectedRun = selectedRunFromGrouped(this.runs, this.selected, this.options.snapshotCache);
700
- if (selectedRun) {
701
- const snap = snapshotFor(selectedRun, this.options.snapshotCache);
702
- const r = snap?.manifest ?? selectedRun;
703
- const agents = snap?.agents ?? agentsFor(selectedRun, this.options.snapshotCache);
704
- const statusStr: RunStatus = isLikelyOrphanedActiveRun(r, agents) ? "stale" : (r.status as RunStatus);
705
- const selectedTasks = snap?.tasks ?? readRunTasks(r, this.options.snapshotCache);
706
- lines.push(sep());
707
- lines.push(row(`${fg("accent", "▸")} ${truncate(sanitizeLine(r.goal), innerWidth - 6)}`));
708
- // L-2: surface the failure/cancellation reason inline for terminal runs.
709
- const isTerminal = statusStr === "failed" || statusStr === "cancelled" || statusStr === "stopped";
710
- const reason = isTerminal ? summarizeTerminalReason(r, selectedTasks, snap?.cancellationReason) : undefined;
711
- const reasonSuffix = reason ? ` · ${truncate(sanitizeLine(reason), 40)}` : "";
712
- lines.push(
713
- row(
714
- fg(
715
- "dim",
716
- sanitizeLine(
717
- ` ${r.team}/${r.workflow ?? "default"} · ${statusStr} · ${r.runId.slice(-10)}${reasonSuffix}`,
718
- ),
719
- ),
720
- ),
721
- );
722
-
723
- // Pane content (max 8 lines) — F-2: colorize embedded status glyphs.
724
- const paneLines = snap
725
- ? this.activePane === "agents"
726
- ? safeRenderPane("agents", () => renderAgentsPane(snap, this.options))
727
- : this.activePane === "progress"
728
- ? safeRenderPane("progress", () => renderProgressPane(snap))
729
- : this.activePane === "mailbox"
730
- ? safeRenderPane("mailbox", () => renderMailboxPane(snap))
731
- : this.activePane === "health"
732
- ? safeRenderPane("health", () =>
733
- renderHealthPane(snap, {
734
- isForeground: !r.async,
735
- }),
736
- )
737
- : this.activePane === "metrics"
738
- ? safeRenderPane("metrics", () =>
739
- renderMetricsPane(snap, {
740
- registry: this.options.registry,
741
- }),
742
- )
743
- : safeRenderPane("transcript", () => renderTranscriptPane(snap))
744
- : [...readAgentPreview(r, 4, this.options), ...readProgressPreview(r, 2, this.options.snapshotCache)];
745
- const filteredPane = paneLines.filter((l) => l && !l.includes("(none)") && l.trim() !== "");
746
- if (filteredPane.length > 0) {
747
- lines.push(row(fg("dim", `── ${this.activePane} ──`)));
748
- for (const line of filteredPane.slice(0, 8)) {
749
- lines.push(colorizeStatusGlyphs(row(truncate(sanitizeLine(line), innerWidth - 2)), this.theme));
750
- }
751
- }
752
-
753
- // F-4: warn when a live run's snapshot is likely stale (flaky read).
754
- const isActiveRun = statusStr === "running" || statusStr === "queued" || statusStr === "waiting";
755
- const staleData = isActiveRun && (snap ? Date.now() - snap.fetchedAt > STALE_SNAPSHOT_MS : true);
756
- if (staleData) lines.push(row(fg("warning", "⚠ data may be stale (manifest read flaky)")));
757
-
758
- // One-line footer — V-1: width-padded so the right edge doesn't jitter.
759
- const usage = aggregateUsage(selectedTasks);
760
- const u = usage ?? {
761
- input: 0,
762
- output: 0,
763
- cacheRead: 0,
764
- cacheWrite: 0,
765
- cost: 0,
766
- };
767
- const tok = (u.input ?? 0) + (u.output ?? 0) + (u.cacheRead ?? 0) + (u.cacheWrite ?? 0);
768
- const tokStr = tok > 0 ? (tok >= 1000 ? `${(tok / 1000).toFixed(1)}k tok` : `${tok} tok`) : "";
769
- let ctxPct: number | undefined;
770
- for (const agent of agents) {
771
- if (agent.status === "running" && agent.runtime === "live-session") {
772
- const pct = getLiveAgentContextPercent(agent.taskId);
773
- if (pct != null) {
774
- ctxPct = pct;
775
- break;
776
- }
777
- }
778
- }
779
- const ctxStr = ctxPct != null ? `${Math.round(ctxPct)}% ctx` : "";
780
- const footerFields: string[] = [];
781
- if (tokStr) footerFields.push(padVis(tokStr, 10));
782
- if (ctxStr) footerFields.push(padVis(ctxStr, 9));
783
- if (footerFields.length) lines.push(row(fg("dim", footerFields.join(" · "))));
784
- }
785
- }
786
- lines.push(border("╰", "╯"));
787
- }
788
-
789
- const target = this.targetHeight();
790
- if (lines.length < target) {
791
- const innerWidth = Math.max(20, width - 4);
792
- const fg = (color: Parameters<CrewTheme["fg"]>[0], text: string) => this.theme.fg(color, text);
793
- const blankRow = `│ ${pad("", innerWidth - 1)}│`;
794
- const bottom = lines.pop();
795
- while (lines.length < target - 1) lines.push(fg("border", blankRow));
796
- if (bottom) lines.push(bottom);
797
- } else if (lines.length > target) {
798
- const bottom = lines[lines.length - 1];
799
- lines.length = target - 1;
800
- lines.push(bottom);
801
- }
802
-
803
- this.cachedLines = renderLines(
804
- lines.map((line) => truncate(line, width)),
805
- width,
806
- );
807
- this.cachedVersion = signature;
808
- this.cachedWidth = width;
809
- }
810
- return this.cachedLines;
811
- }
812
-
813
- // Pi 0.81+ requires the Focusable contract: a string-indexable `focused`
814
- // marker that TUI toggles to track which component currently receives
815
- // input. Without it, isFocusable() returns false and downstream
816
- // dispatch may skip the component. Declared as an own property so
817
- // `"focused" in component` is true.
818
- public focused = false;
819
-
820
- handleInput(data: string): void {
821
- // TEMP DIAGNOSTIC (remove after verifying keybind fix on Pi 0.81.1)
822
- if (process.env.PI_CREW_BROKER_DIAG_UI === "1") {
823
- try {
824
- process.stderr.write(
825
- `[PI-CREW-DIAG] RunDashboard#${this._instanceId}.handleInput data=${JSON.stringify(data)} focused=${this.focused}\n`,
826
- );
827
- } catch {}
828
- }
829
- const action = dashboardActionForKey(data, this.activePane);
830
- // K-1: "?" toggles the help overlay; while it is shown, any other key
831
- // (including Esc) just dismisses it first instead of acting.
832
- if (action === "help") {
833
- this.showHelp = !this.showHelp;
834
- this.scheduleRender();
835
- return;
836
- }
837
- if (this.showHelp) {
838
- this.showHelp = false;
839
- this.scheduleRender();
840
- return;
841
- }
842
- const selectedRunId = this.selectedRunId();
843
- if (action === "close") {
844
- this.done(undefined);
845
- return;
846
- }
847
- if (action === "select") {
848
- this.done(selectedRunId ? { runId: selectedRunId, action: "status" } : undefined);
849
- return;
850
- }
851
- if (
852
- action === "summary" ||
853
- action === "artifacts" ||
854
- action === "api" ||
855
- action === "agents" ||
856
- action === "mailbox" ||
857
- action === "reload" ||
858
- action === "mailbox-detail" ||
859
- action === "health-recovery" ||
860
- action === "health-kill-stale" ||
861
- action === "health-diagnostic-export" ||
862
- action === "notifications-dismiss"
863
- ) {
864
- this.done(selectedRunId ? { runId: selectedRunId, action } : action === "reload" ? { runId: "", action } : undefined);
865
- return;
866
- }
867
- if (action === "events") {
868
- this.done(selectedRunId ? { runId: selectedRunId, action: "agent-events" } : undefined);
869
- return;
870
- }
871
- if (action === "output") {
872
- this.done(selectedRunId ? { runId: selectedRunId, action: "agent-output" } : undefined);
873
- return;
874
- }
875
- if (action === "transcript") {
876
- this.done(selectedRunId ? { runId: selectedRunId, action: "agent-transcript" } : undefined);
877
- return;
878
- }
879
- if (action === "live-conversation") {
880
- this.done(selectedRunId ? { runId: selectedRunId, action: "agent-live" } : undefined);
881
- return;
882
- }
883
- if (action === "progressToggle") {
884
- this.showFullProgress = !this.showFullProgress;
885
- this.invalidate();
886
- return;
887
- }
888
- if (action === "pane-agents") this.activePane = "agents";
889
- else if (action === "pane-progress") this.activePane = "progress";
890
- else if (action === "pane-mailbox") this.activePane = "mailbox";
891
- else if (action === "pane-output") this.activePane = "output";
892
- else if (action === "pane-health") this.activePane = "health";
893
- else if (action === "pane-metrics") this.activePane = "metrics";
894
- else if (action === "up") this.selected = Math.max(0, this.selected - 1);
895
- else if (action === "down") {
896
- const selectableCount = groupedRuns(this.runs, this.options.snapshotCache).filter((row) => row.run).length;
897
- this.selected = Math.min(Math.max(0, selectableCount - 1), this.selected + 1);
898
- }
899
- if (action) {
900
- lastActivePane = this.activePane;
901
- this.scheduleRender();
902
- }
903
- }
904
- }