pi-crew 0.1.49 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/CHANGELOG.md +74 -1
  2. package/README.md +176 -781
  3. package/agents/analyst.md +11 -11
  4. package/agents/critic.md +11 -11
  5. package/agents/executor.md +11 -11
  6. package/agents/explorer.md +11 -11
  7. package/agents/planner.md +11 -11
  8. package/agents/reviewer.md +11 -11
  9. package/agents/security-reviewer.md +11 -11
  10. package/agents/test-engineer.md +11 -11
  11. package/agents/verifier.md +70 -11
  12. package/agents/writer.md +11 -11
  13. package/docs/actions-reference.md +595 -0
  14. package/docs/commands-reference.md +347 -0
  15. package/docs/runtime-flow.md +148 -148
  16. package/index.ts +6 -6
  17. package/package.json +99 -99
  18. package/skills/async-worker-recovery/SKILL.md +42 -42
  19. package/skills/context-artifact-hygiene/SKILL.md +52 -52
  20. package/skills/delegation-patterns/SKILL.md +54 -54
  21. package/skills/mailbox-interactive/SKILL.md +40 -40
  22. package/skills/model-routing-context/SKILL.md +39 -39
  23. package/skills/multi-perspective-review/SKILL.md +58 -58
  24. package/skills/observability-reliability/SKILL.md +41 -41
  25. package/skills/orchestration/SKILL.md +157 -157
  26. package/skills/ownership-session-security/SKILL.md +41 -41
  27. package/skills/pi-extension-lifecycle/SKILL.md +39 -39
  28. package/skills/requirements-to-task-packet/SKILL.md +63 -63
  29. package/skills/resource-discovery-config/SKILL.md +41 -41
  30. package/skills/runtime-state-reader/SKILL.md +44 -44
  31. package/skills/secure-agent-orchestration-review/SKILL.md +45 -45
  32. package/skills/state-mutation-locking/SKILL.md +42 -42
  33. package/skills/systematic-debugging/SKILL.md +67 -67
  34. package/skills/ui-render-performance/SKILL.md +39 -39
  35. package/skills/verification-before-done/SKILL.md +57 -57
  36. package/skills/worktree-isolation/SKILL.md +39 -39
  37. package/src/adapters/claude-adapter.ts +25 -0
  38. package/src/adapters/codex-adapter.ts +21 -0
  39. package/src/adapters/cursor-adapter.ts +17 -0
  40. package/src/adapters/export-util.ts +137 -0
  41. package/src/adapters/index.ts +15 -0
  42. package/src/adapters/registry.ts +18 -0
  43. package/src/adapters/types.ts +23 -0
  44. package/src/agents/agent-config.ts +2 -0
  45. package/src/agents/agent-search.ts +98 -98
  46. package/src/agents/discover-agents.ts +2 -1
  47. package/src/config/config.ts +14 -1
  48. package/src/config/defaults.ts +5 -5
  49. package/src/config/drift-detector.ts +211 -0
  50. package/src/config/markers.ts +327 -0
  51. package/src/config/resilient-parser.ts +108 -0
  52. package/src/config/suggestions.ts +74 -0
  53. package/src/extension/cross-extension-rpc.ts +103 -82
  54. package/src/extension/project-init.ts +36 -4
  55. package/src/extension/register.ts +67 -22
  56. package/src/extension/registration/commands.ts +77 -8
  57. package/src/extension/registration/subagent-tools.ts +10 -1
  58. package/src/extension/registration/team-tool.ts +10 -1
  59. package/src/extension/registration/viewers.ts +48 -34
  60. package/src/extension/run-bundle-schema.ts +89 -89
  61. package/src/extension/run-export.ts +26 -12
  62. package/src/extension/run-import.ts +25 -1
  63. package/src/extension/run-index.ts +5 -1
  64. package/src/extension/run-maintenance.ts +142 -68
  65. package/src/extension/team-manager-command.ts +10 -1
  66. package/src/extension/team-tool/context.ts +1 -1
  67. package/src/extension/team-tool/doctor.ts +28 -3
  68. package/src/extension/team-tool/handle-settings.ts +195 -188
  69. package/src/extension/team-tool/inspect.ts +41 -41
  70. package/src/extension/team-tool/intent-policy.ts +42 -42
  71. package/src/extension/team-tool/lifecycle-actions.ts +27 -8
  72. package/src/extension/team-tool/plan.ts +19 -19
  73. package/src/extension/team-tool/run.ts +12 -1
  74. package/src/extension/team-tool.ts +14 -3
  75. package/src/i18n.ts +184 -184
  76. package/src/observability/exporters/otlp-exporter.ts +92 -77
  77. package/src/prompt/prompt-runtime.ts +72 -72
  78. package/src/runtime/agent-memory.ts +72 -72
  79. package/src/runtime/agent-observability.ts +114 -114
  80. package/src/runtime/async-marker.ts +26 -26
  81. package/src/runtime/attention-events.ts +28 -28
  82. package/src/runtime/auto-resume.ts +100 -0
  83. package/src/runtime/background-runner.ts +11 -1
  84. package/src/runtime/cancellation-token.ts +89 -89
  85. package/src/runtime/cancellation.ts +61 -61
  86. package/src/runtime/capability-inventory.ts +116 -116
  87. package/src/runtime/child-pi.ts +7 -2
  88. package/src/runtime/compaction-summary.ts +271 -0
  89. package/src/runtime/completion-guard.ts +190 -190
  90. package/src/runtime/concurrency.ts +3 -1
  91. package/src/runtime/crash-recovery.ts +33 -0
  92. package/src/runtime/delta-conflict.ts +360 -0
  93. package/src/runtime/diagnostic-export.ts +3 -1
  94. package/src/runtime/direct-run.ts +35 -35
  95. package/src/runtime/event-stream-bridge.ts +3 -1
  96. package/src/runtime/foreground-control.ts +82 -82
  97. package/src/runtime/green-contract.ts +46 -46
  98. package/src/runtime/group-join.ts +106 -106
  99. package/src/runtime/heartbeat-gradient.ts +28 -28
  100. package/src/runtime/heartbeat-watcher.ts +124 -124
  101. package/src/runtime/iteration-hooks.ts +262 -0
  102. package/src/runtime/live-agent-control.ts +88 -88
  103. package/src/runtime/live-control-realtime.ts +36 -36
  104. package/src/runtime/live-extension-bridge.ts +150 -150
  105. package/src/runtime/live-irc.ts +92 -92
  106. package/src/runtime/live-session-health.ts +100 -100
  107. package/src/runtime/loop-gates.ts +129 -0
  108. package/src/runtime/metric-parser.ts +40 -0
  109. package/src/runtime/notebook-helpers.ts +90 -90
  110. package/src/runtime/orphan-sentinel.ts +7 -7
  111. package/src/runtime/parallel-research.ts +44 -44
  112. package/src/runtime/phase-progress.ts +217 -0
  113. package/src/runtime/pi-args.ts +38 -2
  114. package/src/runtime/pi-json-output.ts +111 -111
  115. package/src/runtime/pi-spawn.ts +74 -6
  116. package/src/runtime/policy-engine.ts +79 -79
  117. package/src/runtime/post-checks.ts +122 -0
  118. package/src/runtime/process-status.ts +14 -1
  119. package/src/runtime/progress-event-coalescer.ts +43 -43
  120. package/src/runtime/prose-compressor.ts +164 -164
  121. package/src/runtime/recovery-recipes.ts +74 -74
  122. package/src/runtime/result-extractor.ts +121 -121
  123. package/src/runtime/role-permission.ts +39 -39
  124. package/src/runtime/sensitive-paths.ts +3 -3
  125. package/src/runtime/session-resources.ts +25 -25
  126. package/src/runtime/session-snapshot.ts +59 -59
  127. package/src/runtime/session-usage.ts +79 -79
  128. package/src/runtime/sidechain-output.ts +29 -29
  129. package/src/runtime/stream-preview.ts +177 -177
  130. package/src/runtime/supervisor-contact.ts +59 -59
  131. package/src/runtime/task-display.ts +38 -38
  132. package/src/runtime/task-graph.ts +207 -0
  133. package/src/runtime/task-quality.ts +207 -0
  134. package/src/runtime/task-runner/capabilities.ts +78 -78
  135. package/src/runtime/task-runner/live-executor.ts +7 -1
  136. package/src/runtime/task-runner/progress.ts +119 -119
  137. package/src/runtime/task-runner/prompt-builder.ts +1 -1
  138. package/src/runtime/task-runner/prompt-pipeline.ts +64 -64
  139. package/src/runtime/task-runner/result-utils.ts +14 -14
  140. package/src/runtime/task-runner/run-projection.ts +103 -103
  141. package/src/runtime/task-runner/state-helpers.ts +22 -22
  142. package/src/runtime/team-runner.ts +126 -7
  143. package/src/runtime/worker-heartbeat.ts +21 -21
  144. package/src/runtime/worker-startup.ts +57 -57
  145. package/src/runtime/workflow-state.ts +187 -0
  146. package/src/runtime/workspace-tree.ts +298 -298
  147. package/src/schema/config-schema.ts +12 -0
  148. package/src/schema/validation-types.ts +148 -0
  149. package/src/skills/skill-templates.ts +374 -0
  150. package/src/state/active-run-registry.ts +35 -11
  151. package/src/state/atomic-write.ts +33 -26
  152. package/src/state/contracts.ts +1 -0
  153. package/src/state/event-reconstructor.ts +217 -0
  154. package/src/state/locks.ts +2 -11
  155. package/src/state/mailbox.ts +4 -3
  156. package/src/state/state-store.ts +32 -14
  157. package/src/state/task-claims.ts +44 -44
  158. package/src/state/types.ts +9 -0
  159. package/src/state/usage.ts +29 -29
  160. package/src/subagents/async-entry.ts +1 -1
  161. package/src/subagents/index.ts +3 -3
  162. package/src/subagents/live/control.ts +1 -1
  163. package/src/subagents/live/manager.ts +1 -1
  164. package/src/subagents/live/realtime.ts +1 -1
  165. package/src/subagents/live/session-runtime.ts +1 -1
  166. package/src/subagents/manager.ts +1 -1
  167. package/src/subagents/spawn.ts +1 -1
  168. package/src/teams/team-serializer.ts +38 -38
  169. package/src/types/diff.d.ts +18 -18
  170. package/src/ui/crew-footer.ts +101 -101
  171. package/src/ui/crew-select-list.ts +111 -111
  172. package/src/ui/crew-widget.ts +9 -4
  173. package/src/ui/dashboard-panes/cancellation-pane.ts +42 -42
  174. package/src/ui/dashboard-panes/capability-pane.ts +59 -59
  175. package/src/ui/dashboard-panes/mailbox-pane.ts +35 -35
  176. package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
  177. package/src/ui/dashboard-panes/progress-pane.ts +11 -0
  178. package/src/ui/dynamic-border.ts +25 -25
  179. package/src/ui/layout-primitives.ts +106 -106
  180. package/src/ui/loaders.ts +158 -158
  181. package/src/ui/powerbar-publisher.ts +6 -0
  182. package/src/ui/render-coalescer.ts +51 -51
  183. package/src/ui/render-diff.ts +119 -119
  184. package/src/ui/render-scheduler.ts +143 -143
  185. package/src/ui/run-action-dispatcher.ts +10 -1
  186. package/src/ui/spinner.ts +17 -17
  187. package/src/ui/status-colors.ts +58 -58
  188. package/src/ui/syntax-highlight.ts +116 -116
  189. package/src/ui/transcript-entries.ts +258 -258
  190. package/src/utils/completion-dedupe.ts +63 -63
  191. package/src/utils/frontmatter.ts +68 -68
  192. package/src/utils/git.ts +262 -262
  193. package/src/utils/ids.ts +17 -17
  194. package/src/utils/incremental-reader.ts +104 -104
  195. package/src/utils/names.ts +27 -27
  196. package/src/utils/redaction.ts +44 -44
  197. package/src/utils/safe-paths.ts +47 -47
  198. package/src/utils/scan-cache.ts +136 -136
  199. package/src/utils/sleep.ts +40 -26
  200. package/src/utils/task-name-generator.ts +337 -337
  201. package/src/workflows/validate-workflow.ts +40 -40
  202. package/src/worktree/branch-freshness.ts +45 -45
  203. package/src/worktree/worktree-manager.ts +11 -3
  204. package/teams/default.team.md +12 -12
  205. package/teams/fast-fix.team.md +11 -11
  206. package/teams/implementation.team.md +18 -18
  207. package/teams/parallel-research.team.md +14 -14
  208. package/teams/research.team.md +11 -11
  209. package/teams/review.team.md +12 -12
  210. package/workflows/default.workflow.md +30 -29
  211. package/workflows/fast-fix.workflow.md +23 -22
  212. package/workflows/implementation.workflow.md +43 -38
  213. package/workflows/parallel-research.workflow.md +46 -46
  214. package/workflows/research.workflow.md +22 -22
  215. package/workflows/review.workflow.md +30 -30
  216. package/docs/refactor-tasks-phase3.md +0 -394
  217. package/docs/refactor-tasks-phase4.md +0 -564
  218. package/docs/refactor-tasks-phase5.md +0 -402
  219. package/docs/refactor-tasks-phase6.md +0 -662
  220. package/docs/refactor-tasks.md +0 -1484
  221. package/docs/research/AGENT-EXECUTION-ARCHITECTURE.md +0 -261
  222. package/docs/research/AGENT-LIFECYCLE-COMPARISON.md +0 -111
  223. package/docs/research/AUDIT_OH_MY_PI.md +0 -261
  224. package/docs/research/AUDIT_PI_CREW.md +0 -457
  225. package/docs/research/CAVEMAN-DEEP-RESEARCH.md +0 -281
  226. package/docs/research/COMPARISON_OH_MY_PI_VS_PI_CREW.md +0 -264
  227. package/docs/research/DEEP-RESEARCH-PI-POWERBAR.md +0 -343
  228. package/docs/research/DEEP_RESEARCH_SUBAGENT_ARCHITECTURE.md +0 -480
  229. package/docs/research/GAP_CLOSURE_IMPLEMENTATION_PLAN.md +0 -354
  230. package/docs/research/IMPLEMENTATION_PLAN.md +0 -385
  231. package/docs/research/LIVE-SESSION-PRODUCTION-READY-PLAN.md +0 -502
  232. package/docs/research/OH-MY-PI-DEEP-RESEARCH-v14.7.6.md +0 -266
  233. package/docs/research/REMAINING-GAPS-PLAN.md +0 -363
  234. package/docs/research/SESSION-SUMMARY-2026-05-08.md +0 -146
  235. package/docs/research/UI-RESPONSIVENESS-AUDIT.md +0 -173
  236. package/docs/research-awesome-agent-skills-distillation.md +0 -100
  237. package/docs/research-extension-examples.md +0 -297
  238. package/docs/research-extension-system.md +0 -324
  239. package/docs/research-oh-my-pi-distillation.md +0 -369
  240. package/docs/research-optimization-plan.md +0 -548
  241. package/docs/research-phase10-distillation.md +0 -199
  242. package/docs/research-phase11-distillation.md +0 -201
  243. package/docs/research-phase8-operator-experience-plan.md +0 -819
  244. package/docs/research-phase9-observability-reliability-plan.md +0 -1190
  245. package/docs/research-pi-coding-agent.md +0 -357
  246. package/docs/research-source-pi-crew-reference.md +0 -174
  247. package/docs/research-ui-optimization-plan.md +0 -480
  248. package/docs/source-runtime-refactor-map.md +0 -107
  249. package/src/utils/atomic-write.ts +0 -33
@@ -1,662 +0,0 @@
1
- # Phase 6 Refactor Plan — Robustness sau test 0.1.27/0.1.29 + nợ kỹ thuật từ source-runtime-refactor-map
2
-
3
- > Xuất xứ:
4
- > - Test thực tế run `team_20260428152644_2ae0dce7` (parallel-research, 10/10 completed) trên pi-crew@0.1.27.
5
- > - Re-read source 28/04/2026 sau bump 0.1.28 (responseTimeoutMs 15s→5m) và 0.1.29 (republish).
6
- > - Findings còn lại từ `docs/source-runtime-refactor-map.md` (subagent runtime consolidation, model-routing persistence, adaptive planner repair).
7
- >
8
- > Phase 5 đã hoàn tất (UI/footer/select-list/theme hot-reload). Phase 6 tập trung **runtime hardening + maintainability**, không phá public API.
9
-
10
- ## Quy ước chung (giữ nguyên từ Phase 5)
11
- - Không phá vỡ public API: tool actions, slash commands, config schema, schema.json.
12
- - Sau mỗi task: `npx tsc --noEmit` + `npm run test:unit` (`test:integration` khi đụng runtime/spawn/state).
13
- - Không thêm runtime dependency mới ngoài stdlib + peer deps đã có (`pi-coding-agent`, `pi-ai`, `pi-agent-core`, `pi-tui`, `jiti`).
14
- - Mỗi task = 1 commit độc lập, có thể revert riêng. Test name bám sát hành vi (`describe`/`it` đặt theo contract chứ không theo file).
15
- - Default behavior không đổi (backward-compat); cải tiến hành vi đi qua opt-in env/config khi có nguy cơ regression.
16
- - Mỗi task có Acceptance + Verification + Risk/Rollback. Trước khi mở PR phải `npm run ci` (typecheck + test:unit + test:integration + npm pack --dry-run).
17
-
18
- ## Roadmap tổng quan
19
-
20
- | Tier | Workstream | Số task | Ước tính | Ưu tiên |
21
- |---|---|---|---|---|
22
- | **1** | Background runner & async robustness | T60–T62 | 0.5 ngày | P0 — chặn rủi ro silent fail |
23
- | **1** | Concurrency hard cap | T63 | 0.25 ngày | P0 — chặn user override DoS |
24
- | **2** | Resume durability cho synthesize/write | T64–T66 | 1 ngày | P1 — nâng cao reliability |
25
- | **2** | Adaptive planner repair/retry | T67 | 0.5 ngày | P1 — giảm block rate |
26
- | **2** | Model routing persistence | T68–T69 | 0.5 ngày | P1 — observability |
27
- | **3** | register.ts modularization | T70–T72 | 1 ngày | P2 — maintainability |
28
- | **3** | Subagent runtime consolidation | T73–T75 | 1.5 ngày | P2 — debt theo refactor map |
29
- | **3** | Skills builtin + docs self-contained | T76–T78 | 0.5 ngày | P3 — polish |
30
- | **4** | Tests, smoke, CHANGELOG | T79–T81 | 0.5 ngày | P0 (cuối phase) |
31
-
32
- Tổng: **22 task / ~6.25 ngày**, có thể ship theo nhiều mini-release (0.1.30, 0.1.31, …).
33
-
34
- ## Tiến độ triển khai
35
-
36
- | Task | Trạng thái | Commit / ghi chú |
37
- |---|---|---|
38
- | T60 | ✅ Done | `bfd9bc8` — jiti loader resolution/fail-fast |
39
- | T61 | ✅ Done | `bfd9bc8` — async early-exit guard |
40
- | T62 | ✅ Done | `bfd9bc8` — async startup marker |
41
- | T63 | ✅ Done | `bfd9bc8` — concurrency hard cap + opt-out |
42
- | T64 | ✅ Done | checkpoint phases + child-stdout-final/artifact-written resume recovery |
43
- | T65 | ✅ Done | async notifier marks quiet dead background runners failed with `async.died` |
44
- | T66 | ✅ Done | `5e495dc` — replay pending mailbox on resume |
45
- | T67 | ✅ Done | adaptive plan repair for malformed JSON, oversized plans, and role aliases |
46
- | T68 | ✅ Done | `1f92b8a` — persisted model routing metadata |
47
- | T69 | ✅ Done | `1f92b8a` — agent records carry routing metadata |
48
- | T70 | ✅ Done | `register.ts` split to ≤200 lines with commands, team tool, subagent tools, artifact cleanup modules |
49
- | T71 | ✅ Done | `team-tool.ts` split to ≤300 lines with status/inspect/lifecycle/cancel/plan modules |
50
- | T72 | ✅ Done | `task-runner.ts` split to ≤300 lines with prompt/progress/state/live/result helper modules |
51
- | T73 | ✅ Done | `src/subagents/*` entrypoints added and runtime call-sites migrated |
52
- | T74 | ✅ Done | live-session APIs routed through `src/subagents/live/*` with dynamic task-runner import |
53
- | T75 | ✅ Done | `1004589` + explicit subagent depth/role spawn tests |
54
- | T76 | ✅ Done | `f6ece8e` — built-in coding skills |
55
- | T77 | ✅ Done | `9e54acd` — self-contained architecture docs |
56
- | T78 | ✅ Done | `9e54acd` — runtime flow docs |
57
- | T79 | ✅ Done | multi-shard, no-wrapper spawn, and async restart recovery smokes covered |
58
- | T80 | ✅ Done | package snapshot guards docs/skills/jiti/pi manifest packaging |
59
- | T81 | ✅ Done | changelog release prep notes added; no publish/version bump performed |
60
-
61
- ---
62
-
63
- ## Tier 1 — Robustness chặn rủi ro silent fail (P0)
64
-
65
- ### Task #60 — `background-runner.ts` fail-fast nếu jiti loader không tồn tại
66
-
67
- **Lý do (evidence)**: `src/runtime/background-runner.ts` `getBackgroundRunnerCommand()` xây cứng đường dẫn:
68
- ```ts
69
- const jitiRegisterPath = path.join(packageRoot, "node_modules", "jiti", "lib", "jiti-register.mjs");
70
- return { args: ["--import", pathToFileURL(jitiRegisterPath).href, runnerPath, ...], loader: "jiti" };
71
- ```
72
- Nếu user xóa `node_modules/jiti` (npm prune, monorepo hoisting bất thường, broken install), `spawn(process.execPath, ...)` không fail ở Node parent — child sẽ exit lỗi ngay nhưng parent không capture được vì stdout đã `child.unref()` + đóng `logFd`. Background log chỉ chứa `[pi-crew] background loader=jiti` rồi im lặng. Run sẽ kẹt ở status `running` cho đến khi `process-status.hasStaleAsyncProcess` mark stale (>10 phút).
73
-
74
- **Đích**: `src/runtime/background-runner.ts`
75
-
76
- **Steps**:
77
- 1. Trước khi `spawn`, kiểm tra `fs.existsSync(jitiRegisterPath)`. Nếu thiếu → throw `Error` với message rõ ràng:
78
- ```
79
- pi-crew background runner cannot start: jiti loader not found at
80
- <jitiRegisterPath>. Reinstall pi-crew (`pi install npm:pi-crew`) or
81
- ensure node_modules/jiti is present.
82
- ```
83
- 2. Caller (`team-tool/run.ts` qua `spawnBackgroundTeamRun`) đã có try/catch — đảm bảo error propagate ra notify cho user.
84
- 3. Append error vào `events.jsonl` qua `appendEvent(eventsPath, { type: "async.failed", message })` trước khi throw.
85
- 4. Mở rộng: thêm fallback path tìm jiti trong `require.resolve.paths()` của parent module (Windows monorepo hoist) — nếu primary path missing thì thử `path.join(packageRoot, "..", "..", "node_modules", "jiti", "lib", "jiti-register.mjs")` (npm hoisting 2 cấp). Nếu cả hai miss thì mới throw.
86
-
87
- **Acceptance**:
88
- - Khi `node_modules/jiti/lib/jiti-register.mjs` thiếu → `spawnBackgroundTeamRun` throw với message hướng dẫn reinstall.
89
- - Khi user dùng monorepo hoisting (jiti ở root workspace) → vẫn resolve được.
90
- - `events.jsonl` có entry `async.failed` trước khi spawn.
91
- - Không regression với case có jiti (path 1 hit).
92
-
93
- **Tests**: `test/unit/background-runner.fail-fast.test.ts`
94
- - Stub `fs.existsSync` để giả lập miss → assert throw với pattern `/jiti loader not found/`.
95
- - Stub hoist path tồn tại → assert dùng path thay thế.
96
- - Cleanup không leak global state (`vi`-style spy + restore).
97
-
98
- **Verification**:
99
- ```bash
100
- npx tsc --noEmit
101
- node --experimental-strip-types --test test/unit/background-runner.fail-fast.test.ts
102
- ```
103
-
104
- **Risk/Rollback**: Risk thấp — chỉ thêm sanity check trước spawn. Rollback bằng cách revert commit.
105
-
106
- **Security/Perf notes**: Không I/O bổ sung trong hot path (chỉ 1 stat khi spawn background). Không log đường dẫn đầy đủ ở mức user message để tránh lộ home directory; dùng `shortenPath()` từ `utils/visual.ts` nếu có.
107
-
108
- ---
109
-
110
- ### Task #61 — Capture early-exit của background runner (drain `background.log`)
111
-
112
- **Lý do**: Hiện sau `child.unref(); fs.closeSync(logFd);` parent quên child. Nếu background-runner.ts lỗi cú pháp/import (không phải jiti missing nhưng vẫn fail), log chỉ chứa stderr Node. Status tool báo `Async: pid=X alive=false` sau khi process exit, nhưng manifest status vẫn `running`. User phải đợi `hasStaleAsyncProcess` (10 phút) mới detect.
113
-
114
- **Đích**: `src/extension/team-tool/run.ts` (caller) và `src/runtime/process-status.ts`
115
-
116
- **Steps**:
117
- 1. Trong caller, lưu `pid` ngay sau spawn. Schedule một check sau ~3s (`setTimeout` + `unref`) gọi `checkProcessLiveness(pid)`:
118
- - Nếu `alive=false` AND manifest vẫn `running` AND chưa có event `async.started` → đọc `background.log` (last 4KB), append event `async.failed` với log tail và `updateRunStatus(manifest, "failed", "Background runner exited within 3s; see background.log")`.
119
- 2. Cancel `setTimeout` nếu trong khoảng đó status đã chuyển khác `running`.
120
- 3. Đảm bảo không double-write status nếu background process đã write `async.failed` từ catch block.
121
-
122
- **Acceptance**:
123
- - Background runner exit ngay → run status chuyển `failed` trong ≤4s với reason có tail log.
124
- - Background runner chạy bình thường → không có false positive.
125
-
126
- **Tests**: `test/integration/background-early-exit.test.ts`
127
- - Mock `spawnBackgroundTeamRun` với child exit ngay (set `PI_TEAMS_MOCK_CHILD_PI=fail-immediate` + extend mock branch).
128
-
129
- **Verification**: `npm run test:integration -- background-early-exit`
130
-
131
- **Risk/Rollback**: Cần test kỹ với case async hợp lệ; rollback bằng feature flag `PI_CREW_ASYNC_EARLY_EXIT_GUARD=0`.
132
-
133
- ---
134
-
135
- ### Task #62 — `async.started` event timeout & marker file
136
-
137
- **Lý do**: Bổ sung `T61`. Background runner ghi `async.started` vào `events.jsonl` ở dòng đầu `main()`. Nếu file `events.jsonl` bị lock (Windows), event không append được. Caller hiện không có cơ chế chờ confirm.
138
-
139
- **Đích**: `src/runtime/async-runner.ts` + `src/runtime/background-runner.ts`
140
-
141
- **Steps**:
142
- 1. Background runner ghi marker file `state/runs/{runId}/async.pid` chứa `{pid, startedAt}` ngay sau khi `appendEvent("async.started")` thành công.
143
- 2. Caller (T61) khi healthcheck 3s đọc thêm marker file: nếu marker tồn tại → coi như runner đã start ổn.
144
- 3. Bổ sung `process-status.hasAsyncStartMarker(runId)`.
145
-
146
- **Acceptance**: Marker tồn tại sau khi async runner startup; healthcheck dùng marker khi events.jsonl không khả dụng (Windows lock fallback).
147
-
148
- **Tests**: unit cho `hasAsyncStartMarker` (file exists/missing/parse error).
149
-
150
- **Verification**: `npm run test:unit`
151
-
152
- ---
153
-
154
- ### Task #63 — Hard cap cho `limits.maxConcurrentWorkers`
155
-
156
- **Lý do**: `src/runtime/concurrency.ts.resolveBatchConcurrency()` dùng `limits.maxConcurrentWorkers` user truyền **không cap**. User config `limits.maxConcurrentWorkers=64` → 64 child Pi process spawn song song → DoS local. `parallel-utils.MAX_PARALLEL_CONCURRENCY=4` chỉ áp ở subagent runner cấp thấp, không bảo vệ scheduler.
157
-
158
- **Đích**: `src/runtime/concurrency.ts`, `src/config/defaults.ts`, `src/config/config.ts`
159
-
160
- **Steps**:
161
- 1. Thêm `DEFAULT_CONCURRENCY.hardCap = 8` vào `defaults.ts`.
162
- 2. Trong `resolveBatchConcurrency`, sau `requested = limitMax ?? teamMax ?? workflowMax ?? defaultWorkflowConcurrency`:
163
- ```ts
164
- const cap = positiveInteger(input.hardCap) ?? DEFAULT_CONCURRENCY.hardCap;
165
- const effective = Math.min(requested, cap);
166
- ```
167
- 3. Khi `effective < requested`, ghi `reason` thêm `;capped:${cap}` để observability.
168
- 4. Cho phép user opt-out qua `config.limits.allowUnboundedConcurrency=true` (gated qua warning event `limits.unbounded` + log dòng đầu run, default false).
169
- 5. Cập nhật `schema.json` + `config-schema.ts` cho field mới.
170
-
171
- **Acceptance**:
172
- - `limits.maxConcurrentWorkers=64` (default) → effective=8, reason chứa `capped:8`.
173
- - `limits.maxConcurrentWorkers=64, allowUnboundedConcurrency=true` → effective=64, có event warning.
174
- - Không regression cho values hợp lý (≤8).
175
-
176
- **Tests**: `test/unit/concurrency.cap.test.ts`
177
- - 4 case: requested=2 (no cap), requested=12 (cap=8), unbounded flag (no cap), workflow=parallel-research workflowMax=4 (no cap).
178
-
179
- **Verification**: `npx tsc --noEmit && node --experimental-strip-types --test test/unit/concurrency.cap.test.ts`
180
-
181
- **Risk/Rollback**: Có thể vô tình giảm throughput cho user power-user. Mitigate bằng `allowUnboundedConcurrency` flag. Rollback: revert + bump major nếu user đã dựa vào behavior cũ (chưa rõ).
182
-
183
- **Security/Perf notes**: Bảo vệ memory/cpu local; mỗi child Pi consume ~200MB RAM. 8 = 1.6GB worst case, hợp lý cho dev machine.
184
-
185
- ---
186
-
187
- ## Tier 2 — Reliability nâng cao (P1)
188
-
189
- ### Task #64 — Resume detection: synthesize/write checkpoint
190
-
191
- **Lý do**: `team-runner.executeTeamRun` không biết task synthesize/write đã completed một phần khi crash giữa chừng. Khi resume (`team resume runId`), task `synthesize` re-run từ đầu, gọi LLM lại tốn cost. Risk #5 trong test report.
192
-
193
- **Đích**: `src/runtime/task-runner.ts`, `src/state/state-store.ts`, `src/state/types.ts`
194
-
195
- **Steps**:
196
- 1. Mở rộng `TeamTaskState` thêm `checkpoint?: { phase: "started" | "child-spawned" | "child-stdout-final" | "artifact-written"; updatedAt: string; childPid?: number }`.
197
- 2. `runTeamTask` ghi checkpoint qua `saveRunTasks` ở 4 điểm:
198
- - Trước `runChildPi` (`started`)
199
- - Sau `child.pid` có (`child-spawned` + pid)
200
- - Khi nhận `isFinalAssistantEvent` (`child-stdout-final`)
201
- - Sau `writeArtifact` (`artifact-written`)
202
- 3. `team-tool.handleResume` xét checkpoint:
203
- - Nếu `checkpoint.phase === "artifact-written"` mà status vẫn `running` → mark `completed` (recovery, không re-run).
204
- - Nếu `checkpoint.phase === "child-stdout-final"` → cố parse output từ `transcripts/{taskId}.jsonl` last lines, nếu có valid `message_end` thì mark `completed` mà không re-spawn.
205
- - Else → re-queue.
206
-
207
- **Acceptance**:
208
- - Crash sau khi artifact ghi xong → resume mark `completed` không re-run LLM.
209
- - Crash giữa stdout streaming → resume cố recover từ transcript; nếu không thành công thì re-run.
210
- - State migration backward-compat (task cũ không có `checkpoint` → resume hoạt động như cũ).
211
-
212
- **Tests**: `test/integration/resume-checkpoint.test.ts`
213
- - 3 case: pre-spawn crash, mid-stream crash, post-artifact crash.
214
-
215
- **Verification**: `npm run test:integration -- resume-checkpoint`
216
-
217
- **Risk/Rollback**: Touch durable state shape. Cần migration: nếu task không có `checkpoint`, treat như chưa start. Rollback: revert + xóa field optional khỏi types.
218
-
219
- ---
220
-
221
- ### Task #65 — Resume cho async background run sau parent crash
222
-
223
- **Lý do**: Khi parent Pi session crash, background runner vẫn chạy; manifest cập nhật bình thường. Nhưng nếu **background runner crash** (ví dụ jiti corrupted, OOM), không có ai mark run failed cho đến `hasStaleAsyncProcess` 10 phút sau. Status sẽ misleading.
224
-
225
- **Đích**: `src/runtime/process-status.ts`, `src/extension/async-notifier.ts`
226
-
227
- **Steps**:
228
- 1. Mở rộng `async-notifier.ts.startAsyncRunNotifier`: với mỗi run đang `running`, mỗi `notifierIntervalMs` (5s) check `checkProcessLiveness(async.pid)`. Nếu `alive=false` VÀ run status `running` AND không có event nào trong 30s gần nhất → `updateRunStatus(manifest, "failed", "Background runner died unexpectedly; check background.log")`.
229
- 2. Bổ sung guard: chỉ thực hiện nếu chưa có event `async.completed`/`async.failed` (avoid double-write).
230
-
231
- **Acceptance**: Background runner kill -9 → trong ≤30s status chuyển `failed`, có event `async.died`.
232
-
233
- **Tests**: `test/integration/async-died.test.ts` (mock spawn process exit ngẫu nhiên).
234
-
235
- **Verification**: `npm run test:integration -- async-died`
236
-
237
- **Risk/Rollback**: False positive khi event log chậm flush. Mitigate: chỉ trigger khi không alive AND last event > 30s. Rollback: revert async-notifier hook.
238
-
239
- ---
240
-
241
- ### Task #66 — Mailbox replay khi resume
242
-
243
- **Lý do**: `state/mailbox` có inbox/outbox JSONL nhưng resume không re-deliver pending messages. Risk #5 mở rộng.
244
-
245
- **Đích**: `src/state/mailbox.ts`, `src/extension/team-tool/api.ts`
246
-
247
- **Steps**:
248
- 1. Khi resume, đọc `mailbox/delivery.json`. Mọi message `direction=inbox` chưa `acked=true` → re-emit trong batch đầu.
249
- 2. Add `validate-mailbox repair=true` vào doctor checks để cleanup stale messages > 7 ngày.
250
-
251
- **Acceptance**: Resume sau crash giữa khi mailbox có 3 message pending → 3 message được redelivered.
252
-
253
- **Tests**: `test/unit/mailbox-replay.test.ts`
254
-
255
- **Verification**: `npm run test:unit`
256
-
257
- ---
258
-
259
- ### Task #67 — Adaptive planner repair/retry trước khi block
260
-
261
- **Lý do**: `team-runner.injectAdaptivePlanIfReady` block ngay khi `__test__parseAdaptivePlan` fail (oversize >12 task / JSON malformed / role không hợp lệ). User phải re-run từ đầu. Refactor map đã ghi nhận: "Add adaptive planner repair/retry for invalid JSON instead of immediate block when safe."
262
-
263
- **Đích**: `src/runtime/team-runner.ts`, `agents/planner.md`
264
-
265
- **Steps**:
266
- 1. Khi parse fail, thay vì return `missingPlan: true` ngay, thử **repair**:
267
- - Nếu JSON malformed → spawn 1 child Pi tiny (planner role, model rẻ — Haiku/gpt-5-nano) với prompt: `Fix the following JSON to comply with the adaptive plan schema. Return only ADAPTIVE_PLAN_JSON_START ... ADAPTIVE_PLAN_JSON_END.\n<failed_text>`. Cap retry = 1, timeout 60s.
268
- - Nếu oversize (>12 task) → tự trim phases tail tới ≤12 task, ghi event `adaptive.plan_trimmed`.
269
- - Nếu role không hợp lệ → map sang role gần nhất (`reviewer`→`code-reviewer` nếu team có) hoặc skip task đó nếu phase không trống.
270
- 2. Nếu repair fail → mới block (giữ behavior hiện tại). Ghi event `adaptive.plan_repair_failed`.
271
- 3. Persist repair attempt vào `metadata/adaptive-repair.json` để debug.
272
-
273
- **Acceptance**:
274
- - Plan JSON malformed nhỏ (thiếu `}`) → repair fix → run tiếp.
275
- - Plan 15 task → trim còn 12, run tiếp với warning.
276
- - Plan với role lạ → map hoặc skip task; nếu không cứu được thì block với explain rõ ràng.
277
-
278
- **Tests**: `test/unit/adaptive-repair.test.ts` (3 fixture: malformed, oversize, invalid-role).
279
-
280
- **Verification**: `npm run test:unit -- adaptive-repair`
281
-
282
- **Risk/Rollback**: Có thể ăn thêm 1 model call. Mitigate: chỉ retry khi cost < 0.001 USD ước tính (Haiku tier). Rollback: env `PI_CREW_ADAPTIVE_REPAIR=0`.
283
-
284
- ---
285
-
286
- ### Task #68 — Persist model routing (requested → selected → fallback chain → reason)
287
-
288
- **Lý do**: Refactor map: "Move model routing transparency into persisted task/subagent records: requested model, selected model, fallback chain, fallback reason." Hiện task state chỉ có `modelAttempts: ModelAttemptSummary[]` (model + success + error) nhưng không persist `requestedModel` ban đầu user/agent yêu cầu, cũng như reason vì sao chuyển fallback.
289
-
290
- **Đích**: `src/runtime/model-fallback.ts`, `src/state/types.ts`, `src/runtime/task-runner.ts`
291
-
292
- **Steps**:
293
- 1. Mở rộng `TeamTaskState.modelRouting?: { requested?: string; resolved: string; fallbackChain: string[]; reason?: string; usedAttempt: number }`.
294
- 2. `buildConfiguredModelCandidates` trả thêm `requestedModel` (model agent.md / step.model trước fallback).
295
- 3. `runTeamTask` write `modelRouting` cùng `modelAttempts`.
296
- 4. `team-tool.handleStatus` render section `Model routing:` nếu có. Dashboard agent rows hiển thị `model · ≥requested:claude-sonnet-4-5 → openai-codex/gpt-5.5 (rate-limit)`.
297
-
298
- **Acceptance**:
299
- - Task chạy thành công lần 1 → `usedAttempt=0`, `fallbackChain` chứa chain config (không cần markFallback).
300
- - Task fallback từ A → B vì rate-limit → `reason: "rate-limit"`, `usedAttempt=1`.
301
- - Status output có dòng `Model routing` cho mỗi task có routing data.
302
-
303
- **Tests**: `test/unit/model-routing.test.ts`
304
-
305
- **Verification**: `npm run test:unit`
306
-
307
- **Risk/Rollback**: Task state shape mở rộng — backward-compat (field optional). Rollback: revert types + hide UI.
308
-
309
- ---
310
-
311
- ### Task #69 — Subagent records lưu model routing
312
-
313
- **Lý do**: Liên quan T68 nhưng cho `crew-agent-records` (file-backed agent status hiển thị ở dashboard). Hiện chỉ có `model` field (latest selected); cần `requestedModel` + `fallbackChain`.
314
-
315
- **Đích**: `src/runtime/crew-agent-records.ts`
316
-
317
- **Steps**:
318
- 1. Mở rộng `CrewAgentRecord` thêm `routing?: TeamTaskState["modelRouting"]`.
319
- 2. `recordFromTask` map từ `task.modelRouting`.
320
- 3. `live-run-sidebar` render `routing` ở chỗ model row.
321
-
322
- **Tests**: snapshot trong `test/unit/crew-agent-records.test.ts`.
323
-
324
- **Verification**: `npm run test:unit`
325
-
326
- ---
327
-
328
- ## Tier 3 — Maintainability & debt cleanup (P2)
329
-
330
- ### Task #70 — Tách `register.ts` thành sub-modules theo lifecycle
331
-
332
- **Lý do**: `src/extension/register.ts` ~38KB trộn: lifecycle, RPC, manifest cache, foreground controller, sidebar, widget, mascot, command parsing, subagent manager, viewers. Quy tắc AGENTS.md "Keep `index.ts` minimal; register functionality from `src/extension/register.ts`. Prefer small modules over large orchestrator files." Đã có sub-folders `registration/` + `team-tool/` nhưng register.ts vẫn lớn.
333
-
334
- **Đích**: `src/extension/register.ts` → split
335
-
336
- **Steps**:
337
- 1. Tách thành 5 module:
338
- - `src/extension/registration/lifecycle.ts` — session_start/session_before_switch/session_shutdown handlers + cleanupRuntime.
339
- - `src/extension/registration/widget-loop.ts` — widget interval, sidebar lifecycle (`openLiveSidebar`, `liveSidebarTimer`).
340
- - `src/extension/registration/foreground-runner.ts` — `startForegroundRun` + `foregroundControllers`.
341
- - `src/extension/registration/subagent-tools.ts` — Agent/get_subagent_result/steer_subagent + crew_* aliases.
342
- - `src/extension/registration/commands.ts` — đăng ký toàn bộ slash command (`/teams`, `/team-run`, …).
343
- 2. `register.ts` còn lại chỉ là wiring (≤200 dòng): tạo state, gọi các module.
344
- 3. Giữ public API (export `registerPiTeams`, `__test__subagentSpawnParams`).
345
-
346
- **Acceptance**:
347
- - `register.ts` ≤200 dòng.
348
- - Mỗi module mới ≤300 dòng.
349
- - Tests cũ pass không thay đổi.
350
- - Thêm test snapshot cho commands list (đảm bảo không drop command nào).
351
-
352
- **Tests**: `test/unit/registration.commands-coverage.test.ts` (assert 25 commands đăng ký).
353
-
354
- **Verification**: `npx tsc --noEmit && npm run test`
355
-
356
- **Risk/Rollback**: Refactor lớn — risk regression. Mitigate: tách từng commit nhỏ (1 module / commit). Rollback: revert lần lượt.
357
-
358
- ---
359
-
360
- ### Task #71 — Tách `team-tool.ts` actions còn lại
361
-
362
- **Lý do**: `src/extension/team-tool.ts` ~32KB. Đã có `team-tool/{api,run,doctor}.ts`. Còn `handleStatus`, `handleEvents`, `handleArtifacts`, `handleWorktrees`, `handleResume`, `handleCancel`, `handleSummary`, `handleCleanup`, `handleForget`, `handlePrune`, `handleExport`, `handleImport`, `handleImports` ở file chính.
363
-
364
- **Đích**: `src/extension/team-tool.ts` → split
365
-
366
- **Steps**:
367
- 1. Tạo `src/extension/team-tool/{status,events,artifacts,resume,lifecycle-actions}.ts`.
368
- 2. `team-tool.ts` chỉ giữ router (`handleTeamTool`) + `handleList`/`handleGet` (đã ngắn).
369
-
370
- **Acceptance**: `team-tool.ts` ≤300 dòng. Mỗi sub-module ≤300 dòng.
371
-
372
- **Tests**: existing pass.
373
-
374
- **Verification**: `npm run test`
375
-
376
- ---
377
-
378
- ### Task #72 — Tách `task-runner.ts`
379
-
380
- **Lý do**: `src/runtime/task-runner.ts` ~28KB chứa: prompt building, child-pi orchestration, artifact writing, verification evidence, transcripts, retry logic, mailbox bridge.
381
-
382
- **Đích**: split thành:
383
- - `task-runner/prompt-builder.ts` (renderTaskPrompt + readOnlyRoleInstructions + coordinationBridgeInstructions).
384
- - `task-runner/artifact-writer.ts` (writeTaskInputs/Outputs/Transcripts/Diff).
385
- - `task-runner/retry.ts` (model fallback retry loop).
386
- - `task-runner/index.ts` exports `runTeamTask`.
387
-
388
- **Acceptance**: Mỗi module ≤300 dòng. Public function signature không đổi.
389
-
390
- **Tests**: existing pass + snapshot prompt cho mỗi role (4 role).
391
-
392
- **Verification**: `npm run test:integration -- task-runner`
393
-
394
- ---
395
-
396
- ### Task #73 — Consolidate `child-pi` + `async-runner` + `subagent-manager` thành `src/subagents/`
397
-
398
- **Lý do**: Refactor map (đã ghi nhận từ Phase 0): "Consolidate subagent runtime into `src/subagents/*` or equivalent durable-first module." Hiện 3 file rải rác:
399
- - `src/runtime/child-pi.ts` (435 dòng) — spawn pi CLI con
400
- - `src/runtime/async-runner.ts` (~50 dòng) — entrypoint background
401
- - `src/runtime/subagent-manager.ts` (~290 dòng) — Agent tool backend
402
-
403
- **Đích**: tạo folder `src/subagents/` chứa:
404
- - `src/subagents/spawn.ts` (lift từ child-pi.ts)
405
- - `src/subagents/observer.ts` (ChildPiLineObserver + compactor)
406
- - `src/subagents/manager.ts` (lift từ subagent-manager.ts)
407
- - `src/subagents/async-entry.ts` (lift từ async-runner.ts)
408
- - `src/subagents/index.ts` re-export public API
409
-
410
- Để các file `runtime/child-pi.ts` thành thin re-export (deprecated path) cho 1–2 release rồi xóa.
411
-
412
- **Acceptance**:
413
- - Import paths cũ vẫn hoạt động (re-export shim).
414
- - Không thay đổi logic; chỉ move + group.
415
- - Tests cũ pass.
416
-
417
- **Tests**: existing.
418
-
419
- **Verification**: `npm run ci`
420
-
421
- **Risk/Rollback**: Nhiều file đổi import. Mitigate: làm bằng IDE rename/move chứ không edit thủ công. Rollback: revert.
422
-
423
- ---
424
-
425
- ### Task #74 — Tách live-session runtime khỏi child-process
426
-
427
- **Lý do**: `src/runtime/live-session-runtime.ts` (~14KB) gating sau cờ experimental, nhưng vẫn import từ `task-runner` chính. Nếu mai có người bật `PI_CREW_ENABLE_EXPERIMENTAL_LIVE_SESSION`, code path xen lẫn dễ break.
428
-
429
- **Đích**: di chuyển `live-session-runtime.ts` + `live-agent-control/manager` + `live-agent-control-realtime.ts` vào `src/subagents/live/` (subdirectory mới của T73).
430
-
431
- **Acceptance**: `runtime/runtime-resolver.ts` chỉ phụ thuộc qua `subagents/live`. Default flow (child-process) không import live module.
432
-
433
- **Tests**: existing.
434
-
435
- ---
436
-
437
- ### Task #75 — Subagent depth/permission hardening
438
-
439
- **Lý do**: `pi-args.checkCrewDepth` đã check `PI_CREW_DEPTH` env. Cần test thêm: subagent gọi recursive (Agent tool trong agent) > maxDepth → block + clear message.
440
-
441
- **Đích**: `src/subagents/manager.ts`, `src/runtime/pi-args.ts`
442
-
443
- **Steps**:
444
- 1. Add explicit test cho recursive spawn.
445
- 2. Bổ sung `role-permission.ts` để chặn agent có role `read_only` không được gọi tool `Agent`/`crew_agent`.
446
-
447
- **Tests**: `test/unit/subagent-depth.test.ts`, `test/unit/role-permission.spawn.test.ts`.
448
-
449
- **Verification**: `npm run test:unit`
450
-
451
- ---
452
-
453
- ## Tier 3 — Polish (P3)
454
-
455
- ### Task #76 — Skills builtin: extract từ `Source/awesome-agent-skills` + adapt
456
-
457
- **Lý do**: `pi.skills` trong package.json khai báo `./skills` nhưng folder chỉ có `.gitkeep`. Có thể adapt 5–10 skill cốt lõi từ `Source/awesome-agent-skills/README.md`, `Source/oh-my-claudecode/skills/`, `Source/superpowers/`.
458
-
459
- **Đích**: `skills/`
460
-
461
- **Steps**:
462
- 1. Chọn 5 skill phù hợp coding:
463
- - `safe-bash` (gate dangerous commands)
464
- - `verify-evidence` (final assistant must include changed files + verification)
465
- - `git-master` (commit hygiene + Conventional Commits)
466
- - `read-only-explorer` (forbid edits when role is explorer/analyst)
467
- - `task-packet` (enforce scope/inputs/outputs section)
468
- 2. Mỗi skill là file `.md` trong `skills/{name}/SKILL.md` + optional helper scripts.
469
- 3. Adapt mà không copy nguyên văn (giữ MIT compliance + ghi nguồn trong NOTICE.md).
470
- 4. Reference từ `agents/*.md` qua `skills: safe-bash, verify-evidence` frontmatter.
471
-
472
- **Acceptance**:
473
- - 5 skill files ≤500 dòng mỗi file.
474
- - NOTICE.md cập nhật source attribution.
475
- - Test discovery: `discover-skills.ts` (có chưa? — bổ sung nếu chưa có) trả về 5.
476
-
477
- **Tests**: `test/unit/skills.discovery.test.ts`.
478
-
479
- **Verification**: `npm run test:unit -- skills.discovery`
480
-
481
- **Risk/Rollback**: Có thể inflate package size. Mitigate: skills nhỏ ≤4KB mỗi cái.
482
-
483
- ---
484
-
485
- ### Task #77 — `docs/architecture.md` self-contained
486
-
487
- **Lý do**: `pi-teams/docs/architecture.md` hiện trỏ ra `../docs/pi-crew-source-review-and-lessons.md`, `../docs/pi-crew-architecture.md`, `../docs/pi-crew-mvp-plan.md` — các file nằm ngoài package, sẽ broken khi npm publish.
488
-
489
- **Đích**: `pi-teams/docs/architecture.md`
490
-
491
- **Steps**:
492
- 1. Inline nội dung kiến trúc cốt lõi (3 layer: extension/runtime/state, lifecycle diagram, durable run state, autonomous routing).
493
- 2. Bỏ reference ra file workspace bên ngoài.
494
- 3. Thêm sequence diagram ASCII cho run flow (extension → team-runner → task-runner → child-pi → state).
495
- 4. Liên kết tới `usage.md`, `resource-formats.md`, `live-mailbox-runtime.md`, `publishing.md` (đều trong package).
496
-
497
- **Acceptance**:
498
- - File ≤600 dòng, không link out-of-package.
499
- - `npm pack --dry-run` ship đầy đủ docs/.
500
-
501
- **Verification**: manual review + `npm pack --dry-run`.
502
-
503
- ---
504
-
505
- ### Task #78 — `docs/runtime-flow.md` (mới) + sequence diagram
506
-
507
- **Lý do**: Onboarding contributor cần một biểu đồ/text mô tả full flow. Hiện rải rác giữa architecture.md, source-runtime-refactor-map.md, refactor-tasks.md.
508
-
509
- **Đích**: tạo mới `pi-teams/docs/runtime-flow.md`
510
-
511
- **Steps**:
512
- 1. ASCII sequence diagram: user → handleTeamTool(run) → executeTeamRun → resolveBatchConcurrency → runTeamTask → runChildPi → child stdout → ChildPiLineObserver → onJsonEvent → updateRunStatus → notify.
513
- 2. Bảng "trigger → handler" cho mỗi action (`run`, `resume`, `cancel`, ...).
514
- 3. Liệt kê env var ảnh hưởng (`PI_TEAMS_*`, `PI_CREW_*`, `PI_CODING_AGENT_DIR`).
515
-
516
- **Acceptance**: Document ≤400 dòng, tự đứng được không cần đọc thêm.
517
-
518
- ---
519
-
520
- ## Tier 4 — Tests, smoke, release (P0 cuối phase)
521
-
522
- ### Task #79 — Integration smoke: Windows process visibility + multi-shard fanout
523
-
524
- **Lý do**: Refactor map: "Add real integration smoke scripts for Windows process visibility, async restart recovery, and multi-shard fanout." Test report user vừa gửi đã chứng minh fanout chạy được, nhưng cần script lặp lại được.
525
-
526
- **Đích**: `test/integration/`
527
-
528
- **Steps**:
529
- 1. `test/integration/windows-no-blank-console.test.ts`: spawn `pi --version` qua `pi-spawn.getPiSpawnCommand` với `windowsHide:true` → assert process spawned, no console window (heuristic: `child.spawnargs` không chứa `cmd /c start`).
530
- 2. `test/integration/multi-shard-fanout.test.ts`: dùng `expandParallelResearchWorkflow` với fixture `Source/pi-*` mock (5 thư mục dummy) → assert 4 shard sinh ra, mỗi shard có ≥1 path, dependency synthesize đúng tất cả shard.
531
- 3. `test/integration/async-restart-recovery.test.ts`: spawn background, kill -9, gọi `team status` → mark failed trong ≤30s (T65 dependency).
532
-
533
- **Acceptance**: 3 test pass trên Windows runner CI.
534
-
535
- **Verification**: `npm run test:integration`
536
-
537
- ---
538
-
539
- ### Task #80 — Update `npm pack --dry-run` snapshot + `schema.json`
540
-
541
- **Lý do**: Sau khi thêm config field (T63 `allowUnboundedConcurrency`), `schema.json` exported và `config-schema.ts` cần đồng bộ.
542
-
543
- **Đích**: `schema.json`, `src/schema/config-schema.ts`
544
-
545
- **Steps**:
546
- 1. Regenerate `schema.json` từ TypeBox schema (script `scripts/generate-schema.ts` nếu có; nếu không thì update manually + diff review).
547
- 2. `npm pack --dry-run` capture file list, snapshot vào test (`test/unit/package-files.test.ts`).
548
-
549
- **Acceptance**: schema.json reflect mọi field config; snapshot test verify không drop file ship.
550
-
551
- ---
552
-
553
- ### Task #81 — CHANGELOG + release prep
554
-
555
- **Lý do**: Theo AGENTS.md global Section 2, mỗi PR cần Files & Rationale + Tests + Risks/Rollback. Phase 6 sẽ ship qua nhiều mini-release.
556
-
557
- **Đích**: `CHANGELOG.md`
558
-
559
- **Steps**:
560
- 1. Thêm sections theo nhóm Tier:
561
- - `## 0.1.30 — async/concurrency hardening` (T60–T63, T79).
562
- - `## 0.1.31 — resume durability + adaptive repair` (T64–T67).
563
- - `## 0.1.32 — model routing observability` (T68–T69).
564
- - `## 0.2.0 — refactor: subagent runtime + register split` (T70–T75) — minor bump vì internal API thay đổi.
565
- - `## 0.2.1 — skills + docs` (T76–T78).
566
- 2. Mỗi entry follow format: `### Added / Changed / Fixed / Breaking Changes`.
567
-
568
- **Acceptance**: CHANGELOG đầy đủ; `npm version` script chạy clean.
569
-
570
- ---
571
-
572
- ## Phụ lục A — Acceptance gate cho mỗi mini-release
573
-
574
- Trước khi tag/publish:
575
-
576
- ```bash
577
- # Hard gate
578
- npm run typecheck
579
- npm run test:unit
580
- npm run test:integration
581
- npm pack --dry-run
582
-
583
- # Soft gate (manual)
584
- /team-doctor # in Pi smoke session
585
- /team-validate
586
- /team-autonomy status
587
-
588
- # Cross-platform
589
- # Trigger CI ubuntu/windows/macos workflow trước khi tag
590
- ```
591
-
592
- ## Phụ lục B — Bảng phụ thuộc giữa task
593
-
594
- ```
595
- T60 ──► T61 ──► T62
596
-
597
- T63 (độc lập) ──┘
598
- T64 ──► T65 ──► T66
599
- T67 (độc lập)
600
- T68 ──► T69
601
- T70 ──► T71 ──► T72
602
- T73 ──► T74 ──► T75 (cần T70 ổn định trước)
603
- T76 (độc lập)
604
- T77 ──► T78
605
- T79 phụ thuộc T63 (concurrency cap), T65 (async-died)
606
- T80 phụ thuộc T63
607
- T81 sau cùng
608
- ```
609
-
610
- ## Phụ lục C — Ánh xạ mỗi task ↔ rủi ro/follow-up đã nêu
611
-
612
- | Task | Nguồn yêu cầu |
613
- |---|---|
614
- | T60–T62 | Test report risk #2 + Phase analysis "fail-fast nếu jiti fail" |
615
- | T63 | Test report risk #4 |
616
- | T64–T66 | Test report risk #5 + refactor map "async restart recovery" |
617
- | T67 | refactor-map "adaptive planner repair/retry" |
618
- | T68–T69 | refactor-map "model routing transparency persisted" |
619
- | T70–T72 | AGENTS.md "small modules" + analysis "register.ts/team-tool.ts/task-runner.ts cồng kềnh" |
620
- | T73–T75 | refactor-map "consolidate subagent runtime into src/subagents/*" |
621
- | T76 | analysis "skills/ trống" |
622
- | T77–T78 | analysis "doc kiến trúc trỏ ra ngoài package" + onboarding |
623
- | T79 | refactor-map "real integration smoke scripts" |
624
- | T80–T81 | release hygiene |
625
-
626
- ## Phụ lục D — "Reply with" template cho mỗi PR
627
-
628
- Mỗi PR Phase 6 phải tuân thủ AGENTS.md Section 10:
629
-
630
- ```
631
- Summary: <1 dòng impact>
632
- Plan:
633
- - <bước 1>
634
- - <bước 2>
635
-
636
- Files & Rationale:
637
- - src/.../...: <lý do>
638
-
639
- Tests:
640
- - <test name>: <kịch bản>
641
-
642
- Verification:
643
- - npx tsc --noEmit → Passed
644
- - npm run test:unit → 0 failed / N passed
645
- - npm run test:integration → 0 failed / N passed
646
- - npm pack --dry-run → file list match snapshot
647
-
648
- Risks & Rollback:
649
- - <rủi ro>
650
- - <feature flag / revert plan>
651
-
652
- Security & Perf Notes:
653
- - <OWASP / RAM / IO>
654
- ```
655
-
656
- ---
657
-
658
- **Khuyến nghị triển khai**:
659
- 1. Đi theo thứ tự Tier (P0 → P3); không pha trộn refactor lớn (T70–T75) với hardening (T60–T67).
660
- 2. Mỗi Tier ship 1 mini-release để có baseline ổn định trước Tier kế.
661
- 3. Trước Tier 3 (T70–T75) chạy full test trên CI Windows + macOS để bắt regression cross-platform.
662
- 4. Sau mỗi task: chạy `/team-doctor` trong Pi session để smoke; mở dashboard `/team-dashboard` xác nhận không stale.